Home > Blog > More on coding standards

More on coding standards

December 31st, 2004

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.

  1. January 5th, 2005 at 13:25 | #1

    Hi! Thanks for appreciating my blog about style and symmetry! /Mats

  2. Ralph Potter
    January 5th, 2005 at 21:47 | #2

    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.

  3. Benoit Tremblay
    January 11th, 2005 at 02:58 | #3

    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.

  4. Calum
    January 17th, 2005 at 00:16 | #4

    “this.info = info;”

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

Comments are closed.