Java class containing only private members - java

Lately I met a situation where I needed to create a custom VideoView to my android application. I needed an access to the MediaPlayer object and to add some listeners.
Unfortunately (for me), all members of the VideoView class are private, so even extending the class wouldn't help me to gain access to its MediaPlayer object (or anything else), I had to make a complete duplicate of the class with my modifications.
Well, although it is sound like I'm complaining for the "hard work", it is easier than extending the class in this case (since all the source is available...), but it made me really doubt this method of information hiding. Is this a better practice than leaving main components available to modification / access (protected, not public)? I mean, I understand that if I extend the VideoView class, someday maybe they'll change something in the VideoView class and I might have troubles, but if they'll change the class, my own (duplicate) version will have a bigger difference from the VideoView class, and my goal is not to create my own video view, but to extend the available VideoView.

When a programmer makes something private, they're making a bet that nobody else will ever need to use or override it, and so there will be a payoff from the information hiding. Sometimes that bet doesn't come off. Them's the breaks.

I usually prefer composition rather than inheritance in such situations.
EDIT:
It's safe to use inheritance when both subclass and super class are in the control of the same programmer but implementation inheritance can lead to a fragile API. As you mentioned if superclass implementation changes then subclass can break or more worst - will do unintended things silently.
The other approach would be to have private field that references an instance of the existing class (VideoView) known as composition and each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This wrapper approach can be referred as 'Decorator' pattern as well

I can't speak for the reasoning of the particular VideoView developers, but if you're developing an API, and determine that the state represented by certain data needs to always follow certain rules in order to maintain the integrity and intended purpose of the object, then it makes sense to make the member vars private so you can control their modification.
It does limit what other devs can do, but I assume that's the point. There's some things that, if they were to be changed, you would want it to go through discussion and verification amongst the group that has governance over the API. In that case it makes sense to privatize so that modifications to it can't get out of hand outside of the group's oversight.
I don't know that there's a static rule of thumb that determines when something needs to fall into this category, but I can definitely see the use in certain cases.

When I read all the enlightening answers (and comments) and commenting to those I realized that I expected something which is irrelevant from some classes. In the case of VideoView fr example, this class is already the last in the inheritance chain. It should not be extended, as it is one logical unit, very specific and very tight, for a very specific purpose. My needs, to get special states from the view and the MediaPlayer, were needs for QC purposes, and such needs really shouldn't be considered when providing a product which is a closed unit (although the source is open). This is a reasonable argument and I find it satisfing. Sometimes not every concept of OOP should be implemented. Thank you all for the responses.

Related

'Swizzle' (Maybe by Reflection?) addView() On Android

I'm aware you cannot actually Swizzle in Java.
I was doing some research and I think 'maybe' you can do Reflection in Java to accomplish Swizzle like behaviour (that you can do on iOS).
The culprit (and one of the worst design decisions I've ever seen) is the addView() function on all Android ViewGroup objects. You must explicitly check if the parent is null (you sometimes even need to cast the parent to get the behaviour you need!). Gross.
I want to change the behaviour of this (without creating a million subclasses) by having the addView() method do this check automatically so the client code can ignore this.
Is this something I can do with Reflection (from what I grasp it would require special runtime calling, instead of actually changing the root method call [so maybe not good enough]), or something else? Or am I barking up the wrong tree?
As you mentioned, without creating a million subclasses (or better put, one subclass for every class where you would like to override the addView implementation) this doesn't seem possible. This would actually be the right way to do it, and it also means that you can use these subclasses in XML layout files.
Reflection would allow you to inspect classes/interfaces/fields/methods at runtime, but it won't allow you to change their already defined behaviour provided by the underlying implementation which has been compiled. Although some changes are possible, such as making private methods/fields accessible.
Grey-area options incoming...
One direction worth looking into would be Mockito, which allows you to create spies around existing object instances that would allow you to override the default implementation. This is achieved through Java's proxies and InvocationHandlers. However, at this point I'll stop and say that your production code should not contain any test code and Mockito is clearly meant for that. More so considering that, at least in the past, it used to be hard (if not impossible) to put proxies around some of Android's classes such as Views and Contexts. I believe this has been resolved by DexMaker, which I have less knowledge of myself but it does allow you to perform runtime code generation. This would be another direction worth looking at. I personally think that neither of these should be taken as possible solutions worthy of production code, but something to have a play with for your own curiosity and to learn from.

Game programming: passing main class to every object

I know it's not efficient, but I don't really know why.
Most of the time, when you implement your game you got a main class which has a loop and updates every frame and creates certain objects.
My question is why it's not considered efficient to pass the main class to every object in its constructor?
In my case, I developed my game in Java for Android, using LibGDX.
Thank you!
It increases coupling (how much objects depend on each other) and therefore reduces re-usability and has the tenancy to produce 'spaghetti code'. I don't really understand what you mean by not being 'efficient', but this is why you shouldn't do it.
You should also consider why you need that main class in every single object. If you really think you do, you might need to reconsider your system design. Would you mind elaborating on why you think you need it?
Mostly, it is a matter of coupling the code and making proper design decisions.
You should avoid dependencies between classes whenever possible. It makes the code easily maintainable and the whole design clearer.
Consider the case: you are creating a simulation racing game. You have a few classes for such entities: wheel, engine, gearshift knob, etc... and non-entities: level, player...
Let's say, you have some main point (i.e. GameEngine class where you create instances).
According to you're approach you want to pass GameEngine's instance in entities constructors (or related mutator methods). It's not the best idea.
You really want to allow wheels or breaks to have the knowledge about the rest of the world (such as player's informations, scores, level etc.) and give them access to it's public interface methods?
All classes should have at small level of responsibility (and knowledge about other items) as possible.
If you really need reference to some kind of main point object in you're classes consider using dependency injection tools, such as Dagger.
It won't make you're game design better, but, at least, forces you to favor composition over inheritance - what leads to create better code.
It's not entirely inefficient, since (afiak in the general case) passing a reference to a method is quite cheap when you consider the number of JVM opcodes required, however, a possibly more efficient way of doing this would be to make a static instance of the game class and access that static field from the other classes. You would have to test these two options yourself.
In addition, passing a reference to the methods could make maintaining the code harder, as you have ultimately added a dependency.

Why do we need getters?

I have read the stackoverflow page which discusses "Why use getters and setters?", I have been convinced by some of the reasons using a setter, for example: later validation, data encapsulation, etc. But what is the reason of using getters anyway? I don't see any harm of getting a value of a private field, or reasons to validation before you get the a field's value. Is it OK to never use a getter and always get a field's value using dot notation?
If a given field in a Java class be visible for reading (on the RHS of an expression), then it must also be possible to assign that field (on the LHS of an expression). For example:
class A {
int someValue;
}
A a = new A();
int value = a.someValue; // if you can do this (potentially harmless)
a.someValue = 10; // then you can also do this (bad)
Besides the above problem, a major reason for having a getter in a class is to shield the consumer of that class from implementation details. A getter does not necessarily have to simply return a value. It could return a value distilled from a Collection or something else entirely. By using a getter (and a setter), we free the consumer of the class from having to worry about the implementation changing over time.
I want to focus on practicalities, since I think you're at a point where you haven't seen the conceptual benefits line up just yet with the actual practice.
The obvious conceptual benefit is that setters and getters can be changed without impacting the outside world using those functions. Another Java-specific benefit is that all methods not marked as final are capable of being overriden, so you get the ability for subclasses to override the behavior as a bonus.
Overkill?
Yet you're probably at a point where you've heard these conceptual benefits before and it still sounds like overkill for your more daily scenarios. A difficult part of understanding software engineering practices is that they are generally designed to deal with very real world, large-scale codebases being managed by teams of developers. A lot of things are going to seem like overkill initially when you're just working on a small project of your own.
So let's get into some practical, real-world scenarios. I formerly worked in a very large-scale codebase. It a was low-level C codebase with a long legacy and sometimes barely a step above assembly, but many of the lessons I learned there translate to all kinds of languages.
Real-World Grief
In this codebase, we had a lot of bugs, and the majority of them related to state management and side effects. For example, we had cases where two fields of a structure were supposed to stay in sync with each other. The range of valid values for one field depended on the value of the other. Yet we ran into bugs where those two fields were out of sync. Unfortunately since they were just public variables with a very global scope ('global' should really be considered a degree with respect to the amount of code that can access a variable rather than an absolute), there were potentially tens of thousands of lines of code that could be the culprit.
As a simpler example, we had cases where the value of a field was never supposed to be negative, yet in our debugging sessions, we found negative values. Let's call this value that's never supposed to be negative, x. When we discovered the bugs resulting from x being negative, it was long after x was touched by anything. So we spent hours placing memory breakpoints and trying to find needles in a haystack by looking at all possible places that modified x in some way. Eventually we found and fixed the bug, but it was a bug that should have been discovered years earlier and should have been much less painful to fix.
Such would have been the case if large portions of the codebase weren't just directly accessing x and used functions like set_x instead. If that were the case, we could have done something as simple as this:
void set_x(int new_value)
{
assert(new_value >= 0);
x = new_value;
}
... and we would have discovered the culprit immediately and fixed it in a matter of minutes. Instead, we discovered it years after the bug was introduced and it took us meticulous hours of headaches to trace it down and fix.
Such is the price we can pay for ignoring engineering wisdom, and after dealing with the 10,000th issue which could have been avoided with a practice as simple as depending on functions rather than raw data throughout a codebase, if your hairs haven't all turned grey at that point, you're still generally not going to have a cheerful disposition.
The biggest value of getters and setters comes from the setters. It's the state manipulation that you generally want to control the most to prevent/detect bugs. The getter becomes a necessity simply as a result of requiring a setter to modify the data. Yet getters can also be useful sometimes when you want to exchange a raw state for a computation non-intrusively (by just changing one function's implementation), e.g.
Interface Stability
One of the most difficult things to appreciate earlier in your career is going to be interface stability (to prevent public interfaces from changing constantly). This is something that can only be appreciated with projects of scale and possibly compatibility issues with third parties.
When you're working on a small project on your own, you might be able to change the public definition of a class to your heart's content and rewrite all the code using it to update it with your changes. It won't seem like a big deal to constantly rewrite the code this way, as the amount of code using an interface might be quite small (ex: a few hundred lines of code using your class, and all code that you personally wrote).
When you work on a large-scale project and look down at millions of lines of code, changing the public definition of a widely-used class might mean that 100,000 lines of code need to be rewritten using that class in response. And a lot of that code won't even be your own code, so you have to intrusively analyze and fix other people's code and possibly collaborate with them closely to coordinate these changes. Some of these people may not even be on your team: they may be third parties writing plugins for your software or former developers who have moved on to other projects.
You really don't want to run into this scenario repeatedly, so designing public interfaces well enough to keep them stable (unchanging) becomes a key skill for your most central interfaces. If those interfaces are leaking implementation details like raw data, then the temptation to change them over and over is going to be a scenario you can face all the time.
So you generally want to design interfaces to focus on "what" they should do, not "how" they should do it, since the "how" might change a lot more often than the "what". For example, perhaps a function should append a new element to a list. However, you may want to swap out the list data structure it's using for another, or introduce a lock to make that function thread safe ("how" concerns). If these "how" concerns are not leaked to the public interface, then you can change the implementation of that class (how it's doing things) locally without affecting any of the existing code that is requesting it to do things.
You also don't want classes to do too much and become monolithic, since then your class variables will become "more global" (become visible to a lot more code even within the class's implementation) and it'll also be hard to settle on a stable design when it's already doing so much (the more classes do, the more they'll want to do).
Getters and setters aren't the best examples of such interface design, but they do avoid exposing those "how" details at least slightly better than a publicly exposed variable, and thus have fewer reasons to change (break).
Practical Avoidance of Getters/Setters
Is it OK to never use a getter and always get a field's value using dot notation?
This could sometimes be okay. For example, if you are implementing a tree structure and it utilizes a node class as a private implementation detail that clients never use directly, then trying too hard to focus on the engineering of this node class is probably going to start becoming counter-productive.
There your node class isn't a public interface. It's a private implementation detail for your tree. You can guarantee that it won't be used by anything more than the tree implementation, so there it might be overkill to apply these kinds of practices.
Where you don't want to ignore such practices is in the real public interface, the tree interface. You don't want to allow the tree to be misused and left in an invalid state, and you don't want an unstable interface which you're constantly tempted to change long after the tree is being widely used.
Another case where it might be okay is if you're just working on a scrap project/experiment as a kind of learning exercise, and you know for sure that the code you write is rather disposable and is never going to be used in any project of scale or grow into anything of scale.
Nevertheless, if you're very new to these concepts, I think it's a useful exercise even for your small scale projects to err on the side of using getters/setters. It's similar to how Mr. Miyagi got Daniel-San to paint the fence, wash the car, etc. Daniel-San finds it all pointless with his arms exhausted on top of that. Then Mr. Miyagi goes "hyah hyah hyoh hyah" throwing big punches and kicks, and using that indirect training, Daniel-San blocks all of them without realizing how he's even doing it.
In java you can't tell the compiler to allow read-only access to a public field from outside.
So exposing public fields opens the door to uncontroled modifications.
Fields are not polymorphic.
The alternative to a getter would be a public field; however, fields are not polymorphic.
This means that you cannot extend the class and "override" the field without introducing weird behaviour. Basically, the value you get will depend on how you refer to the field.
Furthermore, you can't include the field in an interface and you can't perform validation (that applies more to a setter).

The missing "framework level" access modifier

Here's the scenario. As a creator of publicly licensed, open source APIs, my group has created a Java-based web user interface framework (so what else is new?). To keep things nice and organized as one should in Java, we have used packages with naming convention
org.mygroup.myframework.x, with the x being things like components, validators, converters, utilities, and so on (again, what else is new?).
Now, somewhere in class org.mygroup.myframework.foo.Bar is a method void doStuff() that I need to perform logic specific to my framework, and I need to be able to call it from a few other places in my framework, for example org.mygroup.myframework.far.Boo. Given that Boo is neither a subclass of Bar nor in the exact same package, the method doStuff() must be declared public to be callable by Boo.
However, my framework exists as a tool to allow other developers to create simpler more elegant R.I.A.s for their clients. But if com.yourcompany.yourapplication.YourComponent calls doStuff(), it could have unexpected and undesirable consequences. I would
prefer that this never be allowed to happen. Note that Bar contains other methods that are genuinely public.
In an ivory tower world, we would re-write the Java language and insert a tokenized analogue to default access, that would allow any class in a package structure of our choice to access my method, maybe looking similar to:
[org.mygroup.myframework.*] void doStuff() { .... }
where the wildcard would mean any class whose package begins with org.mygroup.myframework can call, but no one else.
Given that this world does not exist, what other good options might we have?
Note that this is motivated by a real-life scenario; names have been changed to protect the guilty. There exists a real framework where peppered throughout its Javadoc one will find public methods commented as "THIS METHOD IS INTERNAL TO MYFRAMEWORK AND NOT
PART OF ITS PUBLIC API. DO NOT CALL!!!!!!" A little research shows these methods are called from elsewhere within the framework.
In truth, I am a developer using the framework in question. Although our application is deployed and is a success, my team experienced so many challenges that we want to convince our bosses to never use this framework again. We want to do this in a well thought out presentation of the poor design decisions made by the framework's developers, and not just as a rant. This issue would be one (of several) of our points, but we just can't put a finger on how we might have done it differently. There has already been some lively discussion here at my workplace, so I wondered what the rest of the world would think.
Update: No offense to the two answerers so far, but I think you've missed the mark, or I didn't express it well. Either way allow me to try to illuminate things. Put as simply as I can, how should the framework's developers have refactored the following. Note this is a really rough example.
package org.mygroup.myframework.foo;
public class Bar {
/** Adds a Bar component to application UI */
public boolean addComponentHTML() {
// Code that adds the HTML for a Bar component to a UI screen
// returns true if successful
// I need users of my framework to be able to call this method, so
// they can actually add a Bar component to their application's UI
}
/** Not really public, do not call */
public void doStuff() {
// Code that performs internal logic to my framework
// If other users call it, Really Bad Things could happen!
// But I need it to be public so org.mygroup.myframework.far.Boo can call
}
}
Another update: So I just learned that C# has the "internal" access modifier. So perhaps a better way to have phrased this question might have been, "How to simulate/ emulate internal access in Java?" Nevertheless, I am not in search of new answers. Our boss ultimately agreed with the concerns mentioned above
You get closest to the answer when you mention the documentation problem. The real issue isn't that you can't "protect" your internal methods; rather, it is that the internal methods pollute your documentation and introduce the risk that a client module may call an internal method by mistake.
Of course, even if you did have fine grained permissions, you still aren't going to be able to prevent a client module from calling internal methods---the jvm doesn't protect against reflection based calls to private methods anyway.
The approach I use is to define an interface for each problematic class, and have the class implement it. The interface can be documented solely in terms of client modules, while the implementing class can provide what internal documentation you desire. You don't even have to include the implementation javadoc in your distribution bundle if you don't want to, but either way the boundary is clearly demarcated.
As long as you ensure that at runtime only one implementation is loaded per documentation-interface, a modern jvm will guarantee you don't suffer any performance penalty for using it; and, you can load harness/stub versions during testing for an added bonus.
The only idea that I can think in order to supply this missing "Framework level access modifier" is CDI and a better design.
If you have to use a method from very different classes and packages in various (but few) situations THERE WILL BE certainly a way to redesign those classes in order to make those methods "private" and inacessible.
There is no support in Java language for such kind of access level (you would like something like "internal" with namespace). You can only restrict access to package level (or the known inheritance public-protected-private model).
From my experience, you can use Eclipse convention:
create a package called "internal" that all class hierarchy (including sub-packages) of this package will be considered as non-API code and could be changed anytime with no guarantee for your users. In that non-API code, use public methods whenever you like. Since it is only a convention and it is not enforced by the JVM or Java compiler, you cannot prevent users from using the code, but at least let them know that these classes were not meant to be used by 3rd parties.
By the way, in Eclipse platform source code, there is a complex plugin model that enforces you not to use internal code of other plugins by implementing custom class loader for each plugin that prevents loading classes that should be "internal" in these plugins.
Interfaces and dynamic proxies are sometimes used to make sure you only expose methods that you do want to expose.
However that comes at a fairly hefty performance cost, if your methods are called very often.
Using the #Deprecated annotation might also be an option, although it won't stop external users invoking your "framework private" methods, they can't say they hadn't been warned.
In general I don't think you should worry about your users deliberately shooting themselves in the foot too much, so long as you made it clear to them that they shouldn't use something.

Java Design Questions - Class, Function, Access Modifiers

I am newbie to Java. I have some design questions.
Say I have a crawler application, that does the following:
1. Crawls a url and gets its content
2. Parses the contents
3. Displays the contents
How do you decide between implementing a function or a class?
-- Should the parser be a function of the crawler class, or should it be a class in itself, so it can be used by other applications as well?
-- If it should be a class, should it be protected or public class?
How do you decide between implementing a public or protected class?
-- If I had to create a class to generate stats from the parsed contents for eg, should that class be protected (so only the crawler class can access it) or should it be public?
Thanks
Ron
I think Andy's answer is very good. I have a few additions:
If you believe that a class will be extended in the future, you can set all your private methods (if any) to protected. In this way, any future extending classes can also access these.
I like the rule that a method shouldn't be longer than that you can see its opening and closing brackets ({ }) without scrolling. If a method is longer than that, try to split it up into several methods (private, protected or public by your preference). This makes code more readable, and could also save on lines of code.
So let's say a method is getting big and you split it up into several private methods. If these new methods are only used within the first "mother"-method, it makes sense to move all of that into a class of its own. In this way you will make the original class smaller and more readable. In addition, you will make the functionality of the new class easier to understand, as it is not mixed up with that of the original class.
The best guidance I've seen for these types of questions is the "SOLID Principles of OO Design."
http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod
The most basic of these principles, and the one that sort of answers your first question is the "Single Responsibility Principle." This states that, "a class should have one, and only one, reason to change." In other words, your classes should each do exactly one thing. If you end up needing to change how that one thing works, you only have one class to change, and hopefully just one place to make the change within that class. In your case, you would probably want a class to retrieve the content from the URL, another class to parse it into some sort of in-memory data structure, another class to process the data (if needed), and yet another class (or classes) to display the content in whatever format you need. Obviously, you can get carried away with classes, but it's typically easier to test a lot of small, single-operation classes, as opposed to one or two large, all-encompassing classes.
The question on public vs. protected depends on how you plan to use this code. If your class could be used independently outside your library, you could think about making it public, but if it accomplishes some task which is specific or tied to your other classes, it could probably be protected. For example, a class to retrieve content from a URL is a good general-purpose class, so you could make it public, but a class that does some specific type of manipulation of data might not be useful outside your library, so it can be protected. Overall, it's not always black and white, but ultimately, it's usually not a huge deal either way.
I like to think of classes as "guys" who can do specific stuff "methods".
In your case, theres a guy who can fetch the content of an url if you tell him which url that is.
Then there is this another guy, that is really good at parsing content. I think he does that with a tool called rome, but i'm not sure. he keeps that private (hint ;) )
Then we have that third guy, who displays stuff. He's a bit retarded and only understands stuff that "another guy" produces, but hey thats fine.
Finally the project needs a boss guy, who gives orders to the other 3 guys and passes messages between them.
ps: I never really though about making classes protected or not. Usually they are simply public without any specific reason. As long as it don't hurt, why bother?

Categories