Principles for Coding and JavaScript objects

Shehan Silva
9 min readFeb 26, 2022

This blog article highlights some main theories a developer should be knowledgeable of and some fundamentals on Javascript. This includes the SOLID Principle , Guidelines for approaching and implementing a solution and some few best practices one should follow for the best possible output.

SOLID Principles

Ø What are SOLID Principles ?

These are a set of principles for object oriented concepts which enhance the project quality in terms of growth and maintenance. This is like a guide as to how to use the OOP concepts in the best possible way.

Ø Breakdown of Solid Principles

S — Single Responsibility Principle.

O — Open-Closed Principle.

L — Liskov Substitution Principle.

I — Interface Segration Principle

D — Dependency Inversion Principle.

· Single Responsibility Principle

This simply means that a class should be responsible for only one task and that it should not carry out two or more tasks. From tasks it is not meant that this class can not have different methods , but those methods should be responsible for one common achievement.

This scenario can be explained as follows ;

Let’s assume you want to create a program using Object Oriented Concepts (OOC)s to calculate and output areas of a figure consisting of different shapes. One may simply create a shape class and extend that to the required shapes with the relevant attributes. And also you need a calculator class , let’s say “AreaCalculator” to calculate the class. Normally this is how you would do it , and there is nothing wrong in this , but what if a user wants the same output in a different format , like JSON. In this scenario , this same class would need to calculate and output , so this is what we meant from different tasks, here the same class performs two different tasks of calculating and outputting in the desired format. And according to this principle this must not be done , instead a different class should be created just to output the result in the required format.

· Open/Close Principle

This in simple terms can be said as “Objects or entities should be open for extension , but closed for modification”.

Which means , in a program , we should not code the solution in a way that a class should be updated for every requirement change , instead we should do it in a way that we can extend the class and reach our objective. For that , the abstraction OOP principle comes into play.

In the previous example , we sent the shapes in an array to another class in which it calculated the area of each shape and gave us the sum. In here , we had to have if/else statement to identify the shape and calculate the area , but what if there were many other shapes , this if else statement ladder would only get much longer and this breaks the Open/Close Principle as we modify the class.

Below is the illustration of the above said piece of code.

public function sum()

{

var i = 0

var sum = 0

foreach (this.shapes as shape) {

if (shape === ‘Square’)) {

area[i] = pow(shape.length, 2);

sum += area[i]

} else if (shape === ‘Circle’)) {

area[i] = Math.PI * pow(shape.radius, 2);

sum += area[i]

}

i++

}

return sum;

}

So instead what we can do is , we can use an interface with the common method implemented in different ways (For this scenario, the area() function in the interface is implemented in different ways in each shape class).

· Liskov Substitution Principle

This principle is based for the inheritance concept in OOP. The definition is as follows “Every subclass/derived class should be able to substitute their parent/base class.”

In simple terms , a child class should perform the basic functionalities a parent class is intended to do and should be relevant for it.That is , a method in the child class should not give a different meaning when overriding the method in the parent class.

· Interface Segregation Principle

As in the definition “A client should never be forced to implement an interface that it doesn’t use, or clients should not be forced to depend on methods they do not use.”

That is , if a we implement an interface with several methods , but in reality is only a few methods that we need , this goes against the principle. Thus we have to have interfaces with the methods of same scope.

There is another solution for this , we can also use the “Default Java method”. Using this , we can implement the method in the interface itself and that will become the default implementation , so that a programmer will not necessarily have to implement that method.

· Dependency Inversion Principle

As in the definition “Higher level modules should not depend on lower level modules , but they should depend on abstractions.” This allows decoupling , which means that for an example two components will not be associated to each other directly instead it will have an interface for that.

Guidelines to approach a software solution

As a software engineer , one should be able to work through the things required to approach the solution in the best way possible , there are many methods defined for this.

ü Think through the problem

ü Divide and Conquer : Dividing the problem into smaller problems to make it manageable and easy to understand.

ü Kiss : Keeping the solution as simple as possible without making it complex.

ü Learn from Mistakes.

ü Reason why the intended software should exist.

Guidelines to implement a software solution

After approaching the solution , the next step is implementing it , so also for that there are a few approaches one can follow ;

YAGNI (You ain’t gonna need it) : This is to stick to the present without overthinking about the future , the code should consist of logic required for the moment only.

DRY (Don’t Repeat Yourselves) : Reuse of code.

Embrace Abstraction : Use Abstraction as far as possible to reduce coupling.

DRITW(Don’t reinvent the wheel) : As you might understand from this very phrase , it is a waste of time to solve something that has already been put a solution for. For an example we do not need to write code to communicate with a database thinking from scratch.

Write code that does one thing well.

Make the code well readable for debugging purposes.

Kaizen — Leave it better than you found it : To fix not just the bug but the code around it too.

Practices

In software development , it is very much essential to carry out the work in the most convenient way possible and for that , there are a set of guidelines to guide programmers through.

Some of the best practices include ;

Ø Unit testing

Unit testing is the first testing method out of the four in software development. Unit tests are just another piece of code to check the smallest testable parts in a program like classes and functions individually whether they work and give the intended output. It is mainly carried out by QA engineers . Although writing this piece of code is also time consuming , it will most probably save your time from the future where you might end up solving many bugs in later testing stages , in case you have not written unit test cases before.

Junit is a tool which is used for unit testing purposes.

Ø Code Quality

Quality code is one key aspect of software maintenance , more the quality , more the convenience to maintain the code. We can maintain code quality by ; Using a code standard , Analyzing code before code reviews , following code review practices , refactoring legacy codes.

Also , there are some quality metrics that can be used to get an idea of the code quality.One such metric is CC (Cyclomatic Complexity) , which measures the number of linearly independent paths through a program. The lesser the CC value , better the code.

There are many tools we can use for code quality testing , one such tool is Sonarqube.

Ø Code Review

This code review process is done by some other person than the programmer itself , it is a pretty straightforward process in which the code completed is demonstrated to the reviewing person by the developer , the reviewer can interrupt and ask questions based on the code to identify fixes to uplift the code quality. This is also known as “peer review”.

One of the best practices of code review , is having a limit for the lines of codes to be reviewed. Statistically it has been found that going through 200–400 lines of codes in a time span of 1 or 1 and half hours would lead to a 70–90% defect discovery.

Sonarqube can be used for this as well.

Ø Version Controlling

This is something that can not be considered just a practice but a must do in software development. Without version controlling it is nearly impossible to work together in a system. This would allow multiple developers to develop the same code base without any conflicts to be occurred , version controlling systems would identify if any conflict occur and give suggestions to rectify them. Github is a popular version controlling tool used by many developers worldwide.

Ø Continuous integration

This is the practice of check-in the code to a shared repository several times a day. This would allow developers to detect issues early and fix them without a delay.

Javascript

Javascript(JS) is a programming language often used with web development. It has been designed by the computer programmer Brendan Eich , also a co-founder of the Mozilla corporation. Browsers use different engines to run JS code as mentioned below ;

· Google : V8

· Mozilla Firefox : SpiderMonkey

· Internet Explorer : Chakra

· Safari(Ios) : JavaScriptCore.

Although Javascript shows many similarities with Java in terms of syntax and libraries, they greatly differ in design.

Some key differences between Java and Javascript are mentioned below ;

Java is statically-typed(Variable types are determined at compile-time) while JS is dynamically-typed(Variable types are determined at run-time)

Java is compiled to bytecode which is executed by the JVM , but in JS , the code is interpreted in browsers and not compiled.

Javascript is single threaded by default and Java is multi threaded , but yet concurrency is achieved using an event based approach in JS.

Javascript Classes and Objects

Unlike in Java , there are a few methods we can use in JS to create classes.

One such method is using functions. Below is such an example ;

function Dog(name) {

this.name = name //Attribute

this.getName = function() { //Method

return this.name

}

}

const dog = new Dog(“Scooby”) //Object is created.

console.log(dog.getName()) //Outputs Scooby

The second way is using the class keyword , which is similar to Java.

class Dog {

constructor (name) {

this.name = name //Object Initialized with the given parameter

}

getName() {

return this.name

}

}

The class keyword has been in use since ES6 , therefore it is not fully supported in every browser yet.

The other method is by using object literals. This uses key-value pairs.

var dog = {

name : “Scooby”

age : 5

getDetails : function() {

return “Name” + this.name + “ Age : ” + this.age

}

};

Hope you have enjoyed reading this article and that by now , you have understood the basic concepts which were discussed through out this article , which were the SOLID principles , guidelines on software development approach and implementation , coding practices and some JavaScript basics on objects. We will be discussing some more JavaScript basics in the next article , until then , stay safe!

--

--