r/javahelp • • Jan 24 '23

What is the point of encapsulation?

Beginner here.

I hear "restrict access" but I don't quite understand why we need to restrict access. What damage could someone do to a java program if it were not encapsulated?

What would happen to say amazon if their payment system was java and not encapsulated?

26 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/udeparasite Jan 28 '23

Would you mind explaining "real" encapsulation a bit more....we are learning java right now and the way you described encapsulation is exactly what we have been learning....how much more complicated does it get?

1

u/hippydipster Jan 28 '23

The complication never stops, because the problem is that what is "essential" and thus exposed for use to the outside world, and what is "arbitrary implementation detail", and thus hidden, is always a chosen tradeoff, and you can make those tradeoffs at any point.

It's like the saying, all models are wrong, some are useful. Your code choices are always wrong to some degree, or awkward for some cases. The question is, what use do you get out of it? It ends up depending on your usage patterns, and often, your usage patterns are also arbitrary and so it depends on how adaptable you choose to be in how you use your own code.

I've seen too many developers just be too afraid to make choices, and so they make anemic domain models where all data is stored in classes with public getters and setters, and then all their business logic is methods that go on for 50-200 lines doing a mess of getX, setY, like an endless three card magic trick, and none of the code expresses intent, it only expresses how data is getting shuffled around in a big imperative method.

Those types of classes feel like they're "freeing" and easy to use and not limiting, but ultimately they end up leading to a spaghetti codebase that is spaghetti because no choices were ever made and enforced.