跳到主要内容

2 篇博文 含有标签「theory」

查看所有标签

The SOLID Principles in Software Design and Development

· 阅读需 7 分钟

Introduction​

The SOLID principles are a set of five design principles intended to make software designs more understandable, flexible, and maintainable. These principles were introduced by Robert C. Martin (also known as Uncle Bob) and are widely accepted in the software development community. The acronym SOLID stands for:

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

SOLID Principles This article will explain each principle, provide examples of how they can be broken, and show the correct implementation to fix them.


Single Responsibility Principle (SRP)​

Definition​

The Single Responsibility Principle states that a class should have only one reason to change, meaning it should have only one job or responsibility.

Broken Example​

class Employee {
private String name;
private double salary;

public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

public void save() {
// Code to save employee data to the database
System.out.println("Employee saved to database: " + name);
}

public void calculateSalary() {
// Code to calculate salary
System.out.println("Salary calculated: " + salary);
}
}

Correct Example​

class Employee {
private String name;
private double salary;

public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}

public void calculateSalary() {
// Code to calculate salary
System.out.println("Salary calculated: " + salary);
}
}

class EmployeeRepository {
public void save(Employee employee) {
// Code to save employee data to the database
System.out.println("Employee saved to database: " + employee.getName());
}
}

Open/Closed Principle (OCP)​

Definition​

The Open/Closed Principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

Broken Example​

class Shape {
String type;

public Shape(String type) {
this.type = type;
}
}

class AreaCalculator {
public double calculateArea(Shape shape) {
if (shape.type.equals("circle")) {
// Calculate area for circle
return Math.PI * Math.pow(5, 2); // Assuming radius is 5
} else if (shape.type.equals("rectangle")) {
// Calculate area for rectangle
return 10 * 5; // Assuming width is 10 and height is 5
}
return 0;
}
}

Correct Example​

interface Shape {
double calculateArea();
}

class Circle implements Shape {
private double radius;

public Circle(double radius) {
this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
}

class Rectangle implements Shape {
private double width;
private double height;

public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}

@Override
public double calculateArea() {
return width * height;
}
}

class AreaCalculator {
public double calculateArea(Shape shape) {
return shape.calculateArea();
}
}

Liskov Substitution Principle (LSP)​

Definition​

The Liskov Substitution Principle states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.

Broken Example​

class Bird {
public void fly() {
System.out.println("Flying...");
}
}

class Ostrich extends Bird {
@Override
public void fly() {
throw new UnsupportedOperationException("Ostriches cannot fly");
}
}

Correct Example​

class Bird {
public void eat() {
System.out.println("Eating...");
}
}

class FlyingBird extends Bird {
public void fly() {
System.out.println("Flying...");
}
}

class Ostrich extends Bird {
// Ostriches do not fly, so no fly method here
}

Interface Segregation Principle (ISP)​

Definition​

The Interface Segregation Principle states that clients should not be forced to depend on interfaces they do not use.

Broken Example​

interface Worker {
void work();
void eat();
}

class Robot implements Worker {
@Override
public void work() {
System.out.println("Robot working...");
}

@Override
public void eat() {
throw new UnsupportedOperationException("Robots do not eat");
}
}

Correct Example​

interface Workable {
void work();
}

interface Eatable {
void eat();
}

class Robot implements Workable {
@Override
public void work() {
System.out.println("Robot working...");
}
}

class Human implements Workable, Eatable {
@Override
public void work() {
System.out.println("Human working...");
}

@Override
public void eat() {
System.out.println("Human eating...");
}
}

Dependency Inversion Principle (DIP)​

Definition​

The Dependency Inversion Principle states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Additionally, abstractions should not depend on details. Details should depend on abstractions.

Broken Example​

class LightBulb {
public void turnOn() {
System.out.println("LightBulb turned on");
}

public void turnOff() {
System.out.println("LightBulb turned off");
}
}

class Switch {
private LightBulb bulb;

public Switch() {
this.bulb = new LightBulb();
}

public void operate() {
if (isOn) {
bulb.turnOff();
isOn = false;
} else {
bulb.turnOn();
isOn = true;
}
}

private boolean isOn = false;
}

Explanation​

In the broken example, the Switch class directly depends on the LightBulb class. This creates a tight coupling between the Switch (high-level module) and the LightBulb (low-level module). Here’s why this violates the Dependency Inversion Principle:

  1. Direct Dependency: The Switch class directly creates an instance of LightBulb within its constructor. This means that the Switch class is tightly coupled to the LightBulb class. If you want to change the type of device that the Switch controls (e.g., a fan instead of a light bulb), you would need to modify the Switch class itself.

  2. Lack of Abstraction: There is no abstraction layer between the Switch and the LightBulb. The Switch class is directly aware of the implementation details of the LightBulb class. This makes the Switch class less flexible and harder to extend or modify.

  3. Rigidity: The Switch class is rigid because it can only operate on a LightBulb. If you want to add support for other devices (e.g., a Fan), you would need to create a new Switch class or modify the existing one, which is not ideal.

Why High-Level Module Depends on Low-Level Module​

  • Direct Instantiation: The Switch class directly instantiates the LightBulb class within its constructor. This means that the Switch class is directly dependent on the LightBulb class.
  • No Abstraction Layer: There is no interface or abstract class that both the Switch and LightBulb classes implement. This lack of abstraction means that the Switch class is tightly coupled to the specific implementation of the LightBulb class.

Correct Example​

To adhere to the Dependency Inversion Principle, we introduce an abstraction (an interface) that both the Switch and the LightBulb classes depend on.

interface Switchable {
void turnOn();
void turnOff();
}

class LightBulb implements Switchable {
@Override
public void turnOn() {
System.out.println("LightBulb turned on");
}

@Override
public void turnOff() {
System.out.println("LightBulb turned off");
}
}

class Switch {
private Switchable device;

public Switch(Switchable device) {
this.device = device;
}

public void operate() {
if (isOn) {
device.turnOff();
isOn = false;
} else {
device.turnOn();
isOn = true;
}
}

private boolean isOn = false;
}

Explanation of Correct Example​

  1. Abstraction Layer: The Switchable interface acts as an abstraction layer. Both the Switch and the LightBulb classes depend on this abstraction.
  2. Dependency Injection: The Switch class now takes a Switchable object as a parameter in its constructor. This allows the Switch class to operate on any device that implements the Switchable interface, not just a LightBulb.
  3. Flexibility: This design makes the Switch class flexible and easier to extend. You can now create other classes that implement the Switchable interface (e.g., Fan) and pass them to the Switch class without modifying the Switch class itself.

By adhering to the Dependency Inversion Principle, we ensure that high-level modules (like Switch) do not depend on low-level modules (like LightBulb). Instead, both depend on abstractions (like the Switchable interface), making the system more modular, flexible, and easier to maintain.


Conclusion​

The SOLID principles are fundamental to writing clean, maintainable, and scalable software. By adhering to these principles, developers can create code that is easier to understand, extend, and refactor. Each principle addresses a specific aspect of software design, and understanding how to apply them correctly can significantly improve the quality of your code.

References:​

https://blog.bytebytego.com/p/mastering-design-principles-solid

Understanding Object Types in Application Development

· 阅读需 8 分钟

Introduction​

In application development, different types of objects serve various purposes. Understanding these objects and their roles is crucial for designing scalable and maintainable systems. This article will explain common object types such as Value Object (VO), Plain Old Java Object (POJO), Data Transfer Object (DTO), Entity, Model, Persistent Object (PO), Business Object (BO), and Data Access Object (DAO). We will also provide a textual diagram to illustrate the transition between these objects and sample code to demonstrate their usage.


Object Types​

Value Object (VO)​

A Value Object is an object that represents a simple entity whose equality is not based on identity but on the value of its properties. VOs are immutable and typically used to represent concepts that are naturally comparable by value.

Plain Old Java Object (POJO)​

A POJO is a simple Java object that does not require any specific framework or library. It is a plain Java object that follows basic Java conventions and does not extend or implement any special classes or interfaces.

Data Transfer Object (DTO)​

A DTO is an object used to transfer data between different layers of an application, such as between the service layer and the presentation layer. DTOs are typically simple objects that contain data but do not contain any business logic.

Entity​

An Entity is an object that represents a persistent domain object, typically mapped to a database table. Entities have a unique identity and are often used to represent business concepts.

Model​

A Model represents the data and business logic of an application. It encapsulates the state and behavior of the application's domain. Models are often used in the service layer to perform business operations.

Persistent Object (PO)​

A Persistent Object is an object that is mapped to a database table. It is similar to an Entity but is often used in older or specific frameworks where the term Entity is not used.

Business Object (BO)​

A Business Object encapsulates the business logic of an application. It is responsible for performing business operations and often interacts with DAOs to persist data.

Data Access Object (DAO)​

A DAO is an object that provides an abstract interface to some type of database or other persistence mechanism. It allows the application to access and manipulate data without exposing the underlying data source.


Transition Diagram​

graph TD
A[Entity] -->|Map to Database| B[Repository]
B -->|Fetch Data| C[Service Layer]
C -->|Transform| D[DTO]
D -->|Transfer Data| E[Controller]
E -->|Present Data| F[View]
C -->|Business Logic| G[Model]
G -->|Represent Value| H[Value Object]
C -->|Business Logic| I[Business Object]
I -->|Access Data| J[DAO]
J -->|Map to Database| K[Persistent Object]

Explanation​

  1. Entity: Represents a persistent domain object.
  2. Repository: Manages the persistence of entities.
  3. Service Layer: Contains business logic and transforms entities into DTOs.
  4. DTO: Transfers data between layers.
  5. Controller: Handles HTTP requests and responses.
  6. View: Presents data to the user.
  7. Model: Contains business logic and encapsulates state.
  8. Value Object: Represents a simple, immutable value.
  9. Business Object: Encapsulates business logic.
  10. DAO: Provides an abstract interface to the database.
  11. Persistent Object: Mapped to a database table.

Scenarios​

Value Object (VO)​

  • Scenario: Representing a monetary value or a date range.
  • Usage: Used in business logic to ensure immutability and value-based equality.

Plain Old Java Object (POJO)​

  • Scenario: Simple data structures without any framework dependencies.
  • Usage: Used in any layer of the application where a simple data structure is needed.

Data Transfer Object (DTO)​

  • Scenario: Transferring data between different layers of the application.
  • Usage: Used in the service layer to transfer data to the presentation layer.

Entity​

  • Scenario: Representing a persistent domain object.
  • Usage: Used in the persistence layer to map to database tables.

Model​

  • Scenario: Representing the business logic and state of the application.
  • Usage: Used in the service layer to perform business operations.

Persistent Object (PO)​

  • Scenario: Mapping to a database table in older or specific frameworks.
  • Usage: Used in the persistence layer to represent database records.

Business Object (BO)​

  • Scenario: Encapsulating business logic.
  • Usage: Used in the service layer to perform business operations.

Data Access Object (DAO)​

  • Scenario: Providing an abstract interface to the database.
  • Usage: Used in the persistence layer to access and manipulate data.

Sample Code​

Value Object (VO)​

public final class Money {
private final double amount;
private final String currency;

public Money(double amount, String currency) {
this.amount = amount;
this.currency = currency;
}

public double getAmount() {
return amount;
}

public String getCurrency() {
return currency;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Money money = (Money) o;
return Double.compare(money.amount, amount) == 0 &&
currency.equals(money.currency);
}

@Override
public int hashCode() {
return Objects.hash(amount, currency);
}
}

Plain Old Java Object (POJO)​

public class User {
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Data Transfer Object (DTO)​

public class UserDTO {
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Entity​

@Entity
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Model​

public class UserModel {
private String name;
private int age;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public void validateAge() {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
}

Persistent Object (PO)​

public class UserPO {
private Long id;
private String name;
private int age;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}

Business Object (BO)​

public class UserBO {
private UserDAO userDAO;

public UserBO(UserDAO userDAO) {
this.userDAO = userDAO;
}

public UserDTO getUserById(Long id) {
UserPO userPO = userDAO.findById(id);
UserDTO userDTO = new UserDTO();
userDTO.setName(userPO.getName());
userDTO.setAge(userPO.getAge());
return userDTO;
}

public void createUser(UserDTO userDTO) {
UserPO userPO = new UserPO();
userPO.setName(userDTO.getName());
userPO.setAge(userDTO.getAge());
userDAO.save(userPO);
}
}

Data Access Object (DAO)​

public interface UserDAO {
UserPO findById(Long id);
void save(UserPO userPO);
}

public class UserDAOImpl implements UserDAO {
@Override
public UserPO findById(Long id) {
// Implementation to fetch user from database
return new UserPO();
}

@Override
public void save(UserPO userPO) {
// Implementation to save user to database
}
}

Transition Example​

public class UserService {
private UserBO userBO;

public UserService(UserBO userBO) {
this.userBO = userBO;
}

public UserDTO getUserById(Long id) {
return userBO.getUserById(id);
}

public void createUser(UserDTO userDTO) {
userBO.createUser(userDTO);
}
}

Conclusion​

Understanding the different types of objects in application development is crucial for designing robust and maintainable systems. Each object type serves a specific purpose and is used in different scenarios. By following best practices and adhering to design principles, developers can create applications that are easier to extend, test, and maintain.