Six Easy Tips for More Maintainable Code

I’ve recently had the opportunity to work with a large, unfamiliar code-base. The experience has made me reflect on some of my own coding practices and on writing more maintainable code. Much has been written on this topic, but here are the things that I feel are most important and have a high payoff without much (if any) additional work.

Make use of inherent metadata

Programming languages have inherent metadata in how you name things, what types you use, scoping, visibility, etc. This information is invaluable for someone new looking at the code and helps make the code self-documenting. There are several things you can do here:

Use good names

  1. Give classes, variables, methods, functions, etc. descriptive, differentiable names. Things that are related should have similar names, while things that are not should not.
  2. Keep the names up-to-date. If functionality changes, update the name.
  3. Variables with different scopes should be differentiated. For example, prefix instance variables with an underscore.
  4. Be consistent.
  5. Don’t create variables for things you only use once – just put them inline. Then I don’t have to figure out where else the variable is used.

Use appropriate types

  1. If possible, don’t use multi-level typedefs. It’s a real pain in the ass to go through 5 header files to figure out that foo_bar is an unsigned integer. And don’t typedef pointers away – I want to know if something is a pointer or not. Especially don’t typedef pointers away by inventing your own syntax (e.g. CFArrayRef is a CFArray pointer). The language already has syntax for that.
  2. Do use typedefs for things like enums.
  3. Use the most-specific type possible. If something should not be negative, make it unsigned, etc.

Use appropriate visibility

If something should only be used within a class, make it private. People looking at the code then don’t need to worry about external clients.

Keep things short

Nothing is more depressing than trying to grok a long method/function/class. There shouldn’t be hard rules on length, but I try to write methods/functions that fit on one screen, and to keep my classes under around 1000 lines of code. Without caution, this can lead to a method/class explosion, but I’d rather grok a small class cluster than one gigantic class.

Keep block nesting to a minimum

Don’t have a while loop inside an if, inside an else, inside a for loop, inside an else if, inside an do/while loop, inside a …

Reduce coupling

If I have to understand more than a small portion of the code to change one class, there is a problem.

Write useful documentation

You don’t need a lot. Here is what I think is important:

  1. Describe briefly what a method/function does. No method or function should be so complicated that this is more than a sentence or two.
  2. If a method is overriding a superclass, note that and explain why.
  3. Explain anything unusual or complicated.
  4. If a method has concurrency issues (should only run on the main thread, etc), note those.

Think of those that come after you

Whenever you write some code, try to put yourself in the shoes of the next programmer to work on the code. This is the programmer’s version of the seven generations rule.

About these ads

17 Responses to “Six Easy Tips for More Maintainable Code”

  1. Chris Tomkins’ Blog » Blog Archive » Six Easy Tips for Writing Maintainable Code Says:

    […] Discovered this blog posting by accident (searching for some contact details of a friend who is a namesake of this person!) and thought it was quite interesting. It still amazes me when reading code how often people neglect to do even the simple things. […]

  2. ExLabordiner Says:

    Please, give me contact address (email or msn) of this site administrator…
    Thanks!

  3. Sean Kelly Says:

    Why?

  4. Cesar Says:

    Great entry! Let me make a small comment if I may. You write:

    3. Explain anything unusual or complicated.

    I would rather say: if you find code which you think is unusual or complicated then you are probably doing something wrong or there might be simpler way. If you think the code is complicated / unusual while you are writing it then in two months it will be a complete nightmare. Chances are you could probably make is simpler by thinking a bit more about it.

    This is something I read in Code Complete written by Steven C. McConnell (http://cc2e.com/) which is an excellent book on this subject.

  5. Sean Kelly Says:

    That is a good point. However, sometimes performance or other concerns win out over simplicity or readability.

  6. Top 10 Liste für besseren Code | Zustandsforschung Says:

    […] Six Easy Tips for More Maintainable Code […]

  7. kas » Шесть советов по написанию более понятного программного кода Says:

    […] Cohen) (how to write maintainable code), 6 советов от Шона Келли (Sean Kelly) (more maintainable code) и 12 советов от Джоэла Сполски (Joel Spolsky) (12 steps to better […]

  8. Zustandsforschung » Top 10 Liste für besseren Code Says:

    […] Six Easy Tips for More Maintainable Code […]

  9. writing good code | linkfeedr Says:

    […] way to organise a Ruby project, from people who are experienced in creating them. Further reading How to write maintainable code Twelve steps to better code Strategies for commenting code Common types of bad design How to write […]

  10. Binu897675t5  Says:

    Medicines Online Without a Prescription. The normal purchase time is five minutes. The normal receipt time will be the following day or probably the most part your entire day after ! Press here ! Medicines Online.

  11. dfanats88 Says:

    Каждому Добрый день! Простите за оффтоп но на сайте клуба лучшего софта нашел море уникальных и полезных программ для вашего компьютера заходите не пожалеете!

  12. 17marilynn17 Says:

    Welcome to Weight Loss Blog and find weight loss articles

  13. bestpron1 Says:

    порна видо

  14. kinomore11 Says:

    Скачать шаг вперед 3

  15. Nauman Says:

    thank you so very much for the wonderful demonstration of writing maintainable code.

  16. green smoke review Says:

    I’d a different brand befor Green Smoke and I could not get away from real cigs~urge too great. I have been cigarette smoking for over 20yrs today and thanks to Environmentally friendly Smoke We and my better half have not had the desire to go back to regular cigs. Product is user friendly, affordable and also feels and tastes being a real cig.

  17. Sapsanltd Says:

    Всем Добрый день! Заходите на Грузоперевозки по Москве и области. Гузоперевозки в любую точку на карте Россия и СНГ

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: