Private Class Variables vs Excessive Argument Passing - java

I am currently working on a single activity Android app that uses a lot of shared UI objects (like Button, etc). At the moment, I have these UI objects declared as private non-static class variables. The alternative to this would be to continually pass the objects from method to method and modify them that way. It is currently unclear to me which option should be preferred, as it seems to me that using the maximum encapsulation form would cause me to do quite a bit of argument passing. Can anyone shed some light on this?

Generally I like to think of encapsulation as hiding data within a single class. If multiple methods are accessing that object within the class, that doesn't really violate encapsulation principles. Once you start leaking it outside the class, that's when encapsulation problems occur.
With that said, it is perfectly fine to have a private member which is a Button and multiple methods can access that button.

As above Jeff said You should go for passing arguments as you are inside one activity as you have mentioned in your question and encapsulation is always the first thing to be recommended.I will suggest to do one more thing if you can :
Define one function which will accept the color code or color type, and call this function from all the functions where you want to change the button text color.In this way code can be in one place which is performing the same operation i.e. changing the color.

It depends if those private non-static variables that you want to pass as arguments actually make sense to become the properties of the class.If you think it makes sense and have design control over their updation/modification you can go ahead and declare them as class members

Related

Java 2D game: Where to put "global" non-final variables

I am working on a Java 2D game for which I am using AWT graphics, a JFrame and a JPanel. I would like to know where I should store some non-final but globally accessible (I need to be able to read/change these variables from every other Object/Class) variables to coordinate e.g. the width and height of the game's panel, which I want to be able to change in a little settings menu within the game.
At the moment, I am storing these variables in a separate interface which most of my other classes implement, but this means I cannot change the variables as they are all final.
As I see it I have two options:
Put all these variables as static, non-final ones in my main game class and access them via Game.PanelWidth
OR
Create a separate class just for these variables and access them like this: Variables.PanelWidth, where "Variables" would be that new class' name.
Which method is better, or should I use a completely different approach?
Without going through your code, it's hard to provide a specific response.
General recommendations:
At the moment, I am storing these variables in a separate interface which most of my other classes implement, but this means I cannot change the variables as they are all final.
It's not a good idea to use inheritance to access your settings. For this reason alone I think either of the options you're considering is an improvement as it uses composition instead of inheritance.
You should consider applying the Single Responsibility Principle.
Who is responsible for managing your game's settings? Maybe a Properties object.
Who is responsible for constructing such an object? Maybe the main method.
If you apply this principle, hardly any of your classes should require access to the PanelWidth property.
Specific recommendations:
Java provides a Properties class. This class is both thread safe and easy to use when loading/storing properties to files.
From the Javadoc:
This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.
Rather than creating a static properties object, consider constructing the properties object in the main method (basically, poor-man's dependency injection)
The choice is largely up to you and should be driven by a balance between complexity and the actual needs of the application.
The interface you mentioned is a known anti-pattern Constant Interface - generally frowned upon because you litter the inheritance tree and namespace everywhere with information that should remain encapsulated. It does work though and in small projects it may be acceptable.
A separate class is a better approach, it solves at least the namespace litter. Make its constructor final to prevent accidental subclassing.
Generally, static members can work in small projects, but it can turn out to be impossible in case the project grows and it turns out that the variables aren't really application global, but only use-case global. Refactoring such a case can create a lot of work later.
Using an actual instance of the "global" settings class prevents this from the start, the cost is that you need to pass the instance around to where it needs to be accessed (e.g. as constructor parameter).
Next is threading and the issue of communicating changes to those global variables. Unless your application is running in a single thread (that would be the case in a purely event driven swing application), you cannot simply make changes to values and expect the change to take effect properly at every dependency site (imagine just having read panelWidth, but before you can read panelHeight new dimensions are set). You need a way to prevent these situations. So simple members are out. You'll want get/set methods that ensure only complete information is read and that writes of related values are atomic.
The atomicity can be ensured by encapsulating related values into a composite object, e.g.: Instead of panelWidth, panelHeight you have a panelDimension. No getters/setters for the individual values, are provided. You can only get the entire Dimension (for reads) or replace it with a new dimension (for writes). The actual member can be either volatile, of the AtomicReference variety or protected by making getter/setter synchronized.
To properly communicate changes to every dependency site, you may need some notification mechanism, so either the entire global state or individual parts of it may need the ability to register listeners and notify those listeners on changes (again threading issues are to be considered, since listener callbacks are usually implemented on the thread making the change, which may need consideration in the listener called).

What types of methods are most suitable to exist as "static" in MVC?

What are best practices in defining access controls for methods in MVC pattern. I'm uncertain where to use static methods in a scenario like an ATM (client-server model). I'm using Java.
Appreciate if someone can shed some light on this.
Here's my approach I used to come up with a class diagram.
First I designed all the screens, sketched on a paper. (I'm kinda
artist if you wonder and into graphic design stuff :) )
Then I created View classes Created Model classes by studying the scenario
and use of data
Created Controllers for each Model and some more additional ones
Added methods to Controllers by looking at the buttons I got in the screens, which I think a straight forward way to never miss any method? + some additional ones for GUI controlling
etc.
What do you think about my approach?
Thanks.
I don't see what MVC has to do with it. A static method cannot access instance variables. Therefore static should only be used for methods that receive ALL their necessary data via parameters. Usually this is "utility" routines such as sort routines, formatters, common calculations, etc.
The other place where you might use static routines is to access static variables in a class. But it's rare that you want to do this without also accessing instance variables.
Note that there's no real requirement to make any routine static -- you can have an instance method that doesn't reference any instance variables. But a static method becomes accessible from situations where you don't have an instance handy to invoke the method.

OOD and Passing Activity as a Parameter to Constructors of other classes

So far, to accomplish certain functional goals, I have been getting away with handing out my app's main activity object as a parameter to the constructors of other classes, which then store it as a private variable.
I do this, not because I need access to the entire activity, but rather because I need access to:
Members (either data or
methods) of the activity
Data members which aren't initialized yet
at the time those constructors were
called.
It works, but I have the constant feeling that I am doing something fundamentally wrong in terms of proper OOD.
Especially in regard to point #1:
The members that are so "private" to
Activity become, in essence, a pool
of global variables mess.
In addition, those other classes
that were created for the purpose of
modularity, are now dependent on
knowledge of the activity class,
which makes them not really
re-usable outside this app...
For these reasons, I try to avoid passing an activity as a parameter to constructors as much as possible, but in the Android development environment I find it more difficult to do, for reasons I don't fully understand yet.
My questions:
Are there recommended "rules of
thumb" that can help avoid this
trap of taking "a shortcut" by
passing an activity as a parameter?
Are there cases in which passing an
activity as a parameter is
conceptually justified?
Generally speaking, you should avoid keeping references to the activities. If you really need, store a WeakReference to your activity. This is to avoid memory leaks.
As you said, by passing a reference to an activity, you introduce a dependency between the other object and your activity class. Give some sample code so that we could give an example of how to refactor it.
I have found it best to keep values that multiple classes will require in a separate Util class. That way, you do not have to pass the main Activity around to other classes.
An alternative to this is to pass the required values that the main Activity has as parameters to the other classes as needed.
To your 2nd question, I cannot think of any reason that you would have to pass your main activity and then call methods on it.

Java class containing only private members

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.

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