Importance of Coding Principles

Posted By : Arun Singh | 29-Aug-2019

 

Follow this coding principle to save a lot of time when you are writing a quality application for your client.

 

SOLID  Principle

 

S - Single Responsibility Principle
In programming, every modules/class should have responsibility for a single part of the functionality provided by the software.

For example 
How to write a piece of code that violates this principle.

class User
{
    void CreatePost(Database db, string postMessage)
    {
        try
        {
            db.Add(postMessage);
        }
        catch (Exception ex)
        {
            db.LogError("An error occured: ", ex.ToString());
            File.WriteAllText("\LocalErrors.txt", ex.ToString());
        }
    }
}

 

Can we write like this
 

class Post
{
    private ErrorLogger errorLogger = new ErrorLogger();

    void CreatePost(Database db, string postMessage)
    {
        try
        {
            db.Add(postMessage);
        }
        catch (Exception ex)
        {
            errorLogger.log(ex.ToString())
        }
    }
}

class ErrorLogger
{
    void log(string error)
    {
      db.LogError("An error occured: ", error);
      File.WriteAllText("\LocalErrors.txt", error);
    }
}

 

Abstracting functionality that handles the error logs, we have no need longer violet the single responisbility principle.

O — Open/closed principle
"Software entities like (classes, modules, functions etc) should be open for extensions, but they closed for modification", If you have good knowledge of OOP, you already know about polymorphism. We knows inheritance and/or implementing an interface that enables classes to polymorphic substitute for each other.

For example 
How to write a piece of code that violates this principle.
 

class Post
{
    void CreatePost(Database db, string postMessage)
    {
        if (postMessage.StartsWith("#"))
        {
            db.AddAsTag(postMessage);
        }
        else
        {
            db.Add(postMessage);
        }
    }
}

Can we write like this
 

class Post
{
    void CreatePost(Database db, string postMessage)
    {
        db.Add(postMessage);
    }
}

class TagPost : Post
{
    override void CreatePost(Database db, string postMessage)
    {
        db.AddAsTag(postMessage);
    }
}

L — Liskov substitution principle
Liskov substitution principle parent classes should be easily acting with their child classes without breaking up the application.

Let’s take an example of Animal parent class.

public class Animal {
    public void makeNoise() {
        System.out.println("I am making noise");
    }
}

Now Cat and Dog classes which extends Animal class.

public class Dog extends Animal {
    @Override
    public void makeNoise() {
        System.out.println("bow wow");
    }
}

public class Cat extends Animal {
    @Override
    public void makeNoise() {
        System.out.println("meow meow");
    }
}

I — Interface Segregation Principle
Interface segregation principle offer that "A client should never be forced to implement an interface that it doesn't use". This principle apply on the interface and all the above three principles applies on classes.

Let’s take an example to understand.

interface IPost
{
    void CreatePost();
}

interface IPostNew
{
    void CreatePost();
    void ReadPost();
}

Can we write like this

interface IPostCreate
{
    void CreatePost();
}

interface IPostRead
{
    void ReadPost();
}

D — Dependency Inversion Principle

This principle offer that "high-level module should not depend on low-level module both should depend on abstractions". It means we should have an object of the interface which helps to communicate with the classes. In this principle, if class A changes the class B doesn't need to care or know about the changes.

let's take an example:

class Post
{
    private ErrorLogger errorLogger = new ErrorLogger();

    void CreatePost(Database db, string postMessage)
    {
        try
        {
            db.Add(postMessage);
        }
        catch (Exception ex)
        {
            errorLogger.log(ex.ToString())
        }
    }
}

Can we write like this
 

class Post
{
    private Logger _logger;

    public Post(Logger injectedLogger)
    {
        _logger = injectedLogger;
    }

    void CreatePost(Database db, string postMessage)
    {
        try
        {
            db.Add(postMessage);
        }
        catch (Exception ex)
        {
            logger.log(ex.ToString())
        }
    }
}

 

Use consistent indentation
Everyone should follow the indentation because it will easy to understand the code and all developer IDE should be the same version so everyone indentation will be same. Once you start making large projects then you'll understand the importance of consistent code styling.

 

Follow the DRY Principle
DRY means "Don't Repeat Yourself".
This principle aimed at reducing the repeating function of the project.

 

Comments
Comments are necessary for good code documentation because without commenting new developer will be confused to understand all functionality.
We know two types of commenting is used in all technologies single line commenting and multi-line commenting.

Single line commenting always used inside the function and above the code line. We can you used single line commenting for modified the line.
Multi line commenting always used before the function. In this commenting, we have to explain the parameter and function functionality. We have to must specify in the multi line comments, if we are calling a single function from different files with different parameter.

Code Reviews
Why code review can be as bad. 


You can conduct review only if you have understood 95% code knowledge and who can monitor all updates without wasting to much time. It will be just time consuming and everyone will hate. Many people think code review is a good way of teaching juniors but the main target of code review it's maintaining code quality, and not teaching.

Why code review can be as good.


Each and every person has own role and responsibility for the exact piece of work in the team. Before start code review both person attitude should be positive and code reviewed person understand the risk of the project. It is impossible to know everything and better excellent understand a small piece of code than all but on 25%.

Refactoring does not work
We know mostly developer says "Don't worry we will refactor it in future". After that in the future, this results in big technology debt or in deleting all the code and writing from scratch. So now don't debt unless you have extra money to develop your software a few times from scratch.

Avoid Deep Nesting
If your code has many levels of nesting can make code harder to read and follow.

For Example
 

```
if (a) {
   
  if (b) {
      
    if (c) {
        
        
        
    }
  }
}
```

Can we write like this
 

```
if (a) {
   return 
}
 
if (b) {
   return 
}  
 
if (c) {
   return 
}  
```

Keep the code simple
Always we have to write simple code.  
The code should always be simple. Complicated logic for achieving simple tasks is something you want to avoid as the logic one programmer implemented a requirement may not make perfect sense to another. So, always keep the code as simple as possible.

For example

if (a < 0 && b > 0 && c == 0) {
   return true;
} else {
   return false;

Can we write like this

return a < 0 && b > 0 && c == 0;

 

Thanks for reading!

About Author

Author Image
Arun Singh

Arun is a MEAN stack developer. He has a fastest and efficient way of problem solving techniques. He is very good in JavaScript and also have a little bit knowledge of Java and Python.

Request for Proposal

Name is required

Comment is required

Sending message..