My five rules for writing good code

I just came across a blog post that outlines 5 rules for writing good code.  I agree with them for the most part.  But this subject is extremely subjective and will vary from person to person.  Therefore, I’d like to write up my own rules for writing good code.

Keep it simple

This is the YAGNI rule.
There are often times when we want to try to solve problems we don’t have.  You must resist this urge.  It’s far easier to make simple code more complex than the other way around.  This is usually more of a challenge than it looks.  It’s a sign of good code that you constantly find yourself saying “any idiot could have put this together”.  Reality is that idiots only write simple code when the problem is easy or when they get lucky.

…but not simplistic

You can call this the SYDNI rule.
Albert Einstein said it best when he said “Everything should be made as simple as possible, but not simpler.”  I’ve seen too many “simple” hacks that ended up causing more of a maintenance problem than it would have been just to write something more complex.  As good a thing as simplicity is, you need to be realistic.  Don’t try to make a simple solution match a complex problem.

Abstraction is your friend

So what do you do in those situations where you need to use a complex solution?  Do you give up all hope and just write some horrible piece of crap?  No, you find a way to make that complexity easier to manage.  This is where abstraction comes in handy.
For instance, Lisp introduced the concept that “it’s all data”. This makes it easier to understand things.  If you want to know what something is, you already know that it’s data of some kind.  What is a function?  Data.  What is a list?  Data.  What is code?  Data.  This has a profound effect upon your ability to understand things.

Follow guidelines

Jeff Atwood would call this following the instructions on the paint can.  We tend to sneer at the idea of “best practices”, but reality is that they’re necessary.  There are a lot of problems out there that people have already dealt with and solved.  Why waste time not learning from others’ mistakes.

…but don’t worship them

As the old cliche tells us, rules were made to be broken.  Some of the most well known design patterns break the guidelines and have some of the worst code smells.  In fact, sometimes the guidelines conflict with each other.  Thus, don’t blindly follow guidelines without knowing their purpose.  Instead, understand the rules, know when to follow them and when following them is the greater of two evils.