Be flexible, but stick to your principles.

Being a nerdy developer, time after time I’ve had focused only on getting things done in the smartest way. I didn’t concentrate much on predefined guidelines and absolute quality. However, this quirky ideology of mine changed a couple of years back when I started to work in Magento 2.

The knowledge-thirsty eCommerce platform was challenging to learn, given the plethora of technical guidelines and resources available from Magento. Ideally, Magento is more focused on maintaining the high quality among the developers, and they also provide various means of guidance to the community. The learning curve was simple and following the guidelines made things more accessible than what I expected. It is highly recommended to follow the best practices of Magento to provide the best quality coding.

This is a beginner, know-how article about SOLID principles, which I came across during my quest to strictly follow the guidelines for good programming.

Besides, the very purpose of this article is to upskill budding programmers and developers about SOLID.

What are SOLID Principles?

In object-oriented computer programming, the term SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible, and maintainable.

SOLID Principles are a combination of five design principles namely:

  • Single Responsibility Principle (SRP)
  • Open/Closed Principle (OCP)
  • Liskov Substitution Principle (LSP)
  • Interface Segregation Principle (ISP)
  • Dependency Inversion Principle (DIP)

SOLID-principles-magento-2

Why should you practice SOLID Principles?

After understanding a thing or two about SOLID principles, I started applying them to my day-to-day work coding, and the results were utterly gratifying. Nowadays, I am using these principles a lot appropriately and keen as well in not violating any principle as such.

Following these guidelines:

  • Allows you to stick to the coding standards.
  • Makes the code scalable and repairable – regardless of the size of the change requests.
  • Makes the code universally understandable.

Single Responsibility Principle (SRP)

a class should have only a single responsibility

It’s pretty straightforward. A class should have only one responsibility, and it should not do too many things. Following this principle, makes the class more maintainable. Providing multiple responsibilities to a class makes it more complicated to change any responsibility, which might affect others.

Examples in Magento 2

\Magento\Framework\Event\Manager – Responsible for dispatching the events.

\Magento\Framework\Data\Form\FormKey\Validator – Responsible for validating the form key.

So, the next time you write some class, make it responsible for only one action and make your code robust and maintainable.

Open/Closed Principle (OCP)

software entities … should be open for extension, but closed for modification

Assume your client approaches you to write the code for calculating the sum of numbers. You wrote a class (Add) with a method (Calculate) to calculate the sum and gave it to the client. He was delighted with your work. Sometime later, the same client approaches you to add the multiplication logic. Now you will edit the same class (Changing Add to Operation) and two methods (Add and Multiply) with the respective logic. But, this is not the right approach because your client may come next time for adding subtraction or division and you will end up modifying the source code every time.

As the principle states, for any modifications, a class should be allowed to extend its behavior but not allowed to change the source code. So, better write an interface (Operation Interface) with a method calculate, which the classes (Add or Multiply) can implement. When the client approaches for other operation like Division, you can create a new class by implementing the interface.

Examples in Magento 2

To add any router, implement the \Magento\Framework\App\RouterInterface and add the same to the RouterList(in di.xml). Here, no modification has been made to the existing code even though the router is added.

Liskov Substitution Principle (LSP)

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program

As per the object-oriented programming, when Class B extends Class A, Class B can be a substitute for Class A. LSP extends the same fundamental principle, with a significant change – Class B SHOULD be a substitute of Class A.

In the case of extending any Magento native classes, you should follow the same structure. If you intend to remove any method or modify its parameters, then it will result in the violation of this principle. The violation may cause the application to break or will produce unexpected results.

Examples in Magento 2

Assume a preference written for overriding the \Magento\Quote\Model\Quote::addProduct($product, $request, $processMode) method. Creating the class that extends the above, but modifies the addProduct() method by removing the $processMode parameter. This is a complete violation of the principle. So classes which already calls the addProduct() with three parameters will throw an error and cause the application to break.

Interface Segregation Principle (ISP)

Many client-specific interfaces are better than one general-purpose interface

This is pretty straightforward, and it focuses on splitting the big fat interfaces into smaller ones. The violation of the principle may force the implementation class to depend on the methods that they don’t use.

Assume there is a standard interface for compiling and rendering. When creating a separate implementation class for the compiler and render, based on SRP, the classes should be intended to use the other methods (in simple terms, compilers are forced to use rendering methods).

Examples in Magento 2

\Magento\Framework\View\Element\BlockInterface – implemented in all the blocks for rendering HTML content.

\Magento\Framework\DataObject\IdentityInterface – may implement in blocks or models for caching purposes.

Assume Magento Core Team has combined both and can have only the BlockInterface. However, by doing so, all blocks are forced to have the cache methods that they might not use and will be a strict violation of the principle.

Dependency Inversion Principle (DIP)

one should “depend upon abstractions, [not] concretions”

DIP focuses on decoupling the modules and states that:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.

When Class A(high-level) calls Class B(low-level), Class A depends on Class B. But as per this principle, Class A should not depend on Class B; it should depend on abstractions(interfaces).

  • Abstractions should not depend on details. Details should depend on abstractions.

Interfaces should not depend upon the implementation class, and the implementation should depend upon the respective interface.

Since the code is decoupled, to change the entire implementation class, it’s not necessary to make changes in high-level class. But, in the interest of following the principle, the high-level module also needs to be altered with low-level class.

Examples in Magento 2

Refer any native classes where they mostly inject the interfaces into the constructor instead of the implementation class to create the respective objects. Even when using the factory, it is recommended to create the factory for the interface.

These are the five simple and most commonly used design principles in the process of Object Decomposition. Magento strongly recommends the community to apply the principles wherever needed. So, the next time, when you code a new feature or modify an existing one, keep all the principles in mind and apply to achieve better quality and maintainability on the code.

Leave a comment to add more inputs or examples on any design principle or to write about any other design pattern. Let’s make the community even better.

Be the first to Know

Subscribe to our blog to get the latest articles directly to your inbox.

READY TO DRIVE SALES?

Request a Quote Today

Request a Quote

Leave a Reply

Be the First to Comment!