Seven Rules for Beginning Programmers

A little while ago Phil Wadler posted “VS Naipaul’s Rules for Beginners,” listing the famous author’s seven rules for beginning writers. Upon reading them it occurred to me that, with a little adaptation, they could equally apply to beginning programmers. So, with apologies to Mr. Naipaul, here are my “Rules for Beginners:”

  1. Do not write long procedures. A procedure should not have more than ten or twelve lines.
  2. Each procedure should have a clear purpose. It should not overlap in purpose with the procedures that went before or come after. A good program is a series of clear, non-overlapping procedures.
  3. Do not use fancy language features. If you’re using something more than variable declarations, procedure calls, control flow statements and arithmetic operators, there is something wrong. The use of simple language features compels you to think about what you are writing. Even difficult algorithms can be broken down into simple language features.
  4. Never use language features whose meaning you are not sure of. If you break this rule you should look for other work.
  5. The beginner should avoid using copy and paste, except when copying code from one program they have written to a new one they are writing. Use as few files as possible.
  6. Avoid the abstract. Always go for the concrete. [Ed. note: This one applies unchanged.]
  7. Every day, for six months at least, practice programming in this way. Short statements; short, clear, concrete procedures. It may be awkward, but it’s training you in the use of a programming language. It may even be getting rid of the bad programming language habits you picked up at the university. You may go beyond these rules after you have thoroughly understood and mastered them.

You should also follow me on Twitter here.

59 thoughts on “Seven Rules for Beginning Programmers

    1. John T

      Teach away, but make sure you teach also that use of abstracts and interfaces solves a *specific* problem where you *must* abstract the interface from the implementation. This is why it can be difficult to come up with good examples for this, because it’s not really too common of a problem. If a programmer finds himself writing abstracts and interfaces for a single implementation, then he’s probably not solving a problem by using them. A good rule of thumb that I heard and liked was that polymorphism is not for code reuse, it’s only for abstracting the implementation from the client.

      Reply
  1. Krishna

    “A procedure should not have more than ten or twelve lines.”

    This rule is difficult. These days the programs are so complex that having functions <15 lines is almost impossible.

    Rest of the rules are fine and I agree to them.

    The rule no 5 should be practiced and I think it is the most desirable one.

    Reply
    1. Dave

      I agree…so what would he have us do write 100 lines of code or break that code up into 10 separate functions (procedures) that are only used in one place. Then what, inline them? LOL

      Reply
      1. Koen

        Yes, it’s called ‘clean, self-documented code and it makes a huge difference in maintaining the code for a longer period of time. Especially of it is not the original programmer that must adapt the code later on.

        If I do a code review and see a method with 100 lines or more, I always ask the programmer to re-factor this method. Long methods are simply a code smell and to be avoided at all costs.

        Good, clean code, reads almost as a novel and follows a natural flow. Splitting something large up in small, easily digested chunks helps the programmer understanding the implementation, even a programmer who ‘inherits’ the code and raises the quality of the software.

        The rule is not ‘split it up in 10 parts’, but: ‘make it easier to understand and maintain’.

        Reply
  2. Bruno

    ten or twelve line limit? good luck; i wrote a 623 line case statement last night for setting user color preferences on multiple charts. how do you do that in ten or twelve lines?

    Reply
    1. Kelvin

      You could use base classes and overide the get colour method.
      Then for preferences use a list of preferences that inherit from the base class and specify the colour they should choose.

      Reply
    2. John T

      I can speak from experience that coding for GUI purposes (or also loading/saving files *in some cases*) is the exception to writing short functions.

      Reply
    3. John T

      I must say, though, that if you’re willing to post the code here, I’m up for the challenge of finding a way to do it with multiple short functions. Of course, I may take one look at the function and agree with you completely :-)

      Reply
    4. thomask

      If what you have told is true, then I would suggest there is something seriously wrong in your architecture!!

      Reply
    5. Venki

      The very fact that you are using a 623 line for a case statement shows that you have have to do some re-thinking here. may be if your case is stated, it would be more worthwhile to take a look at.

      I don’t agree on “Avoid the abstract and always go for the concrete”. One must not over-use them. but it does serve it purpose whenever needed.

      Reply
  3. Sanj

    The first one should only be a guideline once you are no longer a beginner. If you go through your programming career never writing a procedure of more than a dozen lines, you will make things seriously difficult when you have to program a switch statement with 10 cases. Alternatively, you will end up with horrendously complex trees of tiny functions simply because you won’t let yourself write a function of 13 or 14 or 20 lines. If a function of 20 or even 30 lines does one single job in a clear way, breaking in down into two or three smaller functions isn’t really necessary, and if the function is called repeatedly, the calling overhead will mount up and slow your program.

    Reply
  4. Doug Stevens

    Additional suggestions for beginners.
    * Find a mentor

    * Find a SIG (special interest group); there are a lot of virtual SIGs on the internet.

    * Document, document, document, document; keep it clear, and brief.

    * Whenever possible, review code from peers; especially on a project you are unfamiliar. See what works and doesn’t work from a readability perspective. Ask yourself, if you can understand the intention of the procedures/program by reading the code alone? If not, think how you can incorporate improvements if someone else had to read your own code.

    * If possible, (and does not violate any disclosure agreements), archive some of your favorite work; in fact add include comments as to why you like it. Then go back to it later (6 months or a year) and review. You will be surprised as to how much you’ve learned, and not only in technical skill.

    Reply
  5. Bob

    Good list. I would however add a couple more. 1) Make judicious of comments and 2) Make variable names meaningful.

    Early in my programming career I was introduced to a book “Elements of Programming Style” Which has served me well. I was surprised to see that it is still available on Amazon.

    Reply
  6. Izzy

    #5 I completely disagree. Copy, paste, adapt, learn. It’s that simple. There is no reason to make a programmer reinvent the wheel – It wastes time and increases frustration. Whether in a business context or an academic context, the goal is to get the job done. If you have free time, you can work on your coding efficiency and scalability (so you can get the job done faster).

    Reply
  7. Richard B. Johnson

    Ten to twelve lines of code per procedure will seldom do anything of value unless you are just calling canned procedures.

    It takes many more lines of code to make a convolution, FFT, or typical signal processing algorithm.

    It is much better to have a procedure stand-alone testable, designed and written so that all inputs and outputs may be tested independently before it is merged into the mainline code. This will prevent some typically horrific effects upon downstream code.

    Reply
  8. Shawn Lawsure

    3 and 6 I couldn’t disagree with more. Using advanced language features helps achieve 1, 2, and 7. It facilitates re-use, more concise (less) code, better readability, etc., which reaps numerous benefits. I would recommend the opposite for a beginner… learn the advanced features of a language and use them appropriately. Always thinking and coding in the abstract is the defining principal behind OOP and also helps achieve the benefits just mentioned.

    Reply
  9. Mitchell Schaff

    Re: Rule #1 – ten or twelve lines might be a little restrictive at the start. New programmers may have difficulty breaking their procedures/functions down to discrete tasks that will fit in a dozen lines.

    I had a college Prof. who required all routines to be twenty or fewer lines. Anything longer than that was no accepted. It was an interesting exercise in what I would call “thinking small”.

    Rule #4 is outstanding!

    Reply
  10. Joe

    I disagree with number one, it is too rigid and I have seen some awful code by simplistic adherence to that kind of rule.
    I would make it number two and rephrase it as; If the proceedure is more than 12 lines long one need to re-examine its purpose and make sure that purpose is clear before proceeding.

    I can see why you have it as number one, and why it is as it is. You are following the example from the writing tips but i have had some bad experience where some overlong proceedures were taken and split into a number of other procedures completely ignoring rule 2 and added nothing ot the cide except obscuring the purpose of the original procedure.

    Reply
  11. Liam Reilly

    Some useful direction but……..

    3.Do not use fancy language features
    Err – so you are saying, never upgrade your IDE as you should not attempt to use any of those new pesky features in later versions

    6.Avoid the abstract
    Err – so you are saying – avoid OOP principles in programming

    Reply
  12. Asido

    “6. Avoid the abstract. Always go for the concrete.”
    Ahh? That is interesting. In my CS program we are always thought to go for abstractation and never concrete implementation. I understand this point as not to use inheritance, polymorphism and stuff like that. Am I correct? If so, what is wrong that?

    Reply
  13. Jason P Sage

    3 – Why not? Beginner should stay beginner? No… Learn Tricks – it will help you read other folks code who may not of read this article.

    4: Never Experiment? E-Gads – this is not the sentiment intended, surely because this author is kindly encouraging new folks to coding some things to consider. Trust that my prose is not to upset but to simply toss in a few alternate ideas.

    5: One sentiment behind such claims has some merit but it’s not even mentioned. So Cut-N-Paste – as without an alternative – it’s like being in school writing on the chalkboard ..like Bart System: I will not throw rocks. I will not throw rocks….

    The Sentiment about cut-n-paste = BAD is you may paste in bugs easily… I say same holds true for typing it by hand over and over.. . The Alternative SOME IDE/text Editors etc may give you that can help the “cut-n-paste” common blunders (read par for course) is a way to save code snippets, and even better ones allow parametric code -recreation or code re-use. Ultra-Edit I think was a decent editor that could do this at one time. for example, you write the routine once, and put in variables where the funtion name na dmaybe some parameters will go when you need them. Then you can spit out code by selecting a function or code snippet, and filling out a couple fields then the editor can prepare that chunk of code for you again and again without error.

    6: Avoid the Abstract? Everything in computers is abstract, however it is very true many programmers in the process of simplifying things go a little too far down the rabbit hole making things sometimes more complicated as a result of attempting to make it simpler. An unwelcome paradox. Solution?

    Perhaps we can read #6 or the entire article as the KISS principle: Keep it simple silly.

    This is important, so things can be shared among colleagues etc… share code blah blah…

    I just want to pepper this sentiment with folks are pretty smart, and if they’re not… I want them working on someone else’s code anyway, not mine or my clients’. Programmers should be able to understand at a glance any construct in the language they are using and the only way to really “grok” or fully comprehend the intimate details of any language (programming or otherwise) is to thoroughly practice every bit of it possible. Increase your vocabulary by use, not exclusion.

    This article finishing with stressing practice and applying what you’ve learned: A point perhaps we could all benefit from an occasional reminder.

    Reply
  14. Chris

    I’m a beginning programmer that had just finished university. What bad programming language habits are picked up at the university?

    Reply
  15. Jan

    Additional rules when working with Object orientation.
    8. Short classes. Every class you build has 1 responsibility. do not bloat your classes with a bunch of unreleated methods.
    9. Pick up on design patterns as soon as possible. These patterns seems fague and abstract in the beginning, but will re-enforce your understanding of proper object orientation. They should have been tought together with object orientation, not as an afterthought.
    10. Do not blindly overload some class is it slightly differs from something else. Use a so called has-a relationship instead.

    Reply
  16. Jack

    Thank you very much Mr.Paulv. seven rules but so important, ill follow them sure since i’m a beginning programmer. Ill keep them in my mind.

    Reply
  17. Mark

    “Never use language features whose meaning you are not sure of – ?”
    “avoid using copy and paste – ?”

    but then I might have to actually ‘understand’ stuff !

    There are DJ’s that make great sounding records without being able to read or write music properly . .. ..

    I like to think of my programming in a similar way.

    I know what I want to achieve and so long as it looks and works right in the end, does it really matter that I don’t FULLY understand every little bit of the pieces I have knitted together?

    In fact . .. If you think we have to understand every tiny piece then there should be no high level languages. Back to writing machine code!

    Reply
    1. Zecc

      I know what I want to achieve and so long as it looks and works right in the end, does it really matter that I don’t FULLY understand every little bit of the pieces I have knitted together?

      Yes, it does matter, because if you didn’t think things through there’s bound to be a case you didn’t remember to test and that will make everything break terribly.

      In fact . .. If you think we have to understand every tiny piece then there should be no high level languages. Back to writing machine code!

      Please! I may not know tor care about the inner mechanisms that make a system behave in such or such manner, but I care about how it responds to certains inputs.
      Or to give a specific example: I may not know about the implementation of object properties in JavaScript, but I most definitely expect them to work in accordance to my conceptual model of them.

      Reply
  18. Paul Gehrman

    This article should be entitled Seven Rules for All Programmers. Simple solutions to problems will always be more elegant and appropriate than “astronaut” design patterns. And Rule number 7 really hits the nail on the head: “getting rid of the bad programming language habits you picked up at the university”. The bloated (theoretical) OO approach to software design that is taught in many university CS departments has set our industry back.

    Reply
  19. Theraot

    “ten or twelve line limit? good luck; i wrote a 623 line case statement last night for setting user color preferences on multiple charts. how do you do that in ten or twelve lines?”

    I would add: and without fancy language features or abstract constructs. (In particular if you are writting Assembler :P, ok, that’s not a beginner but it’s not good to teach something to later have to teach the opposite)

    Anyways I prefer the switch over type discovery, late binding or reflection…. I’d consider a database, unless you don’t plan to update or you are running a web where you modify the source if the need comes.

    If I were writing the list I would have said:
    – Avoid arbitrary numbers, if you need a constant declare it as such, and consider if it may be configurable by the user. Please note that putting a maximum size to methods is also an arbitrary number.

    Reply
  20. Chris

    Awful advice! You are saying it’s okay to copy-paste from another program then? How about creating a library to avoid all of this duplication!?

    #4 – LEARN! Don’t simply avoid using something you don’t understand. Software development is a constant learning process.

    REVERSE #6! Aim for abstract interfaces over creating duplicate concrete types.

    This article makes me sick.

    Reply
  21. Dave Holbon

    Limiting code to a few lines (ten or twelve per procedure) automatically leads to “spaghetti” code that’s very difficult to de-bug… yes have each “procedure” isolated but this I’m afraid is in the eye of the beholder and the environment your working in.

    You try de-bugging someone else’s code that’s been written using this logic, a better description would have been to “normalise” your code – as in database design.

    Reply
  22. Bela

    bullshit: if you never use things that you are not sure then you will never learn new things.
    i would suggest the opposite: try out new things and see how they work
    if you learn a new language then try out all features one after the other,
    make sure you understand them correctly
    ( although don’t put these trial stuff into production code )

    ALWAYS test your code thoroughly even if there is a test department.
    NEVER check-in the simpliest change without testing

    starting a new feature with writing test cases and tools is a good approach,
    use stubs for things that are not yet ready


    I agree that things should be kept as simple as possible so as the KISS rule says:
    Keep It Simple and Stupid
    abstraction is a way to make things simpler so don’t be afraid making abstractions
    that’s quite a natural way how human brain works, nothing wrong in it

    Rewrite your code (or others code) if you have the slightest doubt in it,
    or if you have a new idea how to make it simpler >> but don’t forget to test it

    put enough comments into code so that other could quickly get the idea what your code does
    (and don’t forget to change the comments if you change your code )

    Reply
  23. Will Wayne

    Different people learn in different ways:

    Some require a thorough understanding of the abstract before the concrete has any context or meaning.
    For others, grasping the atomic concrete details first is required before the abstract can come into focus.

    This is, of course, far too simplistic – often we require iteration between the abstract and concrete worlds in a sort of negative feedback loop…but we all start at different points and with different emphasis.

    Reply
  24. Gaurav Verma

    I cant agree with 3 and 6.
    Fancy new features are created for a purpose. I use C# and Why would I not use fancy things like Closures, Lamdas and so on….

    Similarly there is a benefit of abstract, gives clear thinking and avoids so many if – then – else
    What you are saying may make sense for Procedural language but in OO world you are dead wrong.

    Reply
  25. Zvonko

    One Rule to rule them all,
    One Rule to find them,
    One Rule to bring them all
    and in the darkness bind them…

    The Rule is:

    All your colleagues should be able to understand your code

    Reply
  26. Yurash

    1. Do not write long procedures…
    5. …Use as few files as possible.
    => You will have large files with a whole lot of small procedures in each? :)

    Is it good, really? There is a balance between length of methods, complexity of classes, number of modules, abstraction levels etc. Yes, you need some experience to find this balance…

    The problem of complexity should be taken in completeness.
    You should try make things as simple as possible, BUT NOT SIMPLIER (c) A.Einstein
    If the problem domain has some complexity, the software should be adequate.
    So, for beginners – undertake simple problems :)

    As to copy-past – I think you could use it, but then always DRY your code, i.e. refactor to remove duplication.
    In case of the code to be maintained in the future, of cause.

    Reply
  27. Pingback: Всем сотрудникам отдела! «

  28. Pingback: 7 regels voor beginnende programmeurs » Blog.NoiK.nl

  29. Marshall

    Thanks Paul V. for posting these useful and important rules as guidelines for beginners.

    I agree with Bob:

    “1) Make judicious of comments and 2) Make variable names meaningful.”

    I agree with Joe:

    “I would make it number two and rephrase it as; If the proceedure is more than 12 lines long one need to re-examine its purpose and make sure that purpose is clear before proceeding.”

    I agree with Paul:

    “This article should be entitled Seven Rules for All Programmers.”

    Reply
  30. Joshua

    Along the lines of cutting and pasting, I would include, also, don’t repeat code to do the same thing in two different places. This also plays into short procedures. My theory is that if under two or more conditions you repeat more than four lines of code to do the same basic thing you WILL have a failure…especially if you cut and paste. Instead, of course, find the defining variables of the problem and offload to a procedure.

    Reply
  31. David Roh

    Rule #1 is BS – it’s dogma such as this that creates a whole generation of poor programmers.

    Dogma rules are design to help those who cannot think and craft quality code on their own.

    The developer should be able to think for themselves and craft a logically coherent, easy to understand method that accomplishes what its name implies, making the method only as complex as it needs to be to accomplish its task and no more complex.

    Many calls to small methods can not only reduce performance but can make the code much more difficult to understand – allowing significant portions of the task logic to be hidden in places that are time consuming to find and understand to get a complete picture of the method’s task.

    Methods should typically (but not always) be blocks of code that are reused in more than one place.

    In short, stay away from dogma rules and learn to craft code that is easy to understand, easy to maintain, and performs its required task in a reliable and performant manner.

    Good code development is a craft – not a set of dogma rules.

    Reply
  32. Pingback: gOODiDEA.NET

  33. S

    I love it when people suggest others look for different work when their approach may not be in line with theirs. So pretentious.

    Reply
  34. Raj Chaudhuri

    Firstly, yes. To all points.

    But secondly, in these multicore, parallelofied days, perhaps some of these should change a bit?

    Reply
  35. Pingback: Quelles règles les programmeurs débutants devraient-ils toujours respecter ? Un développeur expérimenté livre ses 7 règles d’or | Flomicro astuces & outils… NTIC…

Leave a Reply