Results 1 to 20 of 23
Thread: questions about coding standards
- 09-17-2010, 12:03 AM #1
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
questions about coding standards
I'm trying to clean up my code and comform it to Java standards. A few questions:
What does one typically do (according to the coding standards) about initializing class variables? For example, is this OK:
or is this better:Java Code:public class MyClass { private int n = 1; private char[] char_array = new char[10]; public static final double MY_DOUBLE = 0.05; public MyClass(int num) { n = num; for (int i = 0; i < 10; i++) { char_array[i] = 'X'; } } }
Another question:Java Code:public class MyClass { private int n; private char[] char_array; public static final double MY_DOUBLE = 0.05; // must be initialized here public MyClass(int num) { n = num; char_array = new char[10]; for (int i = 0; i < 10; i++) { char_array[i] = 'X'; } } }
I know the standards say that the consequent of an if statement (what it does if the condition is met) must go one line below the condition and be indented, but what if I have something really short such as this:
To me, it just seem neater if I put it all on one line.Java Code:if (b) x++;
I do something similar for really short accessor methods:
I have other questions but we'll start with these. All answers are greatly appreciated. Thanks!Java Code:// get public int getNumber() {return number;} public String getStr() {return str;} public boolean getBool() {return bool;} // set public void setNumber(int n) {number = n;} public void setStr(String s) {str = s;} public void setBool(boolean b) {bool = b;}Last edited by gib65; 09-17-2010 at 12:05 AM.
- 09-17-2010, 01:24 AM #2
You'll find the official version here:
Code Conventions for the Java(TM) Programming Language: Contents
Apart from thatNot necessarily. A final field must be initialized either at declaration or before the end of every constructor.Java Code:public static final double MY_DOUBLE = 0.05; // must be initialized here
Classes
db
- 09-17-2010, 02:05 AM #3
vsprivate char[] char_array = new char[10];
private char[] char_array = {'X', 'X', 'X', ..7 more}; // Initialize at compile time vs execution time
Problem is: everyone is used to looking after the if statement to see the body of code to be executed.it just seem neater if I put it all on one line.
When on the same line you have to scan it several times to see if it is part of the condition being tested by the if or what it is.
Possible confusion is more important to avoid than to be "neat".Last edited by Norm; 09-17-2010 at 02:08 AM.
- 09-17-2010, 04:53 AM #4
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
Thanks both,
I will take that under advisement.
My next question has to do with checking for errors. I make a point about testing the variables that are passed in to a method. For example, I have this simple method for a video game I'm programming:
I think this goes against certain standards which would have all variable declarations, like "GoodGuy goodGuy = gameControl.getGoodGuy();", at the beginning of the method before anything else. But the way I see it, if there are any errors with the variables passed in, declaring/initializing variables would be a waste of time. Might as well get the error checking out of the way first before declaring/initializing variables.Java Code:public void acquire(Ball b) { if (b == null) { System.out.println("b is null in GoodGuy.acquire(Ball)."); System.exit(0); } GoodGuy goodGuy = gameControl.getGoodGuy(); // ... }
Does this make sense?
- 09-17-2010, 05:11 AM #5
I'm not sure how many of the more senior members will agree or disagree with me here, but honestly, I value efficient and neat code over coding conventions. So your variable is declared later, it's not going to detriment your code beyond workability.
If a code is workable, and understandable, and can be interpreted by another human being with fairly good ease and flow, then it's good.
That's just my $0.02... not sure what it's actually worth. ;)
- 09-17-2010, 05:44 AM #6
I believe coding conventions is for making neat and efficient code. But not necessarily, I may follow conventions every time.I value efficient and neat code over coding conventions
yeah, if any of my pal says "Hey mate, I don't understand flow in your code!", then I would have to toil extra, just trying correct it.If a code is workable, and understandable, and can be interpreted by another human being with fairly good ease and flow, then it's good.
- 09-17-2010, 06:25 AM #7
I don't believe this; look at this coding convention from the link above:
So let's now imagine you have several statements using || conjoining. It's going to look hideous and ugly with them all nested in brackets, which means you either:Java Code:if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT
A) Go against conventions. (YEA! Stick it to da man!)
B) Nest statements (if &&), or add multiple if statements successively (if ||). (Ugly. :()
So, there's just one example. One for efficiency would be the point the OP made above about declaring the variable.
Part of programming on your part is knowing whether the code can be understood. Part of programming on his part is knowing that he needs to be able to understand code. It's a bit symbiotic, and it's not a perfect system--even with conventions.
- 09-17-2010, 09:12 AM #8
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
What you're talking about there is an assertion...use the assert keyword for it, which will throw an AssertionError, which you can attach a message to.
Also, you declare variables when you need them. No point decalring a load of stuff at the top of the method if the first thing that happens is an assertion fails and you exit the method. Complete waste of time.
- 09-17-2010, 09:21 AM #9
Moderator
- Join Date
- Apr 2009
- Posts
- 10,481
- Rep Power
- 16
- 09-17-2010, 04:43 PM #10
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
Thanks Tolls,
However, there is a section in the link you provided that says this:
This is exactly what I'm trying to do (if I understand correctly) - checking for errors in the arguments passed to my methods.Do not use assertions for argument checking in public methods.
Argument checking is typically part of the published specifications (or contract) of a method, and these specifications must be obeyed whether assertions are enabled or disabled. Another problem with using assertions for argument checking is that erroneous arguments should result in an appropriate runtime exception (such as IllegalArgumentException, IndexOutOfBoundsException, or NullPointerException). An assertion failure will not throw an appropriate exception
The above quote says nothing, however, about private methods, but I have very few private methods in my code.
- 09-17-2010, 11:43 PM #11
If the code is running in a GUI launched by javaw, there isn't a console and the sysout won't be seen. All that will happen is that the program will suddenly exit. If explicit checking for a null value is really needed you can throw a NullPointerException.
Alternatively, you can scrap the null test and just allow a NullPointerException to be thrown whenever you try to dereference b. The stack trace will show the path of execution.Java Code:public void acquire(Ball b) { if (b == null) { // System.out.println("b is null in GoodGuy.acquire(Ball)."); // System.exit(0); throw new NullPointerException("Ball cannot be null"); } GoodGuy goodGuy = gameControl.getGoodGuy(); // ... }
sv
- 09-17-2010, 11:47 PM #12
- 09-18-2010, 12:51 AM #13
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
- 09-18-2010, 01:00 AM #14
States? You mean, "if ((object A has some value) && (object B has some value))"? Not sure exactly what you're driving at.
Of course. And I do agree that splitting the if statement onto multiple lines can be used. However the point simply is that the coding conventions are more of a guideline than an actual set of rules.
Here is a line from a game I'm developing...
Edit: I see the code box actually isn't wide enough to handle this. Neat-o! :DJava Code:if ((this.m_Cap == 0) || (this.m_Cap > 0 && this.Size() >= this.m_Cap && this.m_Array[this.m_Cap - 1] != null)) return this;
Now, that's pretty darn ugly. And I have an excess set of brackets on the first condition; but the && statements are not surrounded by them. And since this statement isn't wider than my screen, I don't bother to put it on multiple lines. So it doesn't always pay to follow those conventions. ;)
- 09-18-2010, 01:08 AM #15
Senior Member
- Join Date
- Feb 2010
- Location
- Waterford, Ireland
- Posts
- 748
- Rep Power
- 4
- 09-18-2010, 02:19 AM #16
I always use this. when it's a member variable to avoid confusion with other variables. Normally this wouldn't be a problem... but it has been in the past.
- 09-18-2010, 07:51 AM #17
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
It isn't running in javaw (I don't even know what that is :clueless:).
Originally Posted by Darryl.Burke
I would throw a nullpointerexception if it was really needed, but a sysout error message on the command console will do for my purposes (those purposes being for development only - i.e. I plan to get rid of error messages when it comes time to deploy).
Yeah, that might work, but I'm way more familiar with sysout than exceptions (ha ha! I guess that means it's time to climb the learning curve :D)
Originally Posted by Darryl.Burke
Does that mean something like this:
Originally Posted by al Marshy 1981
or would you consider that going overboard?Java Code:int n = calculateN(); if (n = 3) doSomething(n); string str = "hello world"; System.out.println (str); double d = 0.234; for (double dub = 0.0; dub < d; dub += .01) doSomethingElse(d);
- 09-18-2010, 08:25 AM #18
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,427
- Blog Entries
- 7
- Rep Power
- 17
- 09-18-2010, 09:26 PM #19
Member
- Join Date
- Jun 2010
- Posts
- 86
- Rep Power
- 0
What was that???
Anyway, I just realized that my first question technically wasn't answered: is it better to initialize class variables at their declarations, or should this be done in the constructor? However, it seems like Norm hinted at an answer:
which seems to imply that it's better to initialize at declaration (i.e. less work to be done at run time). Am I right?
Originally Posted by Norm
I would assume the following is not recommended:
as that would require running Color's constructor which can only be done at run time. Setting it to null would be better. Am I right?Java Code:Color c = new Color(RED, GREEN, BLUE);
Also, I wouldn't mind if my last few questions were answered. Thanks.Last edited by gib65; 09-18-2010 at 09:50 PM.
- 09-18-2010, 09:59 PM #20
We need to Define 'better'
Letting the compiler do it once vs every execution time would be a better.
The object for the varible c has to be created once at execution time. Pay now or pay later.require running Color's constructor which can only be done at run time. Setting it to null would be better.
Not defining an object until the object was needed could make for faster startup.
Then there is always the maintenance costs. If your code is hard to understand, the next programmer could blow all your savings by taking too long to make changes to the code when the next change is requested.
Similar Threads
-
Need help coding
By ace_03 in forum New To JavaReplies: 2Last Post: 11-25-2009, 05:16 PM -
Coding help
By Java_Fanatic in forum New To JavaReplies: 7Last Post: 10-15-2009, 04:37 AM -
How to add our own coding standards to eclipse 3.2
By mansoor24 in forum EclipseReplies: 2Last Post: 03-17-2009, 04:50 PM -
coding help
By accies76 in forum New To JavaReplies: 5Last Post: 11-12-2008, 08:15 PM -
Hibernate Standards
By udayadas in forum JDBCReplies: 0Last Post: 08-23-2008, 07:28 AM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks