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

s4ik4t :

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

GhostCat salutes Monica C. :

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).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=129533&siteId=1