More on coding standards

After I wrote a teaser on coding standard, I found this article saying that Style is symmetry and structure! I’ve allways felt that Sun’s standard was hurting my poor brain but I couldn’t say why. Now, thanks to this article, I know why. Symmetry !

When one has to impose coding standards, good reasons are mandatory. Rules need to be set in purpose. A proper rule can improve readability and code sharing, or ease debugging, or leave less room to bugs.

Symmetry is the number one rule to improve readability. You can also add whitespaces to your code because they help your brain to understand the structure the code.

result=((methodCall()*2)+(1-methodCall());

is less structured than :

result = ((methodCall()*2) + (1-methodCall()) ;

Of course a modern IDE will had color to this.

boolean result = ((methodCall()*2) + (1-methodCall()) ;

To ease debugging, a very simple rule taught to every beginner : don’t put two statements on the same line :

argv++; argc--;

When stepping into code, you really want to know which part of the line you are debugging.

It’s been some times that I write if test like this :

if (3.14 == Pi) {...}

instead of :

if (Pi == 3.14) {...}

to avoid :

if (Pi = 3.14) {...}

which is always true (in C/C++). With a modern IDE, it is however not very useful anymore since the IDE can detect things like those.

I like to give prefixes to parameters :

public class Test()
{
	private final int info ;

	public Test (final int anInfo)
	{
		info = anInfo ;
	}
}

It is also a good idea to make the parameter final to avoid changing the value of the parameter instead of the class variable.

4 thoughts on “More on coding standards”

  1. Making parameters final looks weird to me and reminds me to good old times with Delphi, where it was _necessary_. With Java you always can reference the member variable with “this.”. Good IDE’s can color parameters and fields different.

    BTW, in more than 5 years of Java development, we never had a bug which was caused by naming a parameter like a member variable.

  2. There is always a problem with having the parameter being the same name as the object field.
    We experienced a case where it did cause trouble.

    public Test (final int imfo)
    {
    // some code here
    this.info = info;
    // more code here
    }

    Did anybody discovered the typo?
    Having the final or using ‘this.’ didn’t solved the problem.
    Now we always use different names.

  3. “this.info = info;”

    IntelliJ IDEA shows a warning for this, calling it a “Silly assignment”.

Comments are closed.