Skip to content

Latest commit

 

History

History
101 lines (59 loc) · 2.85 KB

File metadata and controls

101 lines (59 loc) · 2.85 KB

Code Smell 142 - Queries in Constructors

Code Smell 142 - Queries in Constructors

Accessing a database in domain objects is a code smell. Doing it in a constructor is a double smell

TL;DR: Constructors should construct (and probably initialize) objects.

Problems

Solutions

  1. Decouple essential business logic from accidental persistence

  2. On persistence classes, run queries in functions other than constructors/destructors

Context

On legacy code, the database is not correctly separated from business objects.

Constructors should never have side effects.

According to the single responsibility principle, they should only build valid objects

Sample Code

Wrong

public class Person {
  int childrenCount; 

  public Person(int id) {
    childrenCount = database.sqlCall(
      "SELECT COUNT(CHILDREN) FROM PERSON WHERE ID = " . id); 
  }
}

Right

public class Person {
  int childrenCount; 

  public Person(int id, int childrenCount) {
    this.childrenCount = childrenCount; 
    // You can assign the number in the constructor
    // Accidental Database is decoupled
    // You can test the object
  }
}

Detection

[X] Semi-Automatic

Our linters can find SQL patterns on constructors and warn us.

Tags

  • Coupling

Conclusion

Separation of concerns is key and coupling is our main enemy when designing robust software.

Relations

Code Smell 205 - Code in Destructors

More Info

Credits

Photo by Callum Hill on Unsplash


My belief is still, if you get the data structures and their invariants right, most of the code will kind of write itself.

Peter Deustch

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code