create 1 static object or a class with static methods - java

I have a GUI class and the Logic class,
which is the better choice:
make the logic class methods static and access them LogicClass.method() from the gui class.
make the logic class regular and make 1 static object from this logic class
private static LogicClass logic;
make it non-static which is a little of a problem because i want to access some methods from the Main function in the GuiClass so it has to be static(i can access them through the constructor but I don't know if that's ok, something like connecting the server).

Static things are best avoided, because sooner or later, you'll want to separate different things, or have more than one instance of something, and then you'll be faced with a horrible refactoring.
It's like salt and water. It's easy to mix the two, but much more difficult to take them apart.
I would suggest you make all your stuff non-static. Just use the "new" and you'll be good to go. You might have to pass around some additional parameters, or introduce some additional fields, but it'll make your code much better in the long run. Only when you know in advance that you'll never have more than one instance of a class, go for "singleton" pattern (it can be achieved by combination of static field + private constructor).

Related

Unique methods for use through the class rather than an object

So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the static keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. MyClass.main()) rather than solely through the object (MyObject.main()). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that MyClass.main() would work, however MyObject.main() would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.
In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!
Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.
Thanks!
Any static method or member belongs to the class, whereas non-static members belong to the object.
Calling a static method (or using a static member) by doing myObject.method() is actually exactly the same as MyClass.method() and any proper IDE will give a suggestion to change it to the second one, since that one is actually what you are doing regardless of which of the two you use.
Now to answer the actual question:
is it possible to make certain methods only accessible through the class and not through the object
No, not as far as i know, but like I said, any proper IDE will give a warning, since it makes little sense and it gives other readers of the code an instant hint that you're dealing with static members.
Yes, short answer is no.
But you can put your static members in a dedicated class, so that no instances share any one of them.
MyObject is instance of MyClass, and you aggregate all you static parts in MyStaticThing.
Using static member on an instance can be misleading, so it is a bad practice
http://grepcode.com/file/repo1.maven.org/maven2/org.sonarsource.java/java-checks/3.4/org/sonar/l10n/java/rules/squid/S2209.html
While it is possible to access static members
from a class instance, it's bad form, and considered by most to be
misleading because it implies to the readers of your code thatthere's
an instance of the member per class instance.
Another thing, do not use static things, because you cannot do abstraction and replace implementations to extend your code.
Being able to switch between implementations is useful for maintenance and tests.
In Java, you can crete an object with these keywords.(new keyword, newInstance() method, clone() method, factory method and deserialization) And when you create an object,it can also use classes abilities which is like static methods.
Short answer:No.
Is it possible to make certain methods only accessible through the class and not through the object?
Yes, it is. You achieve this by preventing any instances of the class to ever be created, by making the class non-instantiable: declare its constructor private.
public final class NonInstantiable {
private NonInstantiable() {
throw new RuntimeException(
"This class shouldn't be instantiated -- not even through reflection!");
}
/* static methods here... */
}
Now, it only makes sense to declare any methods of the class static -- and they can only be called through the class name. Such a class is often called a utility class.

Java: instance really better than static?

So I have a few classes like MainWindow, MenuPanel, GamePanel, GameEngine, Player and so on...
My question is, although I've read much about static vs instance, which should be more recommended to use, according one of my lines looks like this:
MainWindow.getGamePanel().getPlayer1().getName().toLowerCase().compareTo(...);
or MainWindow.getGamePanel().getLabels()[0].getIcon();
Do you think this is a good practice trying so hard not to use statics where every object has different properties and things are not generalized, instead of maybe declaring the labels or the players and namesstatic and having a much more easy to reuse and read code?
The idea is I used these long codes because surely it would be awkward to create a GamePanel(visual class) object in the Player(more like a logical) class for example. So I just created like one object of every class in MainWindow (not the main class, just the JFrame class) and created static getters for every one of them.
MainWindow.getGamePanel().getPlayer1().getName().toLowerCase().compareTo(...);
This is a classic violation of the Law of Demeter, sometimes expressed as "ask, don't look." The class calling these getters has too much knowledge of the overall structure of the program, which makes it brittle. If the relationship between any of these classes changes, all the code that relies on these chained getters will break.
The idea behind "ask, don't look" is that the class calling these getters to get the player name should instead require the player name as a constructor parameter. If that leads to a constructor with a huge number of parameters, the class is probably violating the Single Responsibility Principle.

If a class has no state, should all the methods be static?

Lets say I have a Helper class like with a few methods
public class SomeClassesHelperClass(){
public List removeDuplicatesFromTheGivenList(List someList){
// code here
}
public int returnNumberOfObjectsThatHaveSomeSpecialState(List someList){
// code here
}
}
What are the advantages / disadvantages of making the methods in this class static? Which is the better practice?
If your class provides only utility methods (like yours), I believe it's better to:
make the class final (there's no point to extend it)
define а private constructor to avoid any attempt to create an instance of the class
make all the methods static.
If you decide to make all the methods static then you need to be aware of the impact that that will have on your ability to test other classes that depend up on it.
It severely limits your options for mocking ( or at least makes it more painful )
I don't think there is a right answer to our question - it depends on what the methods do. For example, it's easy to envisage a stateless data access object - if you make all its methods static then you are building a dependency on the data source in to your test cycle, or making your mocking code much uglier
Make them static when they use no state from an object. Most of it are helper classes like Math. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

Is it good practice to create an inner class for simple functionality?

There are some different opinions about simple inner classes, so I was wondering if there is a general consensus on what is good, and when to use private inner classes.
Here's an example that I found, and for which I think it's unnecessary to create an inner class. How good/bad practice is this?
private static class InternalCounter {
int count;
public InternalTabManager() {
count = 0;
}
public int increment() {
return count++;
}
}
Mind you that in this particular case, one instance is kept in the surrounding class to keep track of a count.
Yeah, in this case it does seem very unnecessary but if you have a case where there is some significant functionality and you know that no other class will ever need your inner class and it makes no sense to create a class more globally available then do use an inner class.
It depends on the context. If this class could've been replaced with only a single static int, then I see no need to create an inner class.
On the other hand, this code would allow the parent class objects to share a reference to mutable int (using java.lang.Integer wouldn't be possible because is immutable).
The general advice/practice/pattern in this case are Keep It Simple and You Ain't Gonna Need it - if you don't need particular behaviour, don't make your code more complex than absolutely necessary.
So, if the question is: "Is it good practice to create an inner class for simple functionality, when it could have been solved in a simpler way" then the answer is NO.
When encountered with such situations, we normally ask the developers to question themselves -
How stateful is this object going to be? Is this functionality coupled with the containing class?
Can this be a stand alone object? (purpose and reason for the existence)
Most importantly, is it cleaner?
Listeners, Presenters (UI model) are functional aspects; and deserve separate existence and are rarely modeled as static inner classes
Auditing entries, initialization constructs are non-functional/code-organization aspects; and don't give a definite answer, and IMO it is ok to use static inner classes
A definitive example for using such, would be a state transition model for a small application.
I've also used inner classes in this way but nowaday I tend more to make those classes package-private.
You get all the benefits of the inner class, while those two classes are much better to maintain (being in two separate files).
Yes, it is still possible that a class in the same package uses the class accidentally but it is VERY unlikely to happen.
When you want to inherit(extends) more than one class in one java class you can use inner class concept.here you can extend one class by outer class and another by inner class.
My rule of thumb is to use static inner classes if within a single class you have refactored to a handful of private methods that each take a similar (or the same) parameters each time. In this case I like to group those parameters together into a single inner class such that I have a type that succicently describes why those parameters are grouped together.

private sub classes... is this a bad thing?

So I consider myself a junior java/android developer
I've always come across these but never really liked them and concidered them as dirty code
class herp{
private class derp extends OnclickListener{
...
}
private class gerp AsyncTask{
...
}
}
so should I try to avoid these? or even make sure I never use these?
What is and isn't dirty code is highly subjective.
What can be said is that nested classes can be very useful. Often times they don't need to be nested like that, as they could just as easily be anonymous classes in all likelihood.
The idea is that: you want as few other classes as necessary to access your little class there. You wouldn't want to make your own package, because you really belong in the package you're already in. Instead, you make a private class. Now only you can use it, which is good because it's tailored just for your class.
Now, how many derp instances will you have? Chances are you'd have one. So instead of doing that, I would do this:
OnClickListener derp = new OnClickListener() {
// fill in methods to override here
}
It does basically the same thing, but I can't reuse the class for anything, which is good - no one should be reusing the one-shot class!
What is and isn't clean code is often times personal preference based upon experience. Nesting classes isn't messes per say, however you should be certain that it is an appropriate situation.
If you desperately need some specific functionality for a class which extends something like the OnClickListener in your question, then it is a question of how many times do you need this class? If the answer is once, then an anonymous class would be a cleaner solution. If the answer is in every single method in the class, then a nested class clearly makes more sense.
More or less every feature in Java has a time and place in which it is considered appropriate. Private nested classes such as the ones you have in your question should be reserved in my mind for cases where you satisfy two conditions:
a) you absolutely have to have a separate class that will only be used in this class and no where else
AND
b) you will need to use that class in multiple locations within the class.
At the end of the day, nested private classes are not inherently dirty or hard to maintain, but as with any other feature of an programming language, make sure you need them.
There is no fixed answer on this question. It mainly comes down to your own coding style, preferences, and your team's coding conventions.
Private inner classes are useful for many reasons. You can use them to provide an implementation of an interface (e.g. a List implementation might define its own Iterator implementation as a private inner class) without making the concrete class visible. It protects the implementation, and allows you to provide just enough details to a user of your API/class so he can use it correctly, without cluttering your documentation with useless details (your concrete class).
You can also use private inner classes as a implementation for listeners, even though some might disagree with this philosophy. I do prefer using private inner classes to anonymous classes when the listener has some complex logic.
You might want to use them also to separate code logic into separate classes, but don't wish to expose those classes outsite your outer class.
Keep in mind that every solution using a private inner class can also be implemented without using them. And as with many things in life, using private inner classes isn't a bad practice per se, but abuse is a bad practice.
It's fine. You may consider making them static inner classes, otherwise you'll need an instance of herp to create one (although that might be what you want):
class herp {
private static class derp extends OnclickListener{
...
}
private static class gerp AsyncTask{
...
}
}
The difference demonstrated is:
public static void main(String[] args) {
// With static:
new derp();
// Without static:
new herp().new derp();
}

Categories