Question

DUPE: Private vs. Public members in practice (how important is encapsulation?)

In the course of writing a program in Java, I have abstracted out some libraries that I can see a possible use for in future projects.

Why should I bother with setting restricted access (private/protected) on any of these methods?

It seems like this will just make my life more complicated in the future. If I use public on everything, I will never need to worry about whether I can call something from some other class. I have never seen a case in any of my code yet where it made any sense for me to use anything except public.

Is it so wrong to use 'public' on everything? Am I going to be struck down by the Java gods?

Was it helpful?

Solution

Yes, it's wrong to use public on everything. It means you have absolutely no concept of the difference between "this member is part of a public API; you're expected to be able to use it from the outside world, and it shouldn't change" and "this member is an implementation detail. If I want to change it later, I can do so because I know nothing from the outside world will be calling it."

Having a clear split between API and implementation is important for flexibility and clarity IMO.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top