Friday, December 21, 2012

Writing good code: be concise and do one thing

These are two good posts on guidelines about writing clean, good code:

What are some of your personal guidelines for writing good, clear code? (see Jason Barrett Prado's answer)

Rule of 30 – When is a method, class or subsystem too big?

Both posts touch a very interesting point: code length. One of the common indications of bad or confusing code is when you see lengthy methods, functions, classes. I remember seeing or hearing about methods that were 2 to 3 THOUSAND lines long, with these long indented if statements. What happened to them? Typically everybody avoided touching them if the original developer left. And if refactoring is not valued (and/or becomes more of a liability), nobody will ever try to improve its maintainability. That's why these tips above come in handy: forcing yourself to somehow limit the methods and classes goes a long way because it ends up making the developer think about abstraction and how to split the code.

The other important point in Jason's answer is single responsibility. This also goes a long way. It's a very simple concept, but many experienced developers still don't think along these lines. Have a method doing one thing, have a class doing one thing. When you read books like The Art of Readable Code or Clean Code and start adopting the mindset of having good names, then methods that do multiple things will start to become obvious. When that happens, flag and refactor them at some point. That will improve your code greatly as well.
Post a Comment