"What is the consensus with regards to single entry, single exit methods. I was never taught to code to this convention but recently heard that some companies require it. I wondered how people felt about this?"
There were many responses, some agreeing but mostly disagreeing that it was a good "standard" to enforce. Some of the arguments in favor of single-exit-point-ness were:
- Multiple exit points can lead to more bugs
- There's too much license in "sometimes it's ok to do x". That's the same as saying "It's always OK if I feel like it on any given day."
- It is easier to "see" the method structure with one exit point.
To address the "more potential for bugs" argument, I respond with unit testing. A method that is complex or intricate enough to have multiple paths of logic should usually have a set of tests for each of those paths.
In summary: sometimes a single exit point (return) is more elegant, but sometimes multiple returns lead to more elegant code. We might all disagree (and almost certainly do) about how big those two "sometimes" are in relation to each other, but the bottom line is, "Readability/elegance/simplicity trump all coding rules or standards" - it's going to be pretty hard to argue with that.
In general I feel that code standards usually go too far, are too dogmatic. A coding standards doc should, IMO, always be called a "guidelines" doc and the first section/chapter should state something like "code readability and elegance" trump other rules. Yes, it requires careful attention and discipline to avoid the "I don't feel like it today" trap - but if programmers don't have discipline good attention to detail, well then "where they put their curly-braces" or "how many exit points they have in methods" are going to be the least of the problems...
No comments:
Post a Comment