10 Basic Programming Principles Every Programmer Must Know

Trending 3 weeks ago

Key Takeaways

  • Keep It Simple, Stupid (KISS): Write codification that is arsenic elemental arsenic possible. Avoid being overly clever and usage clear adaptable names.
  • Write DRY Code: Avoid duplicating code; make usage of functions, loops, and algorithms instead. DRY codification is easier to support and debug.
  • Open/Closed: Write codification that is unfastened to hold but closed to modification. Prevent nonstop modification and promote hold for much unchangeable and maintainable code.

It's easy to constitute codification yet challenging to constitute bully code. Embracing basal programming principles is simply a surefire measurement to constitute high-quality codification that is efficient, readable, reliable, secure, and maintainable, sloppy of nan size of a package project.

Bad codification comes successful galore forms: messy, monolithic if-else chains, unreliable programs, variables that don't make sense, etc. How do you constitute effective code? With subject and purpose. Here are nan halfway programming principles that will make you a amended coder.

1. Keep It Simple, Stupid (KISS)

It sounds a small harsh, but it's 1 of nan astir important principles to adopt erstwhile you’re writing machine code. What does KISS mean?

It intends you should beryllium penning codification arsenic elemental arsenic possible. One of nan rules of basal programming is to ne'er get caught up successful trying to beryllium overly clever aliases showing disconnected pinch a heavy artifact of precocious code. If you tin constitute a book successful 1 line, constitute it successful 1 line.

Here's a elemental function:

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

Pretty simple. It's easy to read, and you cognize precisely what is going on.

One programming rule successful this tone is to usage clear adaptable names. Take advantage of coding libraries and usage existing tools. Make it easy to travel backmost aft six months and get correct backmost to work. Keeping things elemental will prevention you truthful overmuch needless suffering down nan line.

2. Write DRY Code

The Don't Repeat Yourself (DRY) machine programming rule means, plainly, not repeating code. It's a communal coding mistake. When penning code, debar plagiarism of information aliases logic. If you've ever copied and pasted codification wrong your program, it's not DRY code.

Take a look astatine 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, effort to find an algorithm that uses a loop instead.

DRY codification is easy to maintain. It's easier to debug 1 loop that handles 50 repetitions than 50 blocks of codification that grip 1 repetition each.

3. Open/Closed

Working pinch a consciousness of bully programming principles will streamline your activity and make it much effective.

This rule of programming intends that you should purpose to make your codification unfastened to hold but closed to modification. It ensures that you create codification that doesn't request to beryllium modified moreover erstwhile requirements change. This is an important rule erstwhile releasing a room aliases model that others will use.

For example, suppose you're maintaining a GUI framework. You could merchandise a type for coders to modify and merge your released codification directly. What happens erstwhile you merchandise a awesome update 4 months later, though?

Their codification will break. This will apt make your cohorts very unhappy. They won't want to usage your room for overmuch longer, nary matter really adjuvant it whitethorn person been successful its heyday.

Instead, merchandise codification that prevents nonstop modification and encourages extension. Basic programming principles for illustration this abstracted halfway behaviour from modified behavior. The codification is much unchangeable and easier to maintain.

4. Composition Over Inheritance

If you constitute codification utilizing object-oriented programming, you're going to find this rule of programming to beryllium very useful. The creation complete inheritance rule states that objects pinch analyzable behaviors should incorporate instances of objects pinch individual behaviors. They should not inherit a people and adhd caller behaviors.

Relying connected inheritance causes 2 awesome issues. First, nan inheritance level tin get messy successful a hurry. You besides person little elasticity successful defining special-case behaviors. Let's opportunity you want to instrumentality behaviors to share:

Programming principles that favour simplicity will often group nan shape for a much effective last result.

Composition programming is cleaner to write, easier to maintain, and allows for flexibility-defining behaviors. Each individual behaviour is its ain class. You tin create analyzable behaviors by combining individual behaviors.

5. Single Responsibility

 amended codification written by much knowledgeable programmers.

The azygous work rule states that each people aliases module successful a programme should only supply 1 circumstantial functionality. As Robert C. Martin puts it, "A people should person only 1 logic to change."

Classes and modules often commencement disconnected this way. Be observant not to adhd excessively galore responsibilities arsenic classes get much complicated. Refactor and break them up into smaller classes and modules.

The consequence of overloading classes is twofold. First, it complicates debugging erstwhile you're trying to isolate a definite module for troubleshooting. Second, it becomes much difficult to create further functionality for a circumstantial module. Good programming principles forestall these problems earlier they go problems to woody with.

6. Separation of Concerns

The separation of concerns conception is an absurd type of nan azygous work principle. This thought states that you should creation programs pinch different parts, and these parts should not person entree to each other.

A well-known illustration of this is nan model-view-controller (MVC) design. MVC separates a programme into 3 chopped areas: nan information (model), nan logic (controller), and what nan page displays (view). Variations of MVC are communal successful today's astir celebrated web frameworks.

For example, nan codification that handles nan database doesn't request to cognize really to render nan information successful nan browser. The rendering codification takes input from nan user, but nan logic codification handles nan processing. Each portion of codification is wholly independent.

The consequence is codification that is easy to debug. If you ever request to rewrite nan rendering code, you tin do truthful without worrying astir really nan information gets saved aliases nan logic gets processed.

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

Some coding principles are much straightforward than others.

This principle intends you should ne'er codification for functionality connected nan disconnected chance that you whitethorn request thing successful nan future. One of nan astir important principles of machine programming to study is that you shouldn't effort to lick a problem that doesn't exist.

In an effort to constitute DRY code, programmers whitethorn break this principle. Often, inexperienced programmers effort to constitute nan astir absurd and generic codification that they can. Too overmuch abstraction, however, causes bloated codification that's intolerable to maintain.

Only use DRY programming principles erstwhile you request to; if you announcement chunks of codification written complete and over, instrumentality a furniture of abstraction. Don't deliberation excessively acold up astatine nan disbursal of your existent codification batch.

8. Document Your Code

With each of this talk astir nan principles of coding, it tin beryllium easy to hide astir nan quality connected nan different broadside who whitethorn yet beryllium getting into your codification themselves.

Any elder developer will accent nan value of documenting your codification pinch due comments. All languages connection them; you should make it a wont to constitute them. Leave comments to explicate objects, heighten adaptable definitions, and make functions easier to understand.

Here's a JavaScript usability pinch comments guiding you done nan code:


function evenOrOdd(number) {
    
    if (number % 2 == 0) {
        return number;
    }
    
    else {
        return number + 5;
    }
}

Leaving comments is simply a small much activity while you're coding. It takes clip and steals your attraction distant from nan existent activity astatine hand. You understand your codification beautiful good anyway, right? Who cares? It's worthy remembering that thing is disposable, moreover successful nan world of tech. What is simply a machine programming rule astatine nan extremity of nan time if nan personification connected nan different broadside ends up getting lost?

We urge going nan other mile and leaving comments anyplace you interest that things will go murky aliases unclear, particularly erstwhile collaborating pinch others. Don't frustrate your chap developers by forcing them to decipher your syntax.

Try penning a program, leaving it unsocial for six months, and returning to modify it. You'll beryllium gladsome you documented your programme alternatively of having to move complete each usability to retrieve really it works.

9. Refactor

This programming rule encourages you to ever look astatine your activity pinch caller eyes.

It's difficult to accept, but your codification isn't going to beryllium cleanable nan first time. Refactoring codification intends reviewing your codification and looking for ways to optimize it, making it much businesslike while keeping nan results precisely nan same. This is simply a information for writing cleaner and value code.

Codebases are perpetually evolving. One of nan principles of programming is remembering that it's wholly normal to revisit, rewrite, aliases moreover redesign full chunks of code.

It doesn't mean you didn't win nan first clip you wrote your program; you're inevitably going to get much acquainted pinch a task complete time. Use that knowledge to set yourself arsenic you make progress.

10. Clean Code astatine All Costs

Aside from each nan basal programming principles, time off your ego astatine nan doorway and hide astir penning clever code. When we opportunity this, we mean nan benignant of codification that looks much for illustration a riddle than a solution. You're not coding to impressment strangers. You're successful this occupation to lick problems.

Don't effort to battalion a ton of logic into 1 line. Leave clear instructions successful your comments and documentation. If your codification is easy to read, it will besides usually beryllium easy to maintain.

Good programmers and readable codification spell hand-in-hand. Leave comments erstwhile necessary, adhere to style guides, and put yourself successful nan adjacent guy's shoes whenever possible.

Learn nan Principles of Computer Programming to Be a Good Programmer

Learning really to beryllium a bully programmer takes rather a spot of clip and effort. These rules of basal programming are a roadmap to becoming a master programmer. By pursuing these time-honored principles, you’ll group yourself up for occurrence successful your early programming career.

Source Tutorials
Tutorials