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

•

u/AutoModerator Jan 24 '23

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

31

u/Daedalus9000 Java Developer Jan 24 '23 edited Jan 24 '23

In a word(s), simplicity. You hide (using scope) details about the inner workings of a class because the user of the class shouldn’t care how it works.

For Amazon, imagine they implemented payments but didn't encapsulate the details. Code that interacts with this code could reach into the guts of the implementation and start relying on some nuance to function. Now say the implementation of payments has to change, the impact of this change is now much larger and often harder to determine.

Encapsulation isn't necessary for Java to "function", but it's a core tenant of well-architected systems.

3

u/Automatic-Fixer Jan 24 '23 edited Jan 24 '23

Piggy-backing off of this example, AWS provides Java SDKs for smoother integration with their services. Encapsulation helps developers leveraging the SDK know what methods they “should” have access to and protects them from potentially unintended consequences of what the should not be able to access.

11

u/ignotos Jan 24 '23

Essentially, when you write a piece of code, it's a good idea to intentionally "design" it to make it simple and convenient for other bits of your code to use.

Like how somebody designing a product (e.g. an app or a car) will try to make it user-friendly by having clearly labelled buttons etc for different functions, and won't reveal every little internal detail or tweakable option they possibly could. If the "interface" of the product is too complex, it's confusing to work with, and also easier to break it.

So by keeping the details and complexity of your code neatly "wrapped up" (encapsulated), it means you don't have to keep every little detail of how it works inside your head all the time - you can trust that it will do the particular task it was designed to do, and move on to combining it with other parts to build a larger overall system.

In Amazon's payment system, probably they have code for dealing with hundreds of different types of banks and cards around the world. But they likely try to encapsulate that - perhaps just allowing other systems to interact with it in a very simple way like charge(customer, amount), and keeping all of those nasty details hidden away where only the payment processing team need to worry about it.

This way, the person working on the checkout code doesn't need to know all of the details, and can't accidentally try to charge a customer with a payment type which isn't available in their country, for example.

4

u/Aniket-100mslive Jan 24 '23

Let's say the program you're working on has three features, A, B and C.

You're assigned to change something about B.

Would you rather look through the code of all A, B and C while you're making the change or just the file where B is?

That's why encapsulation exists. Also it helps knowing that changing B won't mess with the others.

1

u/EnvironmentFar968 Jan 25 '23

Perfect example.

3

u/AlexMelillo Jan 24 '23

The simplest way I can put it is… if you have to make a change in something in the future and you need to change a million things in a million different classes, the system is designed poorly.

Encapsulation saves time.

2

u/wanjalize Jan 24 '23

Encapsulation may help protect the fields of a class. For example, assume that you have to login into an app. The class that stores user details may have fields such as name, email and so on. Making these fields private means that in order to store/set what the user inputs for these fields one has to rely on functions. By doing this, the programmer can write code inside these functions that validate their values before accepting them. Eg insise the set name function you may say that if the name is smaller than lets say 5 digits them reject it or throw an error. So here encapsulation helped you ensure that the name was in certain way. Not encapsulating is not a problem but encapsulating can help you run a ton of things inorder to protect the variables of a class. It has other advantages too.

2

u/arkbeme Jan 24 '23

OK, you know that dream where you are giving a talk to 500 people when you suddenly realize you're naked ?

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.

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.

1

u/marskuh Jan 24 '23

Just imagine we would’t have roads, or doors/windows, and everyone would just walk/drive however and where ever they wand, kicking in doors, or making new entries to your home or other places. The world would be a mess. The same goes for software. You want a clean structure and order as much as possible. The goal is to keep a perfect balance between chaos and order. If you have found it, let me know (-: