Refactoring 009 — Protect Public Attributes
Forget about data structures, DTOs, POJOs, and anemic objects.
Forget about data structures, DTOs, POJOs, and anemic objects.
TL;DR: Avoid external manipulation
Problems Addressed
Encapsulation Violation
Anemic Models
Related Code Smells
Code Smell 01 — Anemic Models
Your objects are a bunch of public attributes without behavior.blog.devgenius.io
Code Smell 40 — DTOs
DTOs are widely used and the ‘solve’ real problems, do they?blog.devgenius.io
Steps
Change the visibility of your attributes from public to private.
Sample Code
Before
public class Song {
String artistName;
String AlbumName;
}After
public class Song {
// 1- Change the visibility of your attributes from public to private
private String artistName;
private String AlbumName; // We cannot access attributes until we add methods
}Type
[X] Semi-Automatic
We can change the visibility with an IDE or text editor.
Safety
This is not a safe refactor.
Existing dependencies may break.
Why code is better?
We can change encapsulated code easily.
The code is not repeated.
Limitations
Some languages don’t have visibility options.
Tags
Anemic
Related Refactorings
Refactoring 001 — Remove Setters
Setters violate immutability and add accidental couplingblog.devgenius.io
Credits
This article is part of the Refactoring Series.
How to Improve your Code With easy Refactorings
Refactorings are amazing to grow and improve our codemcsee.medium.com


