Should I make a class static? [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I've got the following class:
class A
{
private String state;
A() { state = staticGetterCall(); } // staticGetterCall is fast
bool shouldUseState() { return state != null; }
bool getState() { return state; }
}
And then I use that class A in the following way in some other constructor:
B(...) {
...
A a = new A();
if (a.shouldUseState())
{
staticFunction2Call(a.getState());
}
}
That's the only place I use A, so I think it's a good idea to refactor this and make these 2 method static (and inline that String state):
class A
{
bool shouldUseState() { return staticGetterCall != null; }
bool getState() { return staticGetterCall; }
}
So its usage transforms to:
B(...) {
...
if (A.shouldUseState())
{
staticFunction2Call(A.getState());
}
}
Does it make sense?

Should I make a class static?
To answer your question, you need to know the good and bad points of this usage.
According to Joshua Bloch, Effective Java 2Edition, Item 1, let me list his point of view of advantages and disadvantages of static usage over constructors. So you can decide for your program effectively.
Advantages:
1. One advantage of static factory methods is that, unlike constructors, they have names.
2. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
4. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.
Disadvantages
1. The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
2. A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.
In short, static factory methods and public constructors both have their uses, and it pays to understand their relative merits.
Often static factories are preferable, so avoid the reflex to provide public constructors without first considering static factories.

That's the only place I use A, so I think it's a good idea to refactor
this and make these 2 method static (and inline that String state):
It is not a reason to make an instance method static.
static members (methods or fields) are not specific to an instance of the class but are associated to the class itself.
If you define these methods as static, you will have to do some other changes : the state field should also be static and the constructor would also have no sense any longer as static method doesn't access to instance members.
So is it make really sense to make the whole class state and behavior as static ?
If the state depends on the A instance created, keep them as instance members.
And besides in a general way as you have a state in a class, make all static seems to be counter intuitive.
At last, static modifiers don't ease the switches to other implementations (and consequently also mocking in unit test). So, you should also consider this point before to make them static.

Following code makes sense to me
class A {
private static Boolean state;
A() {
state = staticGetterCall();
} // staticGetterCall is fast
private boolean staticGetterCall() {
return true;
}
static boolean shouldUseState() {
return state != null;
}
static boolean getState() {
return state;
}
}
class B {
B() {
A a = new A();
if (A.shouldUseState()) {
staticFunction2Call(a.getState());
}
}
private void staticFunction2Call(boolean state) {
}
}
There were few changes required in your code. These are trivial and I think you are aware of these.
1. Declare state field as static
2. Change datatype of state to Boolean. Right now it is declared as String.

Related

Habit of making private methods static to increase functional programming [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I got in touch with the functional programming paradigm (haskell, scala) and like the concept. I'm trying to incorporate these functional principles in my every day work.
Here an example
public class Functional
{
private final Object o1;
private final Object o2;
public Functional(Object o1, Object o2)
{
this.o1 = o1;
this.o2 = o2;
}
/*
* method has side effects
*/
private void method()
{
// o1.someChange();
// ...
// o2.someChange();
}
/*
* method has no side effects - it only uses its parameters
*/
private static void method(Object o1, Object o2)
{
// o1.someChange();
// ...
// o2.someChange();
}
public void work()
{
method(o1, o2);
}
public static void main(String[] args)
{
Functional f = new Functional(new Object(), new Object());
f.work();
}
}
I find the static method easier to maintain, also for people who did not write the code, since they just have to look at the method parameters - which can be an advantage in big classes. Another minor advantage is performance, because after compilation static methods get called with invokestatic which is slightly faster.
The public methods are still kept non static, since I don't want to discard OOP/encapsulation. I'm only talking about private static methods.
QUESTION
So what do you think of this apprach? Esp. what are the negativ sides my new habit of making all private methods static - within reason, as long as I don't need more than 3, 4 parameters?
IMHO You should use static methods when
there is no arguments (rare)
there is no way to extend the class of interest e.g. you want to add a method for a String.
you want to add a method to an interface (pre Java 8)
Otherwise a static method is much the same as an instance method where you are taking the first argument implicitly. i.e. you can simply transform one into the other.
Consider these recursive method calls.
class Type {
static ReturnType staticMethod(Type type, Object arg) {
return type.method(arg);
}
ReturnType method(Object arg) {
return staticMethod(this, arg);
}
}
IMHO you should use instance methods for clarity as much as possible, and leave static methods to the rare cases you have no alternative.
Note: you can use functional programming whether you use static method or not. The main principle to remember is a) always return what you create/change as a return value b) don't change any of the arguments, including this for instance methods.
This gives you the flexibility to break this a little to; only change this rather than one of the arguments (and only if you have to)

Singleton using Static Members and Methods? [duplicate]

This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 9 years ago.
We can replicate a Singleton behavior my making a Class with Static Methods and Member Elements. Other than serialization What's the harm of implementing a singleton using static Body only.
You can't use this pattern to implement a provider for some interface or to allow for subclassing or other alternate behavior. This means that testing becomes more difficult and you can't use dependency injection for anything your static class does.
A Singleton is a single instance of a class (i.e., one object). A block of static code is not an object. It's just code.
It seems there is a definite difference between this:
public class MyClass {
public static void doIt() {
System.out.println("doIt()");
}
}
And this:
public class MySingleton {
private static MySingleton _singleton = null;
private String cantTouchThis;
private MySingleton() {
cantTouchThis = "Hands off, static block!";
}
public static MySingleton newInstance() {
if (_singleton == null) {
_singleton = new MySingleton();
}
return _singleton;
}
}
In the first case, basically all you have is a block of code you can execute by calling MyClass.doIt(). In the second, by calling MySingleton.newInstance() you can get your hands on an honest-to-goodness object.
HTH
Akwardness or hoop-jumping to unit test such a "singleton" is one potential downside in addition to serialization.
Contrast this with unit testing a true (i.e. instantiable) singleton.
Ultimately, a singleton guarantees a single instance of a class, whereas a static class is not instantiable as #JStevenPerry points out (and I expect you already understand): the two are simply not the same although they can in many ways be employed similarly.

Is it good practice in Java for a class's method to redundantly return a modified global field of the class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Is it good practice in Java for a class's method to redundantly return a modified global field of that class?
Note: I edited the examples below to correct my code.
For example:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
String newString = addStringToVeryImportantString(" World!");
System.out.println(newString);
}
public String addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
return veryImportantString;
}
}
In the above example, addStringToVeryImportantString is returning veryImportantString, even though as a class field it has been modified and is globally available to the calling method.
In the below example, I do the same thing without returning the field:
public class MyClass {
private String veryImportantString;
public static void main(String [] args) {
MyClass myObject = new MyClass();
myObject.fieldQuestion();
}
public void fieldQuestion() {
veryImportantString = "Hello, StackOverflow";
addStringToVeryImportantString(" World!");
String newString = veryImportantString;
System.out.println(newString);
}
public void addStringToVeryImportantString(String inputStr) {
this.veryImportantString = veryImportantString + inputStr;
}
}
My question is: does it matter? Is there any difference in terms of coding standards, readability, efficiency, etc.? In a way, it makes sense to never return a global class field that a function has modified, because what is the point? The field is available anyway. On the other hand, maybe it makes sense to return the field in order to indicate that the primary purpose of the function is to modify that field and return the value.
Thanks for your input.
It is a usual coding standard for a method to either mutate an object (or variable) or get information about it but never both. Therefore a method that has a return will be assumed at first glance not to have any secondary effects (like changing veryImportantString). This is not a hard and fast rule and there are many reasons to break it but it should never be broken lightly.
Secondly the method signature in the second snippet (with a void return) could only reasonably do one thing; change veryImportantString. But with a return it could do two things; change veryImportantString and return it or return a seperate string based upon veryImportantString. As the void signature is less ambiguous it is preferable (unless theres a specific reason to do otherwise)
For your example, its not particularly important.
In general when you have a private piece of data and a public method. Your only way to get information out to the user of an instance of your class related to the private data is via returning something from a public method. Remember that most Java programs are much more complex and the need to return data related to a private field (java beans for instance) are much more common.

Use static method or not?

Hi i have a web service in java, in which i have a class that has different methods that modify the string that the client sends and return it back according to the type of sting he wants. So based on the string type requirement a method is called..
like
class Test{
public static String a(String z)
{
// do stuff and return;
}
public static String b(String z)
{
// do stuff and return;
}
}
so if an array of like 10000 requests comes, these methods are called 10000 times, i want to know that should these methods be taken as static or NOT(i should create a global object of this class in my main web service class and call these methods) ?
I don't think you need to make method as static, if you can access the method within the object then you should (avoid static as much as possible).This improve code performance (in terms of memory utilization).
What's the compelling reason that these methods be static? If you need static methods, then create those. Otherwise, from a design standpoint, stick to non-static methods. You can't override static methods (though you can hide 'em.)
And there's this:
In Java, is there any disadvantage to static methods on a class?
You can use a static method if the method behaves the same for all cases. If the methods just does some work on the string supplied as a parameter and the behavior is the same for all instances, you can.
Again, you can also make a singleton out of it & call the methods through the UNIQUE_INSTANCE.
Something like:
public class Test {
private static final Test UNIQUE_INSTANCE = new Test();
private Test() {
}
public static final Test getUniqueInstance() {
return UNIQUE_INSTANCE;
}
public final String a(String z) {
// do stuff and return;
}
public final String b(String z) {
// do stuff and return;
}
}
Then you can do >>
Test.getUniqueInstance().a("Hello");
Test.getUniqueInstance().b("World");
If there is not any resource which is shared among the threads then there is not harm to use any static method.
Yes, there should be a Static modifier since there is no interaction between the different methods or functions, and the result is returned in the very same method. the "Static" word is to define a class variable or method that can be accessed without instantiating an object of such class.
if you do not intend to instantiate the class, and just need to use the methods inside, "Static" is the correct way to go, and set the class constructor to private.

How to use "Static factory methods" instead of constructors?

Effective java says
"Consider providing static factory methods instead of constructors"
If you have a
class A {
public static A getInstance() {
return new A();
}
}
Does it make sense to provide this method for class A , rather than call new A() in the code.
See here for a nice exposition of the main reasons you might want to do this. In summary:
Named "constructors".
Can return null, if appropriate.
Can return an instance of a derived class, if appropriate.
Reduce verbosity when instantiating variables of generic types.
Another reason comes to mind that the article doesn't mention: Can implement interesting logic to avoid creating new objects all the time (caching based on parameters, recycling, etc.).
For your example above it doesn't make much sense to provide a static constructor. And normally when you provide a static constructor you should make the normal constructor private. Otherwise it is still possible to create an instance with the normal constructor.
I try to explain here with another example, when you could use static factory methods. One of the advantages is, that you can give the factory methods understandable names.
class Complex {
public static Complex fromCartesian(double real, double imag) {
return new Complex(real, imag);
}
public static Complex fromPolar(double modulus, double angle) {
return new Complex(modulus * cos(angle), modulus * sin(angle));
}
private Complex(double a, double b) {
//...
}
}
Complex c = Complex.fromPolar(1, pi)
Or another example would be the Singleton Pattern. There you wan't to provide only one instance. So this is the reason why you make the constructor private and create an own getInstance method where you make sure, that there is always just one instance available.
public class Singleton {
private volatile static Singleton singleton;
private Singleton() {
}
// synchronized keyword has been removed from here
public static Singleton getSingleton() {
if(singleton==null) {
synchronized(Singleton.class){
if(singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
Factory Method Pattern Wikipedia
The Singleton pattern with static method calls are a better design if ur looking for a single instance.. because of the reentrant locking nature of static.. providing thread safety and also avoiding out-of-order writes..

Categories