This content originally appeared on Level Up Coding - Medium and was authored by Maximiliano Contieri
Refactoring 009 — Protect Public Attributes
Forget about data structures, DTOs, POJOs, and anemic objects.
TL;DR: Avoid external manipulation
Problems Addressed
- Encapsulation Violation
- Anemic Models
Related Code Smells
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
Credits
This article is part of the Refactoring Series.
How to Improve your Code With easy Refactorings
Refactoring 009 — Protect Public Attributes was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Maximiliano Contieri
Maximiliano Contieri | Sciencx (2022-10-26T02:45:10+00:00) Refactoring 009 — Protect Public Attributes. Retrieved from https://www.scien.cx/2022/10/26/refactoring-009-protect-public-attributes/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.