Saikat
Saikat

Reputation: 16800

"Access can be private" warning message for public setter/mutator methods in IntelliJ IDEA

I have a public class with private fields and public setter methods to set those fields. Why IntelliJ IDEA is warning me saying "Access can be private" for these setter methods?

enter image description here

Upvotes: 3

Views: 3899

Answers (3)

Amos Kosgei
Amos Kosgei

Reputation: 947

IntelliJ IDEA is intelligent enough to scan your packages and class references within a package and if it notices that the usage is enclosed primarily to a certain package, then it will try to instill some discipline of adherence to encapsulation principles, and in this case: package privateness. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Simple: because IntelliJ doesn't see any usages for these method that would require them to be public in your project.

In other words: the IDE doesn't "know" that you made the setters public on purpose. It just figured: for what you are doing right now, you don't have to do that.

When writing "truly" public APIs, (maybe to be used by 3rd parties that later rely on your classes), this information is safe to ignore. So you might just go in and disable that warning, see here for example.

Beyond that: understand that you should avoid public setters where possible. Unless you have a "data bean" class, having setters/getters for each and any field is actually bad practice. You avoid outsiders to inspect internal state (using getters), and you very much want to prevent outsiders to overwrite internal state (using setters).

Upvotes: 4

Druckles
Druckles

Reputation: 3782

It means they are not used outside of the class and don't need to be public.

Restricting the access of methods keeps your interfaces small and reduces the chance of bugs creeping into your programs.

Upvotes: 1

Related Questions