Sunday, 18 September 2011

Good Programming Practice

This week I have spent some time playing with jQuery components and as a programmer I am always interested in understanding the code rather than just plugging it in and leaving it that. One thing that struck me looking through the source is the amount of code that looks like this
  if (condition) 
      DoSomething();
The key point about this code is the lack of curly braces around the if/else statements - this is a practice I have always tried to avoid and don't particularly like. The truth of course is that with or without braces the code will do exactly the same thing and the issue is more to do with semantics and readability than it is to do with the code itself.

I mentioned this on Twitter and got some interesting responses back from other developers - the main one being that this is probably a language specific question as many languages/frameworks simply won't allow this sort of syntax in the first place.

I have stolen borrowed C# code from the web on many occasions and have very rarly seen this type of code yet in JavaScript it seems to be the norm. Why this is the case I am not really sure, of course file size is an issue in JavaScript which is not so relevant in C# due to its compiled nature but if you are following best practices then you are already minifying your scripts before going live anyway (you are aren't you?) so an extra few lines in your uncompressed files will make little different after compression.

The other thing that people mentioned on Twitter is that the code above would not be acceptable but if it all sat on one line then it would probably would be alright, like this -
  if (condition) DoSomething();
The difference it minimal but from a readability point of view I can see justification for it. It is much clearer what is intended - the problem with the first case is it may be possible for a future developer to come along and do the following
  if (condition) 
      DoSomething();
      DoNextThing();
Which would obviously not do what was expected - this is just a hypothetical case and probably wouldn't really happen in reality but it opens up the possibility that it could. The simple answer is to program defensively and, as most people on Twitter seemed to agree, add the braces in.

What is your opinion? Is there ever a valid reason not to add the braces? What happens in other languages?

No comments:

Post a Comment