What are the best practices for single-instanced classes in java? - java

In my program I have a menu system in which I have a separate class for each menu, for example MainMenu would be a separate class. But the class is only supposed to be instanced once, and after I instance it, it is saved in a list which is all is used for after that. Should I use another solution than a separate class? Or should I make the constructor private and then make a private instance inside the class? I feel like this violates OOP, but I don't see another solution.

Don't make the constructor private, this makes problems when you later want to unit test it.
Just instantiate it once. There are no software terrorist which secretly instantiate your class multiple times.
And avoid Singeltons, you nearly cannot reset the instance later when trying to unit test that.

Related

Does this violate the Single Responsibility Principle?

I am trying to write code to make a simple game.
Assuming that there is a class called Level in which it manages the functionalities for the level.
For example, there are some methods like spawnHero() and spawnEnemies(), start(), finish() and etc in the class.
if I put a private String method called PrettyTimeFormat that converts the game duration time into a nicely arranged format and uses it in the finish() method, would this violate the SRP?
If so, should I make a class called TimeManager and put the PrettyTimeformat method in that class in order to avoid SRP?
It looks like you are missing a Game object. Game has Level, Hero, Enemies, and GameTime. Game can be start()-ed and finish()-ed.
When you architect the solution think about real objects. Objects exist in real life, are living things that do real things and don't create objects that end with -er.

Java - Static Programming Style

When I first started learning java GUI (swing) programming the way I was shown was more of an MVC model which involved using interfaces to call things and pass variables across classes.
I recently started programming in a more static way, having a Jframe call its static Jpanel's and using static methods to change components. Bascially i program everything statically so I can call them from the different classes with ease.
Heres an example:
My main JFrame class called "Home", I initialise the Toolbar class statically:
private static Toolbar toolbar = new Toolbar();
Now whenever I want to do something e.g. change the colour I just call from another class:
Home.toolbar.setForeground(Color.green);
Is this an ok way of programming? So far i've not run into any troubles but I was caught out by the fact that the people I learnt from didn't do this when it seems so much easier to do.
Are there any big down sides to this way of programming?
What are the alternatives?
Basically, you should ask yourself:
"Should toolbar be associated with each object I create? Or should it be one for all objects, and once I change it, it changes for all objects?"
If you answer yourself "Yes", then it's OK, otherwise it shouldn't be static.
Of course there are many things to consider beside that.. For example, static resources are not thread-safe.
If it works, then great... It's correct.
However, I make it my goal to write code that's both maintainable and testable. The problem with static instances is that it creates strong coupling throughout the entire project. Moreover, trying to isolate a class is impossible because the static dependency cannot be mocked or injected.
Typically, GUI code cannot be unit tested. MVC, however, ensures that the testable code is separated from the GUI code.

Android Java App: Extending two classes (walk around)

I have two classes, ImageMap, extending ImageView and PageView extending GLSurfaceView, I am using the ImageMap to mainly have hot spots on drawables but I also need to add a page flip/curl animation to it, in order to do that I need those two classes to act as one object, any idea how to do that?
It is totally clear to me that multiple inheritance is not allowed in java.
There is no way of really extend two classes. What you can do is:
You make a wrapper object, that holds one instance of each object. and simply do this.ImageMap.filed1 and so. This is more convenient while developing the class. This also allows you to proxy method invocations.
You define interfaces which should be implemented, and you make a new class which implements both. This is only for class that use this class to have the interface, without really caring about the implementation.
You may need both things, since the first is about "how to do it" and the second about "how it will be presented to objects that use it".
Your question is not about Android; it's about Java.
Java does not allow for multiple inheritance.
Your reasoning is inaccurate regarding the following:
in order to do that I need those two classes to act as one object
That's not the case. An 'Activity', for example, does not have to be an event handler; it's enough if your 'Activity' can have an event handler, e.g. as an inner class which can access the Activity's variables.

Private Class Variables vs Excessive Argument Passing

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

How to go about display multiple "Menu" classes in java

Hi all I am relatively new to OOD and Java hence am not sure how to do this properly.
Currently I need to create an application (console/command prompt based) that involves going through a series of so called "menus" where the application will display your choices and you enter 1/2/3/4 etc. My professor told me to break up my boundary class (the class where all the display of choices is in) because it's too long (400+ lines).
Now comes the problem. If i were to break it up, I would have to keep creating new object classes to call on the different menu in different classes. For example:
Let say I have MainMenu, FoodMenu, DrinkMenu. So my main method will create a MainMenu object to call displayMenu(). From there, if I want to navigate to the food menu, I have to create another FoodMenu object and call displayMenu() under it again. Further along the codes, if i want to navigate back to the main menu, I would then again have to create the MainMenu object again and call displayMenu.
The above method would have so many variables waiting to be garbage collected and a total waste of memory. Is there another solution around this? Thank you very much in advance.
Hamlyn
Make all your menus either extend an abstract class (okay) or implement an interface (better), if you're not already doing that.
As for how to get to the menus, you can just store one of each type of menu in a menu array or some other collection (for example, a Map if you want to be able to look them up using a string or other object). Have that collection be globally accessible (static in some public class) and then you can display the same instance of a menu each time you need it.
First of all, garbage collection problems happen when you have thousands of objects floating around, not... three. So don't even worry about that.
But in general, your thesis that you need to recreate all those objects is flawed. You only need one of each, and they simply need to be able to get access to references to one another. For example, each "displayMenu" method might take a Menu as an argument; that displayMenu() method would set things up so that the "return to previous menu" option invokes the Menu that was passed as an argument.
As discussed in How to Use Actions, the Action class is a convenient way "to separate functionality and state from a component." This example creates a menu of recent files using instances of the RecentFile class. A similar class for each of your MainMenu, FoodMenu, DrinkMenu might be a way to encapsulate related menu items.

Categories