DEV Community

Cover image for Refactoring 009 - Protect Public Attributes
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

8

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

  1. Change the visibility of your attributes from public to private.

Sample Code

Before

public class Song {
   String artistName;
   String AlbumName;
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

Credits

Image by Couleur on Pixabay


This article is part of the Refactoring Series.

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay