Software engineering is a set of principles and methods to analyse user requirements and develop effective, reliable and quality software. It is a set of best practices introduced by industry experts that programmers should follow during software development to write bug-free, readable and maintainable code.
Let’s go through some of the top design principles of software engineering.
According to Robert C. Martin’s Clean Code, the Law of Demeter says that a method f in class C should call methods only on:
The principle is simple: Talk to friends, not strangers!
According to this principle, divide responsibilities among classes and encapsulate logic within a class or method. There are few key recommendations to follow in order to achieve this:
The Law of Demeter promotes independence and reduces interdependence among classes. According to Robert Martin, “A module should not know about the innards of the objects it manipulates. In other words, objects should hide their data and expose only their operations. This means that an object should not reveal its internal structure through accessors, but should keep it hidden.”
Optimisation is necessary to build faster applications and reduce resource consumption. But everything has its time. Optimising during the early stages of development can do more harm than good. Writing optimised code requires more time and effort and we must continually verify its correctness. It is better to start with a simple approach, even if it is not the most efficient. Later, we can evaluate its performance and decide whether to design a faster or less resource-intensive algorithm.
Let's understand it from another perspective. While it’s true that optimisation reduces resource consumption, it’s important to consider drawbacks. Suppose we start by implementing the most efficient algorithm, but then our requirements change. In that case, all our efforts to create an efficient solution may be wasted. That’s why it’s often better to avoid premature optimisation and focus on other priorities first.
The KISS principle (Keep It Simple, Stupid) originated in the 1960s, when the U.S. Navy made a valuable observation about how systems function. They noticed that complex systems tend to perform poorly, while simple systems tend to work well. This is because complexity can reduce understanding of the system and increase bugs. By following this principle, we can design systems that are easier to understand.
The idea of the KISS principle: Software code should be easy to understand and flexible when it comes to modifying or adding new features. In other words, we should aim to avoid unnecessary complexity in our software development. This might seem like a no-brainer, but it's easy to get carried away with using fancy features and end up creating a lot of dependencies.
To avoid this, it's important to consider the usefulness of any new dependencies, frameworks or features before implementing them. Our methods should be small and focused on solving a single problem. If there are many conditions, try breaking them down into smaller blocks of code. This helps to keep code clean and reduces the likelihood of bugs. In simple words: simple code is easier to debug and maintain.
The DRY principle emphasises the importance of avoiding redundant code. This helps to promote code reuse and makes it more maintainable, extensible and less buggy. The DRY principle originated in the book "The Pragmatic Programmer" by Andy Hunt and Dave Thomas.
From another perspective, the DRY principle helps us avoid a common maintenance and modification challenge. When the same code appears in multiple places, making even a small change requires updating the code in all of those locations. If we miss one of these updates, it can lead to errors that require extra time and effort to fix. By following the DRY principle, we can avoid this potential pitfall and make our code more efficient and reliable. The recommended solution would be:
One of the challenges in software development is that we may think we'll need certain functionality in the future, but then requirements change and that functionality becomes unnecessary. To avoid this problem, we can follow the YAGNI (You Ain't Gonna Need It) principle.
This principle advises us to only implement things when we actually need them, rather than adding functionality to solve potential future problems. By following YAGNI, we can avoid unnecessary complexity and stay focused on the current needs of the project. YAGNI is a core principle of the Extreme Programming (XP) software development methodology.
SOLID is a group of object-oriented design principles, where each letter in the acronym “SOLID” represents one of the principles. When applied together, these principles help developers create code that is easy to maintain and extend over time.
It consists of design principles that first appeared in Robert C. Martin’s 2000 paper entitled "Design Principles and Design Patterns". Let’s go through each SOLID principles one by one:
The Single Responsibility Principle (SRP) states that each class or method should have a clear and well-defined responsibility and that responsibility should be fully encapsulated by the class or method. This means that a class or method should have only one job and only one reason to change, so that if any part of the application needs to be modified, it will only affect one class or method. By following the SRP, we can create more modular and maintainable software systems.
Designing methods or classes with a single responsibility makes our code easier to understand, maintain and modify. When we need to make changes to a particular functionality, we know exactly where to go in the code. By keeping functions and classes short and focused, we can easily reuse them in other parts of the codebase.
Suppose you have an order-processing class that calculates totals, saves orders and sends confirmation emails. If the email service changes, the class must change. If the database changes, it must change again. It has several reasons to change. Now, using SRP, give each responsibility its own class.
class OrderProcessor {
private final OrderRepository repository;
private final EmailService emailService;
OrderProcessor(OrderRepository repository, EmailService emailService) {
this.repository = repository;
this.emailService = emailService;
}
void process(Order order) {
double total = order.calculateTotal();
repository.save(order, total);
emailService.sendConfirmation(order);
}
}
class OrderRepository {
void save(Order order, double total) {
System.out.println("Saving order total: " + total);
}
}
class EmailService {
void sendConfirmation(Order order) {
System.out.println("Sending confirmation email");
}
}Here, OrderProcessor coordinates the work, while separate classes calculate the total, save the order and send the confirmation. Now, a change to how orders are stored belongs in OrderRepository, while a change to email delivery belongs in EmailService.
We should be able to change the behavior of a class without modifying it.
From another perspective, the Open-Closed Principle (OCP) says that software should be open to extension but closed to modification. In practice, this means designing the code so we can add new features without changing existing, working functionality. Doing so reduces the risk of breaking existing behaviour and makes the software easier to extend over time.
For example, suppose there is a checkout system that applies discounts. If it uses a long if/else chain, adding a new discount type means editing the checkout class each time.
class Checkout {
double finalPrice(String discountType, double price) {
if (discountType.equals("holiday")) {
return price * 0.8;
} else if (discountType.equals("loyalty")) {
return price * 0.9;
}
return price;
}
}Now to apply the OCP principle, we define a common discount interface and let each discount type provide its own behavior.
interface Discount {
double apply(double price);
}
class HolidayDiscount implements Discount {
public double apply(double price) {
return price * 0.8;
}
}
class LoyaltyDiscount implements Discount {
public double apply(double price) {
return price * 0.9;
}
}
class Checkout {
double finalPrice(double price, Discount discount) {
return discount.apply(price);
}
}Now to add a new discount, we can create another class that implements Discount.
class StudentDiscount implements Discount {
public double apply(double price) {
return price * 0.85;
}
}Now, Checkout does not need to change. It is open for extension because we can add new discount types, and closed for modification because adding one does not require editing its existing code.
The Liskov Substitution Principle (LSP) was introduced by Barbara Liskov in a 1988 conference keynote address. It states that derived classes should be able to be replaced by their base class without affecting the correctness of the program. In other words, objects of a parent class should be interchangeable with objects of a child class.
To follow the LSP, we should make sure that an inherited class complements rather than replaces the behavior of the base class. This way, we can substitute the child class for the parent class and expect the same basic behavior.
abstract class Shape {
abstract double getArea();
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
double getArea() {
return width * height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}
class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
@Override
public void setWidth(double width) {
super.setWidth(width);
super.setHeight(width);
}
@Override
public void setHeight(double height) {
super.setHeight(height);
super.setWidth(height);
}
}
public class Main {
public static void main(String[] args) {
Shape rect = new Rectangle(10, 20);
System.out.println("Area of rectangle: " + rect.getArea());
Shape square1 = new Square(10);
System.out.println("Area of square: " + square1.getArea());
Rectangle square2 = new Square(15);
System.out.println("Area of square: " + square2.getArea());
}
}The above example follows the Liskov Substitution Principle. The idea is simple: the Square class extends the Rectangle class. So when we create an instance of a Square class and assign it to a Rectangle variable, the program behaves as expected. In other words, we can use the Square object interchangeably with a Rectangle object. Similarly, we can use a Rectangle object interchangeably with a Shape object.
The Interface Segregation Principle (ISP) was first defined by Robert C. Martin while consulting for Xerox. Xerox had developed a printer software that included tasks like stapling and faxing. But as the software grew, it became difficult to make changes and even small modifications would take an hour to deploy.
The issue was that almost all tasks used a single Job class, which became very large and included specific methods for various clients. This meant that a staple job would have knowledge of all the methods of the print job, even though it didn't need them. To solve this problem, the ISP suggests that clients should not be forced to depend on interfaces they do not use.
The suggested solution by Martin is called the Interface Segregation Principle. Instead of having one large Job class, a Staple Job interface or a Print Job interface was created that would be used by the Staple or Print classes. So one interface was designed for each job type, which was all implemented by the Job class.
So the Interface Segregation Principle states that a client should never be forced to depend on methods it does not use. We achieve this by making our interfaces small and focused. It would be best to split large interfaces into more specific ones focused on a particular set of functionalities so that the clients can choose to depend only on the functionalities they need.
Here is a Java example based on a printer system. A single large interface forces every device to support printing, stapling, and faxing—even if it can only print.
// Too broad: every device must implement all three methods.
interface Job {
void print(Document document);
void staple(Document document);
void fax(Document document);
}
class BasicPrinter implements Job {
public void print(Document document) {
System.out.println("Printing document");
}
public void staple(Document document) {
throw new UnsupportedOperationException("Stapling is not supported");
}
public void fax(Document document) {
throw new UnsupportedOperationException("Faxing is not supported");
}
}Here, the BasicPrinter has to provide methods it cannot use. Let's apply the ISP principle by splitting the large interface into smaller, focused interfaces.
interface Printer {
void print(Document document);
}
interface Stapler {
void staple(Document document);
}
interface FaxMachine {
void fax(Document document);
}
class BasicPrinter implements Printer {
public void print(Document document) {
System.out.println("Printing document");
}
}
class OfficeMachine implements Printer, Stapler, FaxMachine {
public void print(Document document) {
System.out.println("Printing document");
}
public void staple(Document document) {
System.out.println("Stapling document");
}
public void fax(Document document) {
System.out.println("Faxing document");
}
}Now, BasicPrinter depends only on printing, while OfficeMachine implements all the capabilities it supports. The interfaces are small and focused, so devices are not forced to depend on methods they do not use.
The Dependency Inversion Principle says that high-level modules should not depend directly on low-level modules. Both should depend on abstractions, i.e. interfaces. This keeps the interaction between them flexible: the high-level module relies on what the low-level module can do, rather than on a specific implementation. In practice, we need to use interfaces instead of concrete classes.
interface EmailSender {
void sendEmail(String to, String subject, String message);
}
class GmailSender implements EmailSender {
@Override
public void sendEmail(String to, String subject, String message) {
// Code to send email using Gmail
}
}
class YahooSender implements EmailSender {
@Override
public void sendEmail(String to, String subject, String message) {
// Code to send email using Yahoo
}
}
class UserService {
private EmailSender emailSender;
public UserService(EmailSender emailSender) {
this.emailSender = emailSender;
}
public void sendWelcomeEmail(String to) {
String subject = "Welcome to enjoyalgorithms";
String message = "We are glad to have you as a part of our community.";
emailSender.sendEmail(to, subject, message);
}
}
public class Main {
public static void main(String[] args) {
EmailSender emailSender = new GmailSender();
UserService service = new UserService(emailSender);
service.sendWelcomeEmail("contact@enjoyalgorithms.com");
}
}In the above example, the UserService class depends on an abstraction (EmailSender interface) rather than on a concrete implementation (GmailSender or YahooSender). In the Main class, we have used UserService class with different implementations of the EmailSender interface, which provide greater flexibility and adaptability to changing requirements.
So, what is the reason behind this principle? The answer is simple: abstractions don’t change a lot. So, we can easily change the behavior of closed or open-source code and boost its future evolution.
Enjoy learning, Enjoy oops!