Programming

10 Basic Programming Principles Every Programmer Must Know

Anthony Grant Updated 14-07-2020

It’s easy to write code. It’s challenging to write good code.

Bad code comes in many forms. Messy code, massive if-else chains, programs that break with one adjustment, variables that don’t make sense. The program might work once but will never hold up to any scrutiny.

Don’t settle for shortcuts. Aim to write code that is easy to maintain. Easy for you to maintain, and easy for any other developer on your team to maintain. How do you write effective code?  You write good code by being disciplined with programming principles.

Here are 10 programming principles that will make you a better coder.

1. Keep It Simple, Stupid (KISS)

It sounds a little harsh, but it’s a coding principle to live by. What does this mean?

It means you should be writing code as simple as possible. Don’t get caught up in trying to be overly clever or showing off with a paragraph of advanced code. If you can write a script in one line, write it in one line.

Here’s a simple function:

function addNumbers(num1,num2){
 return num1 + num2;
}

Pretty simple. It’s easy to read and you know exactly what is going on.

Use clear variable names. Take advantage of coding libraries to use existing tools. Make it easy to come back after six months and get right back to work. Keeping it simple will save you the headache.

2. Write DRY Code

The Don’t Repeat Yourself (DRY) principle means, plainly, not repeating code. It’s a common coding mistake. When writing code, avoid duplication of data or logic. If you’ve ever copied and pasted code within your program, it’s not DRY code.

Take a look at this script:

function addNumberSequence(number){
 number = number + 1;
 number = number + 2;
 number = number + 3;
 number = number + 4;
 number = number + 5;
 return number;
}

Instead of duplicating lines, try to find an algorithm that uses iteration. For loops, and while loops are ways to control code that needs to run multiple times.

DRY code is easy to maintain. It’s easier to debug one loop that handles 50 repetitions than 50 blocks of code that handle one repetition.

3. Open/Closed

This principle means you should aim to make your code open to extension but closed to modification. This is an important principle when releasing a library or framework that others will use.

For example, suppose you’re maintaining a GUI framework. You could release for coders to directly modify and integrate your released code. But what happens when you release a major update four months later?

Their code will break. This will make engineers unhappy. They won’t want to use your library for much longer, no matter how helpful it may be.

Instead, release code that prevents direct modification and encourages extension. This separates core behavior from modified behavior. The code is more stable and easier to maintain.

4. Composition Over Inheritance

If you write code using object-oriented programming A Beginner's Guide to Python Object-Oriented Programming To take full advantage of Python's strengths, you'll want to learn how Python works with object-oriented programming (OOP). Read More you’re going to find this useful. The composition over inheritance principle states: objects with complex behaviors should contain instances of objects with individual behaviors. They should not inherit a class and add new behaviors.

Relying on inheritance causes two major issues. First, the inheritance hierarchy can get messy in a hurry. You also have less flexibility for defining special-case behaviors. Let’s say you want to implement behaviors to share:

Object oriented programming principles

Composition programming is a lot cleaner to write, easier to maintain and allows flexibility defining behaviors. Each individual behavior is its own class. You can 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 provide one specific functionality. As Robert C. Martin puts it, “A class should have only one reason to change.”

Classes and modules Instance vs. Static vs. Class Methods in Python: The Important Differences Python method types can be confusing for beginners. That's why we wrote this quick guide to understanding the differences and when to use each one. Read More often start off this way. Be careful not to add too many responsibilities as classes get more complicated. Refactor and break them up into smaller classes and modules.

The consequence of overloading classes is twofold. First, it complicates debugging when you’re trying to isolate a certain module for troubleshooting. Second, it becomes more difficult to create additional functionality for a specific module.

6. Separation of Concerns

The separation of concerns principle is an abstract version of the single responsibility principle. This idea states that a program should be designed with different containers, and these containers should not have access to each other.

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

For example, the code that handles the database doesn’t need to know how to render the data in the browser. The rendering code takes input from the user, but the logic code handles the processing. Each piece of code is completely independent.

The result is code that is easy to debug. If you ever need to rewrite the rendering code, you can do so without worrying about how the data gets saved or the logic gets processed.

7. You Aren’t Going to Need It (YAGNI)

This principle means you should never code for functionality on the chance that you may need in the future. Don’t try and solve a problem that doesn’t exist.

In an effort to write DRY code, programmers can violate this principle. Often inexperienced programmers try to write the most abstract and generic code they can. Too much abstraction causes bloated code that is impossible to maintain.

Only apply the DRY principle only when you need to. If you notice chunks of code written over and over, then abstract them. Don’t think too far out at the expense of your current code batch.

8. Document Your Code

Any senior developer will stress the importance of documenting your code with proper comments. All languages offer them and you should make it a habit to write them. Leave comments to explain objects, enhance variable definitions, and make functions easier to understand.

Here’s a JavaScript function with comments guiding you through the code:


//This function will add 5 to the input if odd, or return the number if even
function evenOrOdd(number){
 //Determine if the number is even
 if(number % 2 == 0){
 return number;
 }
 //If the number is odd, this will add 5 and return 
 else {
 return number + 5;
 }
}

Leaving comments is a little more work while you’re coding, and you understand your code pretty well right?

Leave comments anyway!

Try writing a program, leaving it alone for six months, and come back to modify it. You’ll be glad you documented your program instead of having to pour over every function to remember how it works. Work on a coding team? Don’t frustrate your fellow developers by forcing them to decipher your syntax.

9. Refactor

Code for coding principles

It’s hard to accept, but your code isn’t going to be perfect the first time. Refactoring code means reviewing your code and looking for ways to optimize it. Make it more efficient while keeping the results exactly the same.

Codebases are constantly evolving. It’s completely normal to revisit, rewrite, or even redesign entire chunks of code. It doesn’t mean you didn’t succeed the first time you wrote your program. You’re going to get more familiar with a project over time. Use that knowledge to adjust your existing code to be DRY, or following the KISS principle.

10. Clean Code At All Costs

Leave your ego at the door and forget about writing clever code. The kind of code that looks more like a riddle than a solution. You’re not coding to impress strangers.

Don’t try to pack a ton of logic into one line. Leave clear instructions in comments and documentation. If your code is easy to read it will be easy to maintain.

Good programmers and readable code go hand-in-hand. Leave comments when necessary. Adhere to style guides, whether dictated by a language or your company.

What Makes a Good Programmer?

Learning how to be a good programmer takes quite a bit of work! These 10 coding principles are a roadmap to becoming a professional programmer.

A good programmer understands how to make their apps easy to use, works well within a team, and finishes projects to specification and on time. By following these principles you will set yourself up for success in your programming career. Try out these 10 beginner programming projects The 10 Best Beginner Projects for New Programmers Want to learn programming but don't know where to start? These beginner programming projects and tutorials will start you off. Read More and review your code. See if you’re sticking to these principles. If not, challenge yourself to improve your code.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

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

  1. sayed
    March 7, 2019 at 9:43 am

    Very Very Informative , really good writting

  2. 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.

  3. 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.'

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

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

  5. 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?

  6. 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.

    • Ted Johansson
      December 20, 2017 at 9:12 am

      Yes. This.

  7. 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.

    • Matt Jones
      November 28, 2017 at 7:48 pm

      I call it self documenting code, a method, variable or paramter should explain what its purpose is.

  8. 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.

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

    Great Article... Great Advice!!!

  10. 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 :)

  11. 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.

  12. 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

  13. 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.