> For the complete documentation index, see [llms.txt](https://petozoltan.gitbook.io/simplecode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://petozoltan.gitbook.io/simplecode/clean-code/clean-code-outline/classes.md).

# Classes

### Two Types of Classes

#### Procedural

Business logic or Service

* Stateless, singleton or static if possible
* Instantiated mostly by the DI framework - *Spring, Java EE*
* If stateful, create it from the code with `new`

#### Data structure

Entity, DTO (Data Transfer Object)

* Only data members
* No business logic
* Always instantiated as new - *by the database layer or with new from the code*
* Accessors/mutators are questionable - *getters/setters*

### Rules

* One reason to exist, change
* "Small"
* No "God" class - *"Sack", "Blob"*
* Encapsulation (hiding, protection) decreases dependency - *Other classes cannot depend on this*
* Tight cohesion

### Cohesion

* Implements the "one thing" rule
* Contains only dependent members
* Refactor to cohesive classes
* There will be many small classes - *Like a toolbox with drawers*
* Reduces amount, cost and risk of changes

### Interfaces

* Create interfaces for service classes -*but not always paranoidly for everything*
* Prefer interfaces to parent classes
* Create marker interfaces

### Class Smells

#### No meaningful name

* You cannot give a meaningful name - *e.g. "Parent", "Common", "Processor", etc.*

#### Unnecessary polymorphism

* Polymorphic class is not used as polymorphic - *never declared to parent type - see later*

#### Does more things - Low cohesion

* Many methods - *"God" or "Blob" class*
* Methods of a class can be split into distinct call chains - *they should be in separate classes*
* Test coverage is not visible or cheating
* Refactor to composition + Facade pattern

Example: Refactoring low cohesion

![](/files/-M1fWXiZYEg4A0Dq9399)

##
