r/javahelp • u/[deleted] • May 15 '21
Solved Hard time understanding abstraction and encapsulation with relation to how it hides details to a user/consumer.
Emphasis on user & consumer, because that's the source of mystery to me. I don't understand what people mean by users and consumers, when they say that "you can hide data from a user" or "users need see only the abstract methods in an interface hiding implementation details" when following encapsulation and abstraction principles, respectively. What's the user here — a hacker, a regular client, both?
For example, I know a project can be released and packaged as a JAR file. Upon inspection, the Zip file contains class files and meta data. A user can then run the JAR if they have JRE, or use WinRAR to inspect the stuff in the JAR file. But they never really see any of the *.java files, or code that makes up the application. Like why would encapsulation or abstraction be necessary for security reasons, if they can't see the code in the first place?
I think I am interpreting this the complete wrong way. Like what do developers even give to consumers in a production setting? How does encapsulation and abstraction be useful for consumers if they can see certain types of stuff? And what is the scope of stuff they see / given? Are they given only certain java files? JAR?
Edit: I really need a concrete example involving a seller and clientele, if anything! Also, my post might come off as rant-like. I'm sorry, but I have been trying to figure out my lapses in understanding, and it has been overwhelmingly fruitless. Last time I felt this way, was when I had to understand the watch order of the Fate series.
5
May 15 '21 edited May 15 '21
What's the user here — a hacker, a regular client, both?
It's typically talking about the calling code. But we can talk about it in terms of users...
Like why would encapsulation or abstraction be necessary for security reasons, if they can't see the code in the first place?
It's not about "security". It's about not depending on details.
Let's say you look at the source code of a library and find some ways you can hack the code to get around the interfaces that the library provided you. For example, the library officially returns to you an interface reference from a method, but from the source code of the method, you can see what the real implementation is, so you cast around the interface to get to the real class.
Now, the library is upgraded, but the author changed the details, but preserved the abstract interface. But because you depended on details, you can't upgrade, because your hacks will no longer work.
By hiding data and providing abstract interfaces that hide implementation details, you are protecting your users (so that they don't have to change their code when you change the details) and giving yourself flexibility to change things (because the details are hidden).
1
May 16 '21 edited May 16 '21
I think I understand better. Clarify me if I am wrong in my thinking:
So encapsulation is not really a data security model, as it is a programming paradigm. At its core, it is the simple idea of bundling methods and variables together in a class.
The beauty of encapsulation, which I finally realize, is that I can control the implementation of these getter and setters, and that not all private variables need to have getters and setter. This took me so long to get. The fact that I can allow users* to only allow some variables to be read-only access, gives ME control. With direct access, however, the users* can unintentionally make changes. I think issues occur when developers just add all setters and getters for all private variables, without understanding the purpose of their variables.
(Of course for JavaBeans and recently when I was messing with JPA and Hibernate, you kinda need to have both public getter and setters. So there are tradeoffs to what you, the developer, can control when using certain libraries/frameworks.)
I asterisked the users to mean other DEVELOPERS. (A simplification, but it helps me understand this for now). For example, another developer and I are working on a project. By setting private variables and enabling certain getters and setters, my fellow peer understands what they should touch and what they shouldn't touch. It's NOT really for SECURITY reasons (why the fuck did I put this in my brain??) as it is just hiding details. It makes interaction with code much smoother, and helps not change state of the objects that can severely impact application and clients who depend on your application.
The whole JAR thing I said is retarded. Yes a user (in this case some random person in the universe) can execute a runnable JAR via a Windows command line call like this:
java -jar <jar-file-name>.jarYes, users can even access methods from JAR. They can also decompile the entire program, and get the source code, if you give them a runnable JAR and they have a JVM, even with encryption related practices. Encapsulation has very little to do with security practices and this stage, as it has to do with hiding details in the development process.
7
u/ratskinmahoney May 15 '21
In the terms you're discussing here the user would be any legitimate user of the API that your code presents. So something like, any developer who gets hold of your jar (or whatever) to incorporate into some code they are writing and hence is interacting with your code as Java. They are dealing with the Java classes that you have written.
The principles of encapsulation, abstraction, and so on are there to ensure that they only have access to the things you want them to use, and for which you provide some guarantee that they work and will continue to work in the future. Encapsulation, for instance, prevents those users from accessing methods or state in your objects that you don't want them accessing directly, and means that you can change or remove those things without breaking the user's code. Abstraction allows you to hide entire classes from them so that they are only permitted to deal with e.g. an interface. This has a similar effect, but allows you to replace entire classes, so long as you replace them with something else that provides the abstraction (e.g. implements the interface).
The goal of this is (broadly) twofold:
Make your life easier by limiting the number of things you have to keep the same in order to avoid annoying your users
Make your user's life easier by making clear what they should be using, and giving some guarantee that this won't change
That last point isn't an absolute - develops change their APIs fairly often - but there would normally be some reasonable expectation of what might change for a major release version vs a minor release version, and some commitment to very clearly communicate such a change. A private method, or a particular implementation of an interface on the other hand might change frequently and without warning.
4
u/RaisinAlert May 15 '21
A user could also be yourself in the future when you’ve moved to a different part of the project.
3
u/ratskinmahoney May 15 '21
I just noticed your edit. For an example, look at what Java itself provides: pick something like an ArrayList and see what private methods and variables it hides from you. Oracle or openjdk or whoever can change those from release to release to fix bugs or improve performance without bothering you, the user since the public methods are still there.
Now have a look at something like Collections.singletonList(). This just returns the interface List, so this could be provided by an ArrayList or a LinkedList or something else: whatever the developer feels works best. Again they can change this from release to release if they think something else might work better.
1
u/ZukoBestGirl May 15 '21
I believe in a more pragmatic way of explaining things, even if this looses some academic details or is only mostly correct. I think it's a much quicker way of getting a simple working understanding of something, and you can go into details later when they'll matter.
But before that, api users:
API basically means exposed methods that other developers can use to do things with your stuff. Be it web endpoint, or a public method in some class. In the context of API, users are always a form of developers. Just because you too are a developer, doesn't mean somoene else doesn't see you as a user. U are a user of the language you code in, of the IDE you use, and of the libraries you use.
A library, like Commons Lang from apache, has an API (public methods). Same for classes like StringUtils, or even Java's very own String class.
About encapsulation and the need for it
Encapsulation is rather easy. But there are two steps to this. Lets say you have decided that something in your class will never ever have write access (public final field). This can never be changed, it is initialized with the only value it will ever have. Think of immutables, like string. In that case, you could just expose length and be done with it. I think charSequence? something in java lang does this but I completely forget what. There aren't many arguments against it, if there is no chance this design will ever change.
But what if you aren't completely 100% sure about it never ever changing? Even if you are, it still might.
Or now think, that you have a field that you don't care when someone decides to change the value. Why not make it public and let them do whatever with it?
Well, there are reasons.
Future Proofing and no breaking other people's code
Maybe, at some point in time, you decide that something has to change, internally. You can no longer store the data in a list, you need a map, or whatever. You can still give the person a list on a getWhatever() method. But if they had direct access, and you change even the name of the field, not even talking about the whole signature, everyone using your api has their code broken.
You do not want to do that. You don't want hudnreds of thousands of developers cursing your name, because your field had a typo and you wanna fix it. Or change internal structures for optimization. So on and so forth.
Do not code against details, code against contracts
In software, the details of how something is done, should never be important, except for the people implementing that thing. Everyone using it, should be able to use it for a very long time (think decade) without changing anything on their end. For a specific input, they should get a specific output. Everything else does not matter.
The logic inside someone else's class, how the store and retrieve data, how they process input. None of that should ever matter.
So you hide all of that, and expose only things that are meant to be used by others. Anything internal, private, can change at any point in time. This is desired, this is the whole idea. It lets you optimize your shit, without bothering people.
2
May 16 '21 edited May 16 '21
ZukoBestGirl
So is AzulaBestBoy xD? Also, I understand encapsulation a little better now because of this response!
1
2
u/iNetRunner May 15 '21
Have you tried to read any Object Oriented language basics textbooks? Regarding your specific questions, these Wikipedia articles give good answers: encapsulation, inheritance, abstraction.
Jar package isn’t meant to be viewed by the end user. Sure it’s based on zip compression, and in rare occasions it might include documentation (javadoc generated API documentation) or sources (for debugging purposes). But it is basically another layer of abstraction than above mentioned OOP term abstraction.
2
u/vsaonline May 15 '21
Users are think of another programmer, so 2 teams are working one is dealing with providing data from lets say yahoo finance on prices and your team is performing some calculation on prices. You will be abstracted from price provider api internals by accessing the prices through interface.
2
u/bentheone May 15 '21
A good real life analogy is a car. You use the wheel to steer in every car, whatever happens under the hood is irrelevant to you. The wheel of the car is the public API of the car, the inner mechanics is what is abstracted, hidden from you. Thanks to that you can drive evey car the same way.
Also, understand that you don't always write programs for others to use, sometimes its only classes and methods, so how and what you expose to the user is important.
1
May 15 '21 edited May 15 '21
Think on an address book library.
It's value (what it's supposed to do) is to store the address and the phone number for (multiple) given person.
With this you'll need, let's say, three methods
addressBook.save(name, phone, address);
addressBook.getPhone(name);
addressBook.getAddress(name);Now, how it does that is no concern of the client/user class. It might be using in-memory map, a database, a file or maybe a little green man... The point is that it doesn't matter (to the class that is using it). That's encapsulation.
Now, for abstraction.
As said before, there are many ways to do things. If you create an abstraction of it (abstract class or interface are the most used) you can switch implementations easily.
Your little green man implementation is no longer enough? Then use the database one. All you need is to change a single line (if properly done).
Edit. For your Seller/Client, maybe calling for the list of available products. The Client does not care on how the Seller stores that info. Or a makeOrder method, again, the Client just wants to place an order, no matter what (and how) the Sellers do internally in order to comply.
Edit 2. I hope this example helps.
//Seller with no encapsulation
List<PurchaseOrder> orders = seller.getOrders();
orders.add(new PurchaseOrder(product, quantity));In this first example the Client knows that the Seller have a list of orders and, to place a new one, it has to get such list and add the new order. In this case the inner working (the list) is exposed (as opposed to encapsulated).
//Seller with encapsulation
seller.makeOrder(product, quantity);In this second example the Client does not know how the Seller is storing and handling the order, it is encapsulated. It might be using a list like the previous example, or maybe not. Even better, it can change how it works and the Client will be oblivious to that change
0
May 15 '21
I think I am interpreting this the complete wrong way
Yes.
What exactly do you think they are?
Have you ever built your own project?
1
May 16 '21
I'm an idiot. I deserve this response.
1
May 16 '21
Its OK.
The thing about your question is like -> the person who will answer will really have to think from where he should start.
you need to go through refences first - https://en.wikipedia.org/wiki/Programming_paradigm, https://en.wikipedia.org/wiki/Object-oriented_programming
•
u/AutoModerator May 15 '21
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://imgur.com/a/fgoFFis) 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:
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.