10 Basic Programming Principles Every Programmer Must Follow
Pinterest Stumbleupon Whatsapp
Advertisement

Anyone can write code. But good code? That’s where it gets tough.

We’ve all heard horror stories about spaghetti code, massive if-else chains, entire programs that can break just by changing one variable, functions that look like they were obfuscated, and so on. That’s what happens when you try to make a shippable product with only a semester of programming experience under your belt.

Don’t settle for writing code that works. Aim to write code that can be maintained — not only by yourself, but by anyone else who may end up working on the software at some point in the future. To that end, here are several principles to help you clean up your act.

1. KISS

The “keep it simple, stupid” principle applies to pretty much all of life, but it’s especially necessary in medium-to-large programming projects.

It starts way in the beginning when you’re defining the scope of what you want to create. Just because you’re passionate about game development doesn’t mean you can create the next World of Warcraft or Grand Theft Auto. When you think you’ve simplified enough, simplify it one level further — feature creep is inevitable, so start small.

10 Basic Programming Principles Every Programmer Must Follow programming principle programming

But even after coding has begun, keep it simple. Complex code takes longer to design and write, is more prone to bugs and errors, and is harder to modify later down the road. In the wise words of Antoine de Saint-Exupery, “Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”

2. DRY

The “don’t repeat yourself” principle is crucial for clean and easy-to-modify code. When writing code, you want to avoid duplication of data and duplication of logic. If you notice the same chunk of code being written over and over again, you’re breaking this principle.

The opposite of DRY code is WET code: “write everything twice” (or “waste everyone’s time”). One of the best ways to diagnose WET code is to ask yourself: in order to alter the program’s behavior in some way, how many areas of code would you need to modify?

Suppose you’re writing a podcast directory app. On the search page, you have code for fetching a podcast’s details. On the podcast page, you have code to fetch that podcast’s details. On the favorites page, the same fetching code. Consider abstracting all of that into a function so that if you need to edit it later, you can do it all in one spot.

3. Open/Closed

Whether you’re writing objects in Java or modules in Python, you should aim to make your code open to extension but closed to modification. This applies to all kinds of projects, but is especially important when releasing a library or framework meant for others to use.

For example, suppose you’re maintaining a GUI framework. You could release it as-is, expecting end users to directly modify and integrate your released code. But what happens when you release a major update four months later? How do they implement all of your additions without throwing away all the work they’ve done?

Instead, release code that prevents direct modification and encourages extension. This separates core behavior from modified behavior. The benefits? Greater stability (users can’t accidentally break core behavior) and greater maintainability (users only worry about extended code). The open/closed principle is key to making a good API What Are APIs, And How Are Open APIs Changing The Internet What Are APIs, And How Are Open APIs Changing The Internet Have you ever wondered how programs on your computer and the websites you visit "talk" to each other? Read More .

4. Composition > Inheritance

The “composition over inheritance” principle states that objects with complex behaviors should do so by containing instances of objects with individual behaviors rather than inheriting a class and adding new behaviors.

Overreliance on inheritance can lead to two major issues. First, the inheritance hierarchy can become messy in the blink of an eye. Second, you have less flexibility for defining special-case behaviors, particularly when you want to implement behavior from one inheritance branch in another inheritance branch:

10 Basic Programming Principles Every Programmer Must Follow programming principle composition inheritance

Composition is a lot cleaner to write, easier to maintain, and allows for near-infinite flexibility as far as what kinds of behaviors you can define. Each individual behavior is its own class, and you create complex behaviors by combining individual behaviors.

5. Single Responsibility

The single responsibility principle says that every class or module in a program should only concern itself with providing one bit of specific functionality. As Robert C. Martin puts it, “A class should have only one reason to change.”

Classes and modules often start off this way, but as you add features and new behaviors, it’s easy for them to evolve into God classes and God modules that take up hundreds, or even thousands, of lines of code. At this point, you should break them up into smaller classes and modules.

6. Separation of Concerns

The separation of concerns principle is like the single responsibility principle but on a more abstract level. In essence, a program should be designed so that it has many different non-overlapping encapsulations, and these encapsulations shouldn’t know about each other.

A well-known example of this is the model-view-controller (MVC) paradigm, which separates a program into three distinct areas: the data (“model”), the logic (“controller”), and what the end user sees (“view”). Variations of MVC are common in today’s most popular web frameworks.

10 Basic Programming Principles Every Programmer Must Follow programming principle mvc pattern
Image Credit: Wikimedia

For example, the code that handles the loading and saving of data to a database doesn’t need to know how to render that data on the web. The rendering code may take input from the end user, but then passes that input to the logic code for processing. Each part handles itself.

This results in modular code, which makes maintenance much easier. And in the future, if you ever need to rewrite all of the rendering code, you can do so without worrying about how the data gets saved or the logic gets processed.

7. YAGNI

The “you aren’t gonna need it” principle is the idea that you should never code for functionality that you may need in the future. Chances are, you won’t need it and it will be a waste of time — and not only that, but it will needlessly increase your code’s complexity.

You could view this as a specific application of the KISS principle and a response to those who take the DRY principle too seriously. Often inexperienced programmers try to write the most abstract and generic code possible to avoid WET code, but too much abstraction ends up in bloated impossible-to-maintain code.

The trick is to apply the DRY principle only when you need to. If you notice chunks of code being written over and over, then abstract them — but never when you think a piece of code will be written over and over. More times than not, it won’t be.

8. Avoid Premature Optimization

The no premature optimization principle is similar to the YAGNI principle. The difference is that YAGNI addresses the tendency to implement behaviors before they’re necessary while this principle addresses the tendency to speed up algorithms before it’s necessary.

The problem with premature optimization is that you can never really know where a program’s bottlenecks will be until after the fact. You can guess, of course, and sometimes you may even be right. But more often than not, you’ll waste valuable time trying to speed up a function that isn’t as slow as you think or doesn’t get called as often as you’d expect.

Reach your milestones as simply as you can, then profile your code to identify true bottlenecks.

9. Refactor, Refactor, Refactor

One of the hardest truths to accept as an inexperienced programmer is that code rarely comes out right the first time. It may feel right when you implement that shiny new feature, but as your program grows in complexity, future features may be hindered by how you wrote that early one.

10 Basic Programming Principles Every Programmer Must Follow programming principle coding

Codebases are constantly evolving. It’s completely normal to revisit, rewrite, or even redesign entire chunks of code — and not just normal, but healthy to do so. You know more about your project’s needs now than when you did at the start, and you should regularly use this newly gained knowledge to refactor old code.

Note that it doesn’t always have to be a big process. Take a page from the Boy Scouts of America, who live by these words: “Leave the campground cleaner than you found it.” If you ever need to check or modify old code, always clean it up and leave it in a better state.

10. Clean Code > Clever Code

Speaking of clean code, leave your ego at the door and forget about writing clever code. You know what I’m talking about: the kind of code that looks more like a riddle than a solution and exists solely to show off how smart you are. The truth is, nobody really cares.

One example of clever code is packing as much logic into one line as possible. Another example is exploiting a language’s intricacies to write strange but functional statements. Anything that might cause someone to say “Wait, what?” when poring over your code.

Good programmers and readable code go hand in hand. Leave comments when necessary. Adhere to style guides, whether dictated by a language (like Python) or a company (like Google). Observe per-language idioms and stop writing Java code in Python or vice versa. See our article on tips for writing cleaner code 10 Tips for Writing Cleaner & Better Code 10 Tips for Writing Cleaner & Better Code Writing clean code looks easier than it actually is, but the benefits are worth it. Here's how you can start writing cleaner code today. Read More .

What Makes a Good Programmer?

Ask five people and you’ll get 10 different answers. To me, a good programmer is one who understands that coding should ultimately serve the end user, who is easy to work with in a team, and who finishes his projects to specification and on time.

If you’re just starting out, don’t worry too much about that yet. Focus on learning how to code without stress. If you feel stuck, see our article on overcoming programmer’s block. And if you just aren’t happy writing code, read our article on signs you aren’t meant to be a programmer 6 Signs That You Are Not Meant To Be A Programmer 6 Signs That You Are Not Meant To Be A Programmer Not everyone is cut out to be a programmer. If you aren't completely sure that you're meant to be a programmer, here are some signs that may point you in the right direction. Read More .

How would you define a good programmer? Got any tips for inexperienced programmers who want to improve? Share with us down in the comments below!

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. mike
    November 8, 2017 at 1:12 am

    The only thing I can add is practice makes perfect. There are only a few people that have "that something" that is a notch above most everyone else. I can only explain this through an analogy. Back in the days of building your own circuits (remember soldering irons) you could give the same problem or diagram to two people and while the circuit would work the guy with "that something" would create an elegant product.

    The same is true of programming.

  2. Richard Lockley
    October 30, 2017 at 4:29 pm

    Try SATE - Start At The End - as a methodology. All output comes from one of two places - either from the input, or as a result of calculation(s), no matter the language. True of most engineering tasks as well. Field by field, function by function, determine what you want to achieve first, then work the problem 'backward.'

  3. Jaden Peterson
    October 30, 2017 at 4:23 am

    Why are CSS and HTML shown on every image? Neither are technically programming languages.

  4. mearnsgeek
    October 28, 2017 at 12:48 pm

    "Often inexperienced programmers try to write the most abstract and generic code possible to avoid WET code,"

    This touches on something I feel is important but haven't really seen. I'd call it DBD - Don't Be Dogmatic.

    It's very easy for quasi-religions to be built up around the latest programming buzzword and trend. A result of this, often for less experienced developers, is that programming practice becomes an act of blindly following these new instructions "because they're the latest best practice" - often to the point of creating other problems as you point out in your sentence I quoted.

    Read up on some classic books "Code Complete", "The Art of Programming" (Brian Kernighan), "Design Patterns" etc and see what techniques apply to the problem you're working on.

    Each programming task is unique - don't blindly use the same tools for each job. Just because they have a hammer, does a carpenter use that for every carpentry job?

  5. Red
    October 27, 2017 at 8:13 pm

    A good developer knows English. I've met a bunch and only the ones born in the US could you have a conversation with. Most of them just answer "Yes". To something. Not what I was asking, that's sure.

  6. GreenRaccoon23
    October 27, 2017 at 6:29 am

    YAGNI- My boss says it this way: "Don't solve problems you don't have."

    I don't know a name for it, but here's another one: Explain with code, not comments. The best code explains itself better than any comments could. Sometimes it just isn't possible, but most of the time, a need for comments is a clue that the code has unnecessary complexity or that there's a simpler way to structure it.

  7. Hildy J
    October 27, 2017 at 3:14 am

    Think first, plan second, diagram third, code fourth, test fifth, sixth, seventh, etc.

    Document what you are doing and why you are doing it in the code at every level - from the purpose of the program to the use of each field.

    Check your data - you will get garbage on occasion and it can be malicious so don't send data forward for processing until you have verified that it is data in the length and format you expect.

    • Jonathan
      October 27, 2017 at 9:12 pm

      Or test fourth, and then code fifth.
      Your test then becomes your documentation.

    • mearnsgeek
      October 28, 2017 at 12:36 pm

      Extend your first sentence with " but use your judgement".

      Often a prototype is a better approach, both for yourself and particularly if you're writing software for a client who, even if they designed and wrote a spec themselves, need an actual "working" prototype to see if that's what they *really* want.

      Don't be too attached to your prototype though. Be prepared to throw away that code rather than turn it into production quality code.

  8. Michael L Treadway
    October 27, 2017 at 2:52 am

    Great Article... Great Advice!!!

  9. Fred Steffen
    October 26, 2017 at 11:57 pm

    Thank you! This is a great article and I try and apply all of these every day. Premature optimization and overuse of patterns for the sake of premature optimization has killed a ton of projects. But, it also keeps me in work :)

  10. Charles Stepp
    October 26, 2017 at 11:56 pm

    Many of these principles, and several forgotten ones were covered in the forgotten classic, "Structured Design: Fundamentals of a Discipline of Computer Program and Systems Design" by Yourdon and Constantine

    • Marco
      October 27, 2017 at 7:32 pm

      I'm going to check that book out, thanks for the tip.

  11. Dima
    October 26, 2017 at 10:18 pm

    Composition over inheritance — the author clearly never heard of interfaces.

    Premature optimization — experienced developer can and should predict common bottlenecks.

    • Le Anh Quan
      October 27, 2017 at 1:50 pm

      Hi Dima, interface does not count here. Actually composition in OOP world is tough and verbose, FP would suite more

  12. Howard A Pearce
    October 26, 2017 at 9:28 pm

    Most of this seems to be what make good programming - not what makes a good programmer.

    Number 1 on my list is the ability to be logical in one's thinking which now all people are good at.
    It is this logic which allow one to apply the principles of programming mentioned above.