How To Write Perfect Code

March 6, 2009
Tags:

Have you ever written perfect code?  If so, how often does this happen?  If not, why not, and do you think it’s possible?  Perfect code is something that many developers strive for but few, if any, achieve.  In this entry, I will discuss the set of requirements that must be met for a developer to be in a position to write perfect code.

What is Perfect Code?

My definition for perfect code is “Code that solves a problem, without bugs, in an optimal way”.  This has slight ambiguities, so I’ll break it down.

1.  Solves a problem

The whole idea of writing the code is to solve some non-trivial problem.  To do this perfectly, the solution must be solved for all possible cases.

2.  Without bugs

The code needs to perform the required task correctly in all situations.  This includes valid and invalid input and situations.

3. In an optimal way

I come from a game development background and therefore performance is important.  Depending on the situation, optimal will take on a different meaning.  For games, this might mean that the entire game loop must run at a minimum of 30 frames per second.  For a banking program this might mean that a transaction takes less than 10 second to complete.

Is Perfect Code Possible?

The simple answer is, yes.  Code can be written that perfectly solves a problem, without bugs and can therefore be classed as perfect.  Unlike many professions, what we create is never fully “set in stone”.  Code can change at any level, from fixing a broken statement to re-architecting an entire application.  When the three requirements below are met, developers are in the best possible position to write perfect code.

The Requirements (aka What’s Needed To Write Perfect Code)

To expect perfect code from developers, the following 3 requirements must be met:

1. Thorough Domain Knowledge
2. Enough Time
3. Great Developers

Just think about each of these for a minute before continuing.  If you’re a developer, do you meet all three requirements in your current position?  If not, which ones don’t you meet, and why?  Feel free to post a comment.

Below I’ll break down these requirements and show two graphs.  One for the amount of return gained for levels of input into each requirement.  The second graph shows the cost of achieving a set level of quality.

Each requirement also has a limiting factor.  This is the top reasons why developers often write imperfect code.

1. Thorough Domain Knowledge

Developers must have a good grasp on the subject matter they are to be working on.  If you’re making a driving game, you need to know the way cars handle, what torque is and why a blowoff valve sounds so cool.  If you’re writing an accounting program then you need to be boring, and therefore understand accounting (or is it the other way around).  You also need to know about debits and credits and the difference between cash flow and capital.

Moving from no domain knowledge to a simple understanding helps a lot when striving for perfect code.  After this point, learning more about the domain helps, however the next big leap in code quality comes from having an intimate understanding of the domain (the small mark on the x-axis in the graph below).

The following graphs show the level of quality gained by increasing domain knowledge and the cost required to achieve this.

Limiting Factor:

It’s difficult to find someone with expert domain knowledge and takes time for people to learn.  Also, many developers simply won’t want gain an intimate understanding of the domain.  This can be solved by having domain experts work closely with developers.  See Domain Driven Design by Eric Evans for an in depth discussion on this topic.

2. Enough Time

Most projects I’ve seen rarely have enough time.  Time is critical for writing perfect code as it unlocks the following factors:

  1. Hacks/quick fixes won’t be written
  2. There will be little to no overtime
  3. Peer reviews and pair programming become possible
  4. Work can be designed rather than simply hacked together
  5. Work can be thoroughly tested

The mark on this graph shows where “enough time” is given for a project.  If enough time is given, the quality in code jumps substantially.  After this time though, there is a point of diminishing return as having developers continue to work on the project won’t return great gains.

One point to note is that if the amount of time given to developers changes mid project, all bets are off.

Limiting Factor:

Money is the major limiting factor with giving developers more time.  However it isn’t the only one.  Competitors can bring products out before yours or customers may have strict deadlines that you must meet.  Also, developers don’t live forever, and rarely life in the same job forever.  The longer a project runs, the more likely you are to lose developers and therefore have to retrain and rehire more, at great cost.

3. Great Developers

I agree with the concept that good developers are 10 times more efficient than average developers.  Joel Spolsky put this perfectly when he said “Five Antonio Salieris won’t produce Mozart’s Requiem.” For those that haven’t seen Amadeus, he’s saying that the order of magnitude difference between good and great developers is staggering.  Unfortunately, you just can’t get the quality you need unless you have great developers; it’s as simple as that.

The mark on this graph show’s the level of developer skills required to write perfect code.  About the top 5-10% of developers fit into this bracket.  The good news is that the difference in cost between an average developer and a great isn’t the same order of magnitude higher.

Limiting Factor:

Great developers are hard to find!  With companies like Microsoft and Google paying crazy amounts of money, the top tier will often work for them.  However the good news is that great developers can be trained and in the right environment, so long as you have smart people you can often turn them into great developers if they (and you) care enough about software development.

Do We Want Perfect Code?

That may seem like a simple question, however in reality it isn’t.  In a vacuum, for most developers that question is rhetorical.  Of course we want to write perfect code, we take pride in our work and we strive for excellence.  However, when you look at the cost involved in achieving perfect code it is not always a requirement.

This is something we must take seriously when writing software as the realities of business mean that more often than not, imperfect code is exactly what the business needs.  It’s better to ship code with issues than to not ship code at all.

Conclusion

I’m sure I’ve said at least a few controversial things, so please comment and/or email me to continue the discussion.  I continue to strive for perfect code in my life, and whether I’ll ever reach it is irrelevant.  I’ll leave you with a quote from one of my favourite movies:

“There are no perfect men in this world, only perfect intentions.”

  • http://www.tinyfrogsoftware.com Joshua Smyth

    I think you’ve illustrated how to write good code, not perfect code.

    Using your criteria,

    1. Solves a problem
    2. Without bugs
    3. In an optimal way

    It is quite possible to have two pieces of code, one of which is more optimal than the other, (less lines of code, faster, easier to understand, cross-platform, generic etc..) and therefore more perfect.

    I think that the above criteria specify nessesary, but not suffient conditions for perfect code.

    But sometimes good code is good enough :)

  • Mark

    A friend of mine in my first job was fond of raising Zeno’s Paradox of motion in relation to coding. That is to say, as long as you continue to code toward perfection, there is still code that needs to be written to catch up to perfection. This is especially true in terms of scope creep, changing technologies and other external influences that cannot be mitigated through coding alone.

    Still, I think the tenets you’ve raised are good goals for perfect code, though point 3 is subjective. The way you optimise a timing problem for a game is not necessarily the same way you would solve a timing problem for a safety switch. A game can have a timer resolution of a few tens of milliseconds while a safety switch must have a tighter resolution. Then again, it’s all based off the original problem anyway.

    I’m curious to hear whether you think that test driven development (ie. Writing a test as the problem and then the code to solve that test with the ultimate goal of putting it all together as the overall solution) brings us closer to the ideal of perfect code, or whether it draws us away from it.

  • Greg

    I’ll avoid the ‘Is perfect code possible’ discussion for now. I’d like to say that perfect code is always desired but frequently not wanted or needed.

    Perfect code would be more necessary for components that will be reused or maintained over time, or even components with such complexity that the initial development could benefit from careful design and implementation.

    In a commercial project there is frequently the thought that some component ‘may’ be reused later, but the financial success of the current project will determine the future for subsequent projects. In the end, ‘good value’ code is more important than perfection. Perfection may get its chance to occur as a maturing process over time and open source can help commercial and noncommercial projects achieve this.

    I’d also say that the ‘perfect code’ may have a very limited context. What is the ‘right’ way to solve a problem may not be the right way later, eg. optimal quick sort on single CPU vs multi core. And the problem itself may shift eg. goals and requirements for LOD system.

    One final thought is that it is good practice to separate interface from implementation, allowing either to be tweaked or matured over time to obtain better value. At different points in time you may achieve a perfect interface or perfect implementation (for a given platform), bonus if you can get both together!

  • http://davidgillespie.wordpress.com David Gillespie

    From the point of view not of a developer, but as someone who has asked developers to write the best code they can in the time possible, it strikes me as the kind of math problem where the distance between where you are and where you want to be can be forever halved, meanign you’re ever closer but never really quite there.

    Like you say, software is maleable and I think there is value and strength in taking the time to say “I know this isn’t right, but it is least wrong, Perhaps the difference is semantics, I think it’s important none the less.

  • Dave McCarthy

    I would make two points, which balance between the philosophical and mathematical rather than being technical, but then I am much better at philosophy and math than coding so probably for the best!

    1: There are a great many problems for which there is no complete set of solutions and the goal must be to find the greatest possible subset of solutions and/or find maximal and minimal values (speaking somewhat metaphorically, though this can be literally true). Often code is presented as solving for all cases when in fact the programmer has adjusted the problem space from his viewpoint, and thus codes in a incorrectly, and arbitrarily, reduced solution space. The most common form of this is precluded by the thought process which goes something like “Well, in 99.9% of cases, we can ignore variable x”. Which is fine until variable x hits some resonant or asymptotic value and your solution is incorrect and, much more harmfully, presumed to be correct. As has been said above, it is vital to know where your code is lacking.

    2: My first point is an additional reason why your first requirement, thorough domain knowledge is absolutely essential. As you may be able to tell from the above, I am a physics student and it very quickly becomes obvious that in my field there are those who can code, those who grasp abstract concepts well and those whose math skills are outstanding. Any 1 of those 3 can do well in physics, so entwined is programming with our field, but to approach Mozart, one must have all 3 in abundance. Needless to say, this is something almost never seen.

  • http://www.edityourpaper.webs.com Stanley Garland

    I would agree that perfect code is what we all strive for but there is no end to what “perfect” is. As soon as I think it is perfect, then I am fooling myself when my colleague comes up with a new and innovative way to “work-around” and do what took me a page to do in a few lines. Creativity is the only true limiting factor to the supposed perfect code. Then, the question arises, is there “good enough” code. What is good enough today, will be an outdated way to do it in a few years.
    http://www.edityourpaper.webs.com

    Stanley Garland

  • Ashish Madan

    There is nothing called Perfect Code. When you say perfect code , what do you actually mean? Only a person involved in coding knows this fact “There is no perfect Code” .

    Pls get in toch if you have any doubts
    Thanks,
    Ashish Madan.

  • Phodu Coder

    Get a life! Geeks.
    As long as you dont get fired, the code is good enough i say.

  • Chandan Kumar Singh

    Yeah fully agree wid ASHISH MADAN … no body can say the delivered things are perfect.. infact the s/w is the basic build of code which gets deteriorate day by day…. so how we can say the piece of code is perfect solution of particular problem.

    Thanks,
    CK