Basic Programming Principles

Tram Ho

Your code should be clear and easy to maintain. It’s easy to code, but it’s hard to write good code.

Bad code comes in many forms. Messy code, huge if-else chains, programs that break with just one tweak, variables that don’t make sense—the program may work once, but if put to the test, never can now stand.

How do you write efficient code? By writing with discipline and purpose. Below I will share important programming principles

1. Why are Programming Principles important?

Programming principles are a set of rules and guidelines that are applied in the process of writing code, to ensure that the code will meet functional requirements, be easy to maintain and reuse.

By learning some programming principles and using them in your code, you will become a better developer. Following these methods will improve the overall quality of the code and make it easier for you or others to make changes or add functionality in the future.

Programming principles help you avoid problems like messy or overly complex code, broken programs after one tweak, and meaningless variables. Sticking to them will also allow you to collaborate more successfully by making sure fellow programmers can understand your code.

2. Common Programming Principles

2.1 KISS – “Keep It Simple, Stupid”

Which means you should write the code as simply as possible.

The KISS principle states that simplicity should be the goal of system design, and that most systems work best when it is kept simple, rather than being suppressed. complicate matters more. Unnecessarily complicating matters should always be eliminated.

-> use explicit variable names

-> use encryption libraries and use existing tools

Example: In an HTML template file, we can use ngFor to iterate over UI elements:

In the component file, we can declare variables and logic functions:

With this approach, we use basic Angular to display the list of items and allow the user to add a new item to the list. The code is very simple and easy to understand, ensuring compliance with the KISS principle.

2.2 Keep things DRY – Don’t Repeat Yourself (DRY)

DRY means do not repeat code, avoid repetition. It’s a common coding error. When writing code, avoid duplication of data or logic. If you’ve ever copied and pasted code in your program, it’s not DRY code. Instead of copying lines, try to find an algorithm that uses loops.

DRY code is easy to maintain. It is easier to debug a loop that handles 50 iterations than it is 50 blocks of code that handles one iteration. A good implementation of DRY will help you maintain the code better, or solve the problem of changing the code logic of a piece of processing more easily later.

2.3 YAGNI – You Aren’t Gonna Need It

YAGNI means not doing something until it is necessary.

One of the most important principles of learning computer programming is that you shouldn’t try to solve a problem that doesn’t exist.

In the introduction to YAGNI, Martin Fowler mentioned 4 problems when violating YAGNI:

  • Cost of building: When you make a function that ultimately doesn’t need it. It costs you a lot of effort in designing, coding, testing…
  • Cost of repair: When the functionality you are aiming for is needed, but you implement it in an unreasonable way. It will cost you effort to re-plan, re-code, and retest the functionality you already have, because it’s not really what you need.
  • Cost of delay: In any case, you will encounter this problem. You are wasting time on a function that you do not need at the moment, it means that the necessary functions at the present time cannot be completed and released soon.
  • Cost of carry: In any case, you will encounter this problem. You are adding a lot of new code to your project, making the system more complicated and will take more effort to maintain, modify, and debug.

For example:

In this example, we just define an AppComponent component and use DataService to get data from an API. We don’t need to create other components or complex data processing functions, because we don’t know exactly what we will need in the future.

According to the YAGNI principle, we should write code based on specific current requirements, instead of writing code based on assumptions about possible future requirements. Writing simple code and implementing only the necessary features is important to reduce complexity and ensure application stability.

In fact, it is also difficult to define the boundaries of YAGNI. There are many features, or logic processing, you will have to consider whether it is YAGNI or not. Programmers sometimes violate this principle when trying to adhere to DRY encryption methods, so keep both in mind.

2.4 SOLID

This is a set of programming principles introduced by Robert C. Martin (aka Uncle Bob) for designing and writing efficient and maintainable code.

SOLID includes 5 principles: Single Responsibility (SRP), Open-Closed (OCP), Liskov Substitution (LSP), Interface Segregation (ISP), Dependency Inversion (DIP).

Single Responsibility Principle (SRP):

A class or object should have only one responsibility and should not extend beyond its scope. Single Responsibility (SRP): Each component (component, service, directive, pipe…) should have only one responsibility in the system.

For example:

If there is a component to display the product list and also use it to add, edit and remove products, this is not in line with this principle, because it does too much work.

Here is an example of applying this principle in an Angular service:

In this example, ProductListService is only responsible for communicating with the API to get information , add new, and delete users. No complex processing logic is performed in this service. This makes the service easier to maintain and reuse.

Open/Closed Principle (OCP):

Source code should be designed to be extensible, but closed for modification, meaning you don’t need to modify existing code every time you want to add new functionality.

In Open/Closed (OCP) principle, we need to design classes and modules so that they are extensible (open) to add new features, but closed (closed) to modify existing features. .

For example:

We have an online sales website, and on this website there is a list of products displayed to the user. In this case, we can create an Angular component to manage product listings and display them on the web page.

To apply the OCP principle in this example, we could design the component to allow extension for new product listing related features, but close it so as not to change existing features. Specifically, we can create an abstract class ProductListComponent to define common methods for the component that displays the product list, as follows:

We can then create subclasses to inherit from ProductListComponent and implement the loadProducts() and displayProducts() methods based on the specific requirements of the new feature to be added. For example, in case we want to add product filtering by price, we can create a subclass of PriceFilteredProductListComponent as follows:

So, when we want to add product filtering by price, we just need to create a new class that inherits from ProductListComponent , implement the necessary methods and use it to display the product list. In this case, adding the feature does not affect the existing features of the component.

Liskov Substitution Principle (LSP):

Child objects should be able to replace their parent objects without affecting program functionality.

Interface Segregation Principles (ISP):

An interface should contain only necessary methods for a particular object and not unnecessary methods.

Dependency Inversion Principle (DIP):

The source code should depend on interfaces, not concrete classes. This ensures flexibility and maintainability of the source code.

2.5 Separation of Concerns

Separation of concerns is a principle in programming, which means separating tasks into different parts to minimize dependencies between them. This principle allows for easier development and maintenance of code by dividing system functions into highly independent separate parts.

For example, when building a web application, we can use the MVC (Model-View-Controller) pattern to divide the application’s functionality into different parts. The Model prepares the data, the View displays the interface to the user, and the Controller handles the request from the user. By separating these functions into different parts, it is easier to modify and maintain the code and to reduce problems related to correctness and security of the application.

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

~~ Conclusion: ~~

These programming principles help ensure that your code is rigorously designed, easy to maintain, and easy to extend into the future. Applying these principles will make your code highly reusable and reduce errors associated with code development and maintenance.

Reference:

Share the news now

Source : Viblo