Cohesion is how closely related the responsibilities inside a module, class, or function are — A module has high cohesion when everything inside it works toward one clear purpose.
type Utils struct{}
func (u *Utils) RegisterUser() {}
func (u *Utils) SendEmail() {}
func (u *Utils) GeneratePDF() {}
func (u *Utils) CalculateTax() {}
type UserService struct{}
func (s *UserService) RegisterUser() {}
func (s *UserService) DeleteUser() {}
func (s *UserService) GetUser() {}
Coupling is the degree of dependency between different modules, classes, or components in a software system.
we have two types of coupling:
interface OrderRepository {
void save(Order order);
}
class OrderService {
private final OrderRepository repository;
OrderService(OrderRepository repository) {
this.repository = repository;
}
void createOrder(Order order) {
repository.save(order);
}
}
class OrderService {
private MySQLDatabase db = new MySQLDatabase();
void createOrder(Order order) {
db.connect();
db.executeSQL("INSERT INTO orders ...");
}
}
so, the goal is to have: low coupling with high cohesion
| Metric | Meaning |
|---|---|
| 1. Coupling | How dependent is a class on other classes? |
| 2. Cohesion | How closely related are the responsibilities within a class? |
| 3. Sufficiency | Does the class have enough features to fulfill its purpose? |
| 4. Completeness | Does the class cover all useful behaviors expected of its abstraction? |
| 5. Primitiveness | Are the class's basic operations implemented directly, rather than built from other public operations? |