Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default 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:

    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';
    	}
        }
    }
    or is this better:

    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';
    	}
        }
    }
    Another question:

    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:

    Java Code:
    if (b) x++;
    To me, it just seem neater if I put it all on one line.

    I do something similar for really short accessor methods:

    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;}
    I have other questions but we'll start with these. All answers are greatly appreciated. Thanks!
    Last edited by gib65; 09-17-2010 at 12:05 AM.

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default

    You'll find the official version here:
    Code Conventions for the Java(TM) Programming Language: Contents

    Apart from that
    Java Code:
    public static final double MY_DOUBLE = 0.05; // must be initialized here
    Not necessarily. A final field must be initialized either at declaration or before the end of every constructor.
    Classes

    db

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,407
    Rep Power
    25

    Default

    private char[] char_array = new char[10];
    vs
    private char[] char_array = {'X', 'X', 'X', ..7 more}; // Initialize at compile time vs execution time

    it just seem neater if I put it all on one line.
    Problem is: everyone is used to looking after the if statement to see the body of code to be executed.
    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.

  4. #4
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    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:

    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();
    
    	// ...
        }
    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.

    Does this make sense?

  5. #5
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    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. ;)

  6. #6
    Prajin's Avatar
    Prajin is offline Senior Member
    Join Date
    Jun 2010
    Location
    Ktm, Nepal
    Posts
    120
    Rep Power
    0

    Default

    I value efficient and neat code over coding conventions
    I believe coding conventions is for making neat and efficient code. But not necessarily, I may follow conventions every time.

    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.
    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.

  7. #7
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by Prajin View Post
    I believe coding conventions is for making neat and efficient code. But not necessarily, I may follow conventions every time.
    I don't believe this; look at this coding convention from the link above:
    Java Code:
    if (a == b && c == d)     // AVOID!
    if ((a == b) && (c == d)) // RIGHT
    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:
    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.

    Quote Originally Posted by Prajin View Post
    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.
    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.

  8. #8
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default

    Quote Originally Posted by gib65 View Post
    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:

    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();
    
    	// ...
        }
    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.

    Does this make sense?
    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.

  9. #9
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,009
    Rep Power
    20

    Default

    Quote Originally Posted by Zack View Post
    I don't believe this; look at this coding convention from the link above:
    Java Code:
    if (a == b && c == d)     // AVOID!
    if ((a == b) && (c == d)) // RIGHT
    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:
    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.
    Can you give an example?
    The one in the code conventions link is rubbish admittedly...I can't think of anyone who brackets individual == statements, but individual "states" for getting into a particular piece of code should be, to my mind.

  10. #10
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    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.
    Thanks Tolls,

    However, there is a section in the link you provided that says this:

    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
    This is exactly what I'm trying to do (if I understand correctly) - checking for errors in the arguments passed to my methods.

    The above quote says nothing, however, about private methods, but I have very few private methods in my code.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default

    Quote Originally Posted by gib65 View Post
    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:

    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();
    
    	// ...
        }
    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.

    Does this make sense?
    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.
    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();
    
    	// ...
        }
    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.

    sv

  12. #12
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default

    Quote Originally Posted by Zack View Post
    I don't believe this; look at this coding convention from the link above:
    Java Code:
    if (a == b && c == d)     // AVOID!
    if ((a == b) && (c == d)) // RIGHT
    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:
    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.
    Always remembering that a, b, c, d in that example code will be longer, meaningful variable names in actual code, or may even be method calls, I usually break each condition to its own line for readability. Like
    Java Code:
    if (a == b
           && c == d) {
       // do something
    }
    db

  13. #13
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Quote Originally Posted by gib65 View Post

    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.

    Does this make sense?
    programming in a language like C would require all variables at the beginning. best to declare and define variables close to where they are actually used in java.

  14. #14
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    Can you give an example?
    The one in the code conventions link is rubbish admittedly...I can't think of anyone who brackets individual == statements, but individual "states" for getting into a particular piece of code should be, to my mind.
    States? You mean, "if ((object A has some value) && (object B has some value))"? Not sure exactly what you're driving at.

    Quote Originally Posted by Darryl.Burke View Post
    Always remembering that a, b, c, d in that example code will be longer, meaningful variable names in actual code, or may even be method calls, I usually break each condition to its own line for readability. Like
    Java Code:
    if (a == b
           && c == d) {
       // do something
    }
    db
    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...
    Java 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;
    Edit: I see the code box actually isn't wide enough to handle this. Neat-o! :D
    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. ;)

  15. #15
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Quote Originally Posted by Zack View Post
    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...
    Java 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;
    Edit: I see the code box actually isn't wide enough to handle this. Neat-o! :D
    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. ;)
    redundant use of 'this' ?

  16. #16
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    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.

  17. #17
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    Quote Originally Posted by Darryl.Burke
    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.
    It isn't running in javaw (I don't even know what that is :clueless:).

    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).

    Quote Originally Posted by Darryl.Burke
    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.
    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)

    Quote Originally Posted by al Marshy 1981
    programming in a language like C would require all variables at the beginning. best to declare and define variables close to where they are actually used in java.
    Does that mean something like this:

    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);
    or would you consider that going overboard?

  18. #18
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,523
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by surya86mca View Post
    Respected sir...
    i have an assignment to develop the Fleet Management System
    Stop double posting and stop hijacking someone else's topic.

    kind regards,

    Jos

  19. #19
    gib65 is offline Member
    Join Date
    Jun 2010
    Posts
    86
    Rep Power
    0

    Default

    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:

    Quote Originally Posted by Norm
    private char[] char_array = {'X', 'X', 'X', ..7 more}; // Initialize at compile time vs execution time
    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?

    I would assume the following is not recommended:

    Java Code:
    Color c = new Color(RED, GREEN, BLUE);
    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?

    Also, I wouldn't mind if my last few questions were answered. Thanks.
    Last edited by gib65; 09-18-2010 at 09:50 PM.

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,407
    Rep Power
    25

    Default

    We need to Define 'better'
    Letting the compiler do it once vs every execution time would be a better.

    require running Color's constructor which can only be done at run time. Setting it to null would be better.
    The object for the varible c has to be created once at execution time. Pay now or pay later.
    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.

Page 1 of 2 12 LastLast

Similar Threads

  1. Need help coding
    By ace_03 in forum New To Java
    Replies: 2
    Last Post: 11-25-2009, 05:16 PM
  2. Coding help
    By Java_Fanatic in forum New To Java
    Replies: 7
    Last Post: 10-15-2009, 04:37 AM
  3. Replies: 2
    Last Post: 03-17-2009, 04:50 PM
  4. coding help
    By accies76 in forum New To Java
    Replies: 5
    Last Post: 11-12-2008, 08:15 PM
  5. Hibernate Standards
    By udayadas in forum JDBC
    Replies: 0
    Last Post: 08-23-2008, 07:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •