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