Skip to content
โ† Writing

6 Principles of Software Engineering You May Know But Don't Use

The art of writing clean code is not just a task, but an essential skill that every programmer should passionately embrace.

Jun 16, 2023 ยท 13 min read

6 Principles of Software Engineering You May Know But Don't Use

Introduction

The art of writing clean code is not just a task, but an essential skill that every software engineer should passionately embrace. Have you ever realized that becoming a programmer is not as difficult as you imagine? However, becoming a programmer who can create powerful applications with highly efficient code may be challenging.

Writing Code is Easy. Being a Great Developer is Hard.
I will not write any more bad code

How can we develop code that is easily maintainable, readable, and comprehensible to others? What steps can we take to maximize the effectiveness of our code?

1. Keep It Simple, Stupid (KISS)

The KISS principle encourages developers to keep things simple when writing code. Instead of overcomplicating things or show off by turning your code into lengthy paragraphs. If you can write the code in a single line, go ahead and write it as a single line.

Example without following the KISS principle:

example.ts
const calculateAverage = (numbers: number[]): number => {
  let sum = 0;
 
  for (let i = 0; i < numbers.length; i++) {
    sum += numbers[i];
  }
 
  const average = sum / numbers.length;
  return parseFloat(average.toFixed(2));
};
 
const numbers = [1, 2, 3, 4, 5];
const average = calculateAverage(numbers);
 
console.log(average);

The KISS principle is violated by unnecessarily introducing complexity. The addition of a loop and the usage of the toFixed method to limit the decimal places of the average make the code more convoluted than necessary. This added complexity can lead to confusion, potential bugs, and difficulties in maintaining and understanding the code.

Let's make a change

Example with following the KISS principle:

example.ts
const calculateAverage = (numbers: number[]): number => {
  const sum = numbers.reduce((acc, curr) => acc + curr, 0);
  return sum / numbers.length;
};
 
const numbers = [1, 2, 3, 4, 5];
const average = calculateAverage(numbers);
 
console.log(average);

The KISS principle is followed by using a simple and concise approach to calculate the average of a list of numbers. The reduce method is leveraged to compute the sum, and then the average is calculated by dividing the sum by the length of the array. The code is clear, readable, and achieves the desired result without unnecessary complexity.

2. Don't Repeat Yourself (DRY)

The essence of this principle is not to repeat the same thing. Imagine you have a piece of functionality in your software that is used in multiple places. Instead of copying and pasting the same code snippet in each location, the DRY principle suggests creating a reusable components, functions, classes, or modules that encapsulates that functionality.

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Example without following the DRY principle:

example.ts
const number1 = 1;
const number2 = 2;
const sum1 = number1 + number2;
console.log(sum1);
 
// ...
 
const number3 = 3;
const number4 = 4;
const sum2 = number3 + number4;
 
console.log(sum2);

The DRY principle is violated by duplicating the addition logic in multiple places. Although it might seem harmless in this simple case, duplicating code can lead to several issues as the codebase grows:

  1. Maintenance difficulties: If the addition logic needs to be modified or fixed, every occurrence of the duplicated code must be updated individually.
  2. Code readability and understandability: Duplicated code can make the codebase harder to read and understand. Developers encountering the same logic in different places may struggle to determine its purpose and behavior, leading to confusion and potential errors.
  3. Scalability and extensibility challenges: Duplicating code violates the principle of modularity and reusability. As the codebase expands and new requirements arise, the lack of a centralized and reusable solution can hinder the scalability and extensibility of the software.

What if we change it to be like this?

Example with following the DRY principle:

example.ts
const calculateSum = (a: number, b: number): number => {
  return a + b;
};
 
const sum1 = (1, 2);
const sum2 = (3, 4);
 
console.log(sum1);
console.log(sum2);

The DRY principle is followed by creating a reusable function calculateSum that takes two numbers as input and returns their sum. Instead of duplicating the code to perform addition in multiple places, the function encapsulates the logic. This approach eliminates redundancy and promotes code reusability. If the addition logic needs to be modified or updated, it can be done in a single place.

By applying the DRY principle, you enhance the overall quality and maintainability of your codebase. It saves time, reduces the risk of introducing bugs, and promotes a more efficient development process. Embracing the DRY principle allows you to write clean, concise, and reusable code, making your software more robust and your development workflow more efficient.

3. You Aren't Gonna Need It (YAGNI)

This is a guiding principle in software development that emphasizes avoiding unnecessary features or functionalities. It suggests that developers should only implement what is currently required, rather than speculating and building features that may or may not be needed in the future.

Example: Imagine you're developing a basic to-do list application. You start by implementing the core functionality, allowing users to add and delete tasks. However, as you work on it, you get tempted to add more advanced features like task prioritization, due dates, reminders, and collaboration capabilities.

By following the YAGNI principle, you resist the temptation to implement these additional features upfront. Instead, you focus on delivering a minimal viable product (MVP) that fulfills the immediate needs of managing tasks. You recognize that including unnecessary features would increase the development time, complexity, and potential for bugs without providing immediate value to the users.

4. SOLID

The SOLID principles are a set of five fundamental principles in software development that provide guidelines for designing and developing maintainable and flexible code. Each principle focuses on a specific aspect of software design and encourages developers to write code that is modular, extensible, and easy to understand.

SOLID Principle

S - Single Responsibility Principle (SRP)

The SRP states that a class or module should have a single responsibility or reason to change. It promotes the idea that a class should only have one primary purpose, making it easier to understand, maintain, and test. By separating concerns and avoiding bloated classes, we enhance code readability and achieve better maintainability.

Example without following the SRP principle:

Example.kt
class TaskManager {
  fun manipulateTask(task: Task, action: String) {
    when (action) {
      "add" -> // Code to add task to the task manager
      "update" -> // Code to update task to the task manager
      "delete" -> // Code to delete task to the task manager
      else -> // Code to handle else condition
    }
  }
}
 
/**
 * The `TaskManager` class has multiple responsibilities, violating the SRP.
 * It is responsible for managing tasks, including adding, deleting, and updating them.
 * This violates the principle as the class has more than one reason to change.
 */

Example with following the SRP principle:

Example.kt
class TaskManager {
  fun addTask(task: Task) {
    // Code for adding task
  }
 
  fun updateTask(task: Task) {
    // Code for update task
  }
 
  fun deleteTask(task: Task) {
    // Code for delete task
  }
}
 
/**
 * The `TaskManager` class follows the SRP by having separate methods for adding, updating, and deleting tasks.
 * Each method has a single responsibility.
 */

O - Open/Closed Principle (OCP)

The OCP emphasizes that software entities (classes, modules, functions) should be open for extension but closed for modification. This means that we should design our code in a way that allows new functionality to be added without modifying existing code. By relying on abstractions, interfaces, and polymorphism, we can introduce new behaviors without impacting the existing codebase.

Example without following the OCP principle:

Example.kt
class PaymentProcessor {
  fun processPayment(paymentMethod: String) {
    when (paymentMethod) {
      "CreditCard" -> // Code for processing payment with credit card
      "Paypal" -> // Code for processing payment with Paypal
      else -> // Do something on else condition
    }
  }
}
 
/**
 * The `PaymentProcessor` class violates the OCP by being open for modification.
 * If a new payment method is introduced, the class would need to be modified to handle the new logic, breaking the principle.
 */

Example with following the OCP principle:

Example.kt
interface PaymentProcessor {
  fun processPayment()
}
 
class CreditCardProcessor: PaymentProcessor {
  override fun processPayment() {
    // Code for processing payment with credit card
  }
}
 
class PaypalProcessor: PaymentProcessor {
  override fun processPayment() {
    // Code for processing payment with Paypal
  }
}
 
/**
 * The `PaymentProcessor` interface and its implementations (CreditCardProcessor and PaypalProcessor) adhere to the OCP.
 * If we want to add a new payment processor, we can simply create a new class implementing the `PaymentProcessor`
 * interface without modifying the existing code.
 */

L - Liskov Substitution Principle (LSP)

The LSP states that subtypes must be substitutable for their base types without affecting the correctness of the program. In simpler terms, this principle ensures that derived classes should be able to replace their base classes seamlessly, without breaking the expected behavior. Adhering to the LSP allows for better code reusability and interchangeability of objects.

Example without following the LSP principle:

Example.kt
class Vehicle {
  fun startEngine() {
    // Code to start the engine
  }
}
 
class Car: Vehicle {
  override fun startEngine() {
    // Code specific to starting a car's engine
  }
}
 
class Motorcycle: Vehicle {
  override fun startEngine() {
    // Code specific to starting a motorcycle's engine
  }
}
 
/**
 * The `Car` and `Motorcycle` classes violate the LSP by adding specific behavior to their respective startEngine methods.
 * This could lead to unexpected behavior when substituting objects of the base class with objects of the derived classes.
 */

Example with following the LSP principle:

Example.kt
abstract class Vehicle {
  abstract fun startEngine() {
    // Code to start the engine
  }
}
 
class Car: Vehicle {
  override fun startEngine() {
    // Code specific to starting a car's engine
  }
}
 
class Motorcycle: Vehicle {
  override fun startEngine() {
    // Code specific to starting a motorcycle's engine
  }
}
 
/**
 * The `Car` and `Motorcycle` classes are substitutable for their base class `Vehicle` without
 * changing the behavior of the program.
 * They both override the `startEngine` method based on their specific implementation.
 */

I - Interface Segregation Principle (ISP)

The ISP suggests that clients should not be forced to depend on interfaces they do not use. It advises creating specific, focused interfaces instead of having a single large interface. By segregating interfaces based on specific client needs, we prevent unnecessary dependencies and achieve better modularity and flexibility in our code.

Example without following the ISP principle:

Example.kt
interface PrintAndScan {
  fun print()
  fun scan()
}
 
class AllInOnePrinter: PrintAndScan {
  override fun print() {
    // Logic for printing
  }
 
  override fun scan() {
    // Login for scan
  }
}
 
/**
 * The `PrintAndScan` interface violates the ISP as clients might be forced to
 * implement methods they don't need, introducing unnecessary dependencies.
 */

Example with following the ISP principle:

Example.kt
interface Printer {
  fun print()
}
 
interface Scanner {
  fun scan()
}
 
class AllInOnePrinter: Printer, Scanner {
  override fun print() {
    // Logic for printing
  }
 
  override fun scan() {
    // Logic for scanning
  }
}
 
/**
 * The code follows the ISP by segregating the interfaces `Printer` and `Scanner` based on specific client needs.
 * The `AllInOnePrinter` class implements both interfaces, providing the necessary functionality.
 */

D - Dependency Inversion Principle (DIP)

The DIP states that high-level modules should not depend on low-level modules both should depend on abstractions. It encourages the use of abstractions and dependency injection to decouple modules and promote loose coupling between different components. By depending on abstractions, we can easily substitute implementations and achieve more flexible and testable code.

Example without following the DIP principle:

Example.kt
class EmailService {
  fun sendEmail(message: String) {
    // Code to send email
  }
}
 
class NotificationService {
  private val emailService = EmailService()
 
  fun sendNotification(message: String) {
    emailService.sendEmail(message)
  }
}
 
/**
 * The `NotificationService` directly depends on the `EmailService` class, violating the DIP.
 * This tight coupling makes it harder to switch to different notification mechanisms without modifying the service.
 */

Example with following the DIP principle:

Example.kt
interface Notifier {
  fun notify(message: String)
}
 
class EmailNotifier: Notifier {
  override fun notify(message: String) {
    // Code to send an email notification
  }
}
 
class SMSNotifier: Notifier {
  override fun notify(message: String) {
    // Code to send an SMS notification
  }
}
 
class NotificationService(private val notifier: Notifier) {
  fun sendNotification(message: String) {
    notifier.notify(message)
  }
}
 
/**
 * The `NotificationService` depends on the `Notifier` interface,
 * allowing different implementations (`EmailNotifier`, `SMSNotifier`) to be injected.
 * This promotes loose coupling between the service and the concrete implementations.
 */

By understanding and applying the SOLID principles, developers can create code that is modular, maintainable, and adaptable to change. Following these principles leads to code that is easier to read, test, and extend, resulting in more robust and flexible software systems.

5. Separation of Concerns (SOC)

The Separation of Concerns (SoC) principle is a fundamental concept in software engineering that promotes dividing a software system into distinct and independent parts, where each part addresses a specific concern or responsibility. The goal is to keep different concerns separate to achieve modularity, maintainability, and reusability in the codebase.

Example: Imagine you're building a house. The house consists of various components such as the foundation, walls, roof, plumbing, electrical wiring, and interior design. Each component has its own specific purpose and responsibility, but they all come together to create a functional and comfortable living space.

Applying the SoC principle in software development is similar. Instead of having a monolithic and tightly-coupled codebase, we break down the system into separate modules, classes, or functions, with each one addressing a specific concern.

6. Continuous Learning and Adaptability

The field of software engineering is a rapidly evolving landscape, where new technologies and practices emerge with regularity. A good software engineer understands the significance of continuous learning and embraces adaptability to remain relevant in this ever-changing industry. By proactively staying abreast of the latest trends and consistently enhancing their skills, software engineers can confidently deliver cutting-edge and innovative solutions.

Final Thoughts

By understanding and incorporating these principles and concepts into your software development journey, you can elevate the quality of your code, enhance collaboration, and build robust and scalable software systems that stand the test of time. Remember, mastering these principles requires practice and experience, so keep exploring, learning, and applying them in your projects. Happy coding ๐ŸŒป