# Refactoring 009 - Protect Public Attributes

> TL;DR: Avoid external manipulation

# Problems Addressed

- Encapsulation Violation

- Anemic Models

# Related Code Smells

%[https://maximilianocontieri.com/code-smell-01-anemic-models]

%[https://maximilianocontieri.com/code-smell-40-dtos]

# Steps

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

# Sample Code

## Before

[Gist Url]: # (https://gist.github.com/mcsee/803a3400fe6b241417de5abd17b89606)
```java
public class Song {
   String artistName;
   String AlbumName;
}
```

## After

[Gist Url]: # (https://gist.github.com/mcsee/bfefa85761d0030892bcbdd438ca7f59)
```java
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

%[https://maximilianocontieri.com/refactoring-001-remove-setters]

# Credits

Image by [Couleur](https://pixabay.com/users/couleur-1195798/) on [Pixabay](https://pixabay.com/)

* * * 

This article is part of the Refactoring Series.

%[https://maximilianocontieri.com/how-to-improve-your-code-with-easy-refactorings]
