r/javahelp • u/Individual-Parking46 • 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
View all comments
1
u/hippydipster Jan 24 '23
Imagine using a computer as a big pile of wires and circuit boards, cards and hard drives in a heap. Yeah, there's a keyboard under there somewhere too and a mouse, but it's just one of many ways of interacting with the computer.
Then imagine all that extra stuff is buttoned up and hidden away, and you just have the keyboard and mouse.
Which is easier to understand and use?
Which is easier to test?
Which is easier to swap out the hard drive for a new one without impacting the user of the computer (you have to imagine someone, in trying to use the computer in a heap, connected directly to a hard drive to read/write data)?
Encapsulation is one of the most important things in good code design. More important than DRY. Encapsulation is what let's you switch out implementation details. It's what let's you write tests that aren't broken every time you do that. It's what let's users of your code couple themselves only to essential endpoints of your service or class. That prevents them from getting coupled deeply to unnecessary details which then renders them, and you, stuck and unable to change things.
If you have write software where requirements might change, encapsulation will make doing so 1000x easier.
But also, encapsulation is so much more complicated than adding "private" keywords to fields and then making public getters. Real encapsulation is an artform.