Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What's better to use in Java: a singleton or a class with all static members? Or does it not matter?
For example, I want to access an X class from different classes, but the X class has to contain similar values for all classes which use it.
There are some cases, where static classes makes sense than Singleton. You can see the example of java.lang.Math. This is not singleton -. its just providing us a bunch of static methods.
If your class is not maintaining any state, and just providing global access to some methods, then you should go with using static class, as static methods are faster than Singleton, because of static binding during compile time. Remember you cannot use polymorphism with static methods as static methods cannot be overridden.
If you want to maintain the state of the object, you have to go with the singleton instead of static methods.When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.
You can have a detailed description here
Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz2iNE3rW4i
For me: Singleton is an anti-pattern and should only be used if there is a strong reason, also a class only holing public static variables is not acceptable in my opinion, this sound not realy object orientated to me. You could use Dependency Injection, the benefits are testability and you can avoid the doublecheck on creating a singleton (if you don't use an enum).
this would look like:
public class SharedObject{
// content
}
public class Worker{
private final SharedObject sharedObject;
public Worker(SharedObject sharedObject){
this.sharedObject = sharedObject;
}
}
With this way you also see, where the objects come from, you can easyly mock the shared object using Mocktio. It forces you to structure your code for easy testing, meanwhile it will go in a more modular direction.
I prefer static methods for classes which are stateless, just like Math or System class, and singleton as vice versa->for statefull classes, like FacesContext.
An all-static class is often used for shared utility methods that are grouped logically together but do not share state (fields) between them.
A singleton is better if:
You might want different objects with different behaviors to play that role.
The object needs to implement an interface (e.g. a shared ActionListener)
(Another way of saying this: If you need polymorphism, your singleton must be an object and not a class)
It is preferable not-heritable and non-instantiable class with static methods. e.g.:
public final class Constants {
private Constants() {
// non-public constructor
}
public static final Pattern ID_PATTERN = Pattern.compile("^\\d{4,10}$");
public static final Locale DEFAULT_LOCALE = new Locale("en", "US");
...
}
Use singleton only if you want to maintain some state, similar to the application scope. However, must be two classes if you want a clean design.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have developed a Java Program which contains certain static variables that are used in all the classes.
Now, I want to store those variables at a single platform, which I can refer to call from any class rather than declaring them again & again.
I have researched on the internet and found some good solutions like declaring them in an interface and implementing that interface in my classes.
Also, I can write a separate class and call those variables using the object of that class.
Can anyone suggest the better solution? or which one is better between these two? please explain :)
It kind of depends on what you mean by "variables" if you mean global mutable state, you should probably either use a Singleton pattern, or even better, redesign your application in such a way as to eliminate global mutable state. (Encapsulation)
If all your static variables are final, or effectively final (for instance loaded from environment variables at run time), then wrapping them in a class (with a private Constructor, since you do not want to be able to create objects of the class that only has static members) is probably the best solution.
Interfaces are designed to describe behavior, rather than state, so unless you have a contract described in it, it doesn't seem useful to have it as an interface, and could potentially lead to confusion down the road.
1:- Create an enum class like this,
public enum YourClassName{
// these are your three varible
VARIABLE1("val1"), VARIABLE2("val2"), VARIABLE3("val3"),;
private String value;
YourClassName(String value) {
this.value=value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
2:- Once you have an enum class with some variable then you can call from every class like this,
YourClassName.VARBIABLE1.getValue();
this will help you and i think its a good way.
Well to further work on #sleepToken answer there can be multiple ways to what you are looking to do. Again these approaches may depend on the design and at times may totally be different than what is being followed in the code base that you are working on.
For instance in most cases I have seen a convention that constants are defined in an Interface in java and that interface is hardly ever implemented. You can have multiple of these interfaces as well. Like one interface for storing constants related to user and may be another for the constants related to the system
IUserConstants.java
ISystemConstants.java
Now this is totally up to you to decide the names and what these interfaces will hold. Since these are constants you will define in them they are supposed to be public and static and at times you will make them final as well but make sure that you know the difference between runtime and compile time constants. Again this is something you will have to decide about.
Further more public static final are redundant for interfaces. This link just got my attention.
You can check this sample interface
public interface IConstants{
public static final int TIME=10;
public static final String CONFIG_STRING=SomeClass.LoadValue();
}
Another approach I have seen is to use an abstract class that contains all the constants which are static and public and if you want to make sure that it is not further used for implementation you can use a private constructor although I am not sure why this was used because at times legacy code that comes in front hardly makes sense.
public abstract class IConstants
{
public static final int TIME = 10;
public static final String CONFIG_STRING = SomeClass.LoadValue();constant
private IConstants()
{
throw new AssertionError();
}
}
I hope this helps you
You can refer to static variables from any class... (assuming they are not private): just do ClassName.variable.
The better option is to not use static variables as global variables. Use getters and setters to pass values.
The interfaces solution is hacky and I have used it before - but that is also not ideal. Implementing a constants interface is considered bad practice.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am on a new project, and the legacy java code is filled with classes that are using a mix of private static methods, and public static methods.
It's very hard to follow.
For example:
public Car {
private static checkGas(){
..
}
public static startCar(){
checkGas();
}
}
Is there some design pattern I never heard of that would make this applicable?
I've always used public static methods on "helper" classes that do not need Util.caculate(..), and in the above "Car" example I wouldn't have use any private static or public static methods... just private and public methods.
You generally want to limit access as tightly as possible, so if you have a utility class with some public static methods and some static helper methods that they call, those helper methods should be private.
This is not fundamentally different than writing non-static private helper methods to support non-static public methods.
I wouldn't call this a design pattern, so much as a good general practice.
Don't make things public unless you have to. Once a method is public, you can't modify its signature without breaking everything that uses it.
Edit
Regarding the best place to put static methods, I'd rather put them on the class they're designed to help, rather than aggregate random static methods in a "Util" class.
A good example of this would be the Integer class, which can be instantiated to represent a numerical value, but also has many static helper methods like compare, max, parseInt, etc.
Utility classes should be for things that are truly generic, such as the Math class.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am currently maintaining the application state using a class as below. It has only static variables and static methods
public class MyAppSession{
private MyAppSession(){ // private constructor}
private static UserProfile userProfile;
private static Enum appsessionMode;
private static List<UserProfile> guests ;
private static String host ;
public static UserProfile getUserProfile() {
return userProfile;
}
public static void setUserProfile(UserProfile userProfile) {
MyAppSession.userProfile = userProfile;
}
public static Enum getAppsessionMode() {
return appsessionMode;
}
public static void setAppsessionMode(Enum appsessionMode) {
MyAppSession.appsessionMode = appsessionMode;
}
...... other getters and setters
I am maintaining the session of my application using these static methods and variables. In my application i am using this class in numerous classes to identify the state of my application and handle business logic. I will also be updating the session based on the users actions.
During my code review meeting i was asked to remove static, make it a singleton, and get the instance of this object in all dependent classes.
Now on the evil side of static, i know its difficult to mock these. and different memory allocation for static variables which are not freed.
I want to understand what is the best way to handle such scenarios? is really static overkill for above scenario?
Although it is open for a discussion, and depends on each one's own taste, I would say that the way to go is with a Dependency Container. It makes testing a lot easier, and is considered as a best practice. Dependency Container follows great principles of good programming, and is an implementation of Inversion of Control (IoC), in which the control of the dependencies is inverted from one being called to one calling.
Singleton is considered as an anti pattern, for some regards. It actually pollutes the global scope. I once had the same conflict with using the language built-in static identifier, and have heard something that has changed my mind - do NOT use it. You can do everything without static identifier, and do it better. Only when you have full grasp of it - you may use it, sparsely.
One caveat: you maybe not use Dependency Container if you plan on a simple project. You can use Singleton, Registry, Multiton or even static. But those can become a serious drawback on large systems, as they are anti-patterns. By the way, your static implementation is actually an example of some kind of a Singleton.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
With the time ...lots of utility method are introduced in java project for more complex and simple task.
When using static methods we introduce tight coupling in our code and it make our code more difficult to test, especially if the utility methods are quite complex.
I am just thinking that it now difficult to manage and test these utilities. please guide me in avoiding these utilities methods and how can i organize existing project to remove all STATIC utilities.
Can you help me avoiding static method ?
There is nothing wrong with having lots of static methods.
Static methods are (or should be, read on) stateless, which makes them the easiest methods to test - there's no setup, just call them.
You don't need mocking, because there is no state to deal with.
Regarding being stateless, technically static methods can be stateful if they use static variables to store state. If this is the case, from a good-design perspective they should be converted to instance methods using instance variables to store state, employing the singleton pattern if required.
To contradict the other answers currently available: Static methods are bad!
They do introduce strong coupling. Yes there are cases where it is acceptable. Yes you can make a seam for inside a static method, by making the strategy used inside exchangeable. But as a rule of thumb static are still bad.
To answer the question, how to get rid of static methods. Simple: put them on a proper Object. All statics are gone. Have we improved our code? not much yet. If we replace
callToStaticMethod()
with
new X().callToNoLongerStaticMethod()
we replaced a static call with a constructor call which is essentially just another static method. But now your X is just another dependency, so you can inject it:
class A{
private final X x;
A(X aX){
x = aX;
}
}
Note: there is no need to use Spring or any other framework for this. If you feel like it provide a constructor which uses the default implementation. If you are a purist, introduce an interface for X.
Testing A without relying on the implementation of X becomes trivial and obvious. Same for replacing X in any way.
Static utility methods are not so bad. You can hide a package-private strategy behind the static call. This can be easily tested (and replaced) given that the test case belongs to the same package. Moreover, it makes the code very readable. Of course, the clients of the static utility method can still only use one implementation in their tests. So here is some inflexibility.
Bohemian is right when talking about state. If your static utilities have state you are doing something wrong.
About your question: If you want to avoid static methods you can use the spring framework and define different implementations of utilities that you use and test in different contexts. In this case, however, access to these objects is not so convenient as you must first obtain a reference to the context that knows your utility object.
Nothing wrong with a set of static utility methods that belong together in a class. See for example java.util.Collections. If every method in that class that operates on a List would be specified in the List interface itself, they would have to be implemented by all subclasses. As long as they can be implemented by the public List methods, there is no problem.
Of course, as soon as you start adding methods to the interface (or in case of a class, making methods public) only to be able to put functionality in static methods instead of the class itself, then you're on the wrong path.
This question already has answers here:
Should private helper methods be static if they can be static
(20 answers)
Closed 9 years ago.
What do you think about using private static methods?
Personally, I prefer using a static private method to non-static as long as it does not require access to any instance fields.
But I heard that this practice violates OOP principles.
Edit: I am wondering from style prospective of view, not performance.
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state?
(*) = In principle, due to the class level visibility in Java, a static method on a class has access to instance fields of an object of that class, for example:
class Test
{
int field = 123;
private static void accessInstance(Test test)
{
System.out.println(test.field);
}
}
You need to pass in the reference to an instance (this pointer) yourself of course, but then you are essentially mimicking instance methods. Just mentioning this for completeness.
As mentioned above, private static methods are often useful for organizing re-used logic and reducing/eliminating repeated code. I'm surprised that I haven't noticed any mention of performance in this discussion. From Renaud Waldura's 'The Final Word on Final':
(Note, private static methods are implicitly final)
"Since a final method is only implemented in the declaring class, there is no need to dynamically dispatch a call to a final method, and static invocation can be used instead. The compiler can emit a direct call to the method, bypassing entirely the usual virtual method invocation procedure. Because of this, final methods are also candidates for inlining by a Just-In-Time compiler or a similar optimization tool. (Remember, private/static methods are already final, therefore always considered for this optimization.)"
Check out the whole paper: http://renaud.waldura.com/doc/java/final-keyword.shtml
private or public doesn't make a difference - static methods are OK, but if you find you're using them all the time (and of course instance methods that don't access any instance fields are basically static methods for this purpose), then you probably need to rethink the design. It's not always possible, but most of the time methods should reside with the data they operate on - that's the basic idea of OOP.
I don't necessarily see any real problem with what you are doing, but my first question would be if the method doesn't require access to any instance fields, then what is it doing in that class in the first place?
It's a matter of taste, but I make methods that don't react to a state within the object static. This way I don't have to rewrite code if a static function needs similar functionality. A sorting function would be a good example of such a case.
I tend not to use private static methods. I do use public static methods and group them into Util classes to promote reuse.
Private static methods can for example operate on private static members of their class. This can be utilized to encapsulate and unify certain class specific operations.
The major drawback of using static methods is in my opinion the fact that one throws away the possibility to override. Since classes in Java are not like, let's say, classes in Smalltalk, you can not override static methods.
Since your question relates to private static methods, overriding is out of option anyway.
I tend to use static methods only in case of utility classes (like java.lang.Math) or patterns like the Singleton pattern. All of these require a higher visibility than private, because they represent services provided by their class to others.
Final thought: If you have one or more private static methods, think about extracting them to a dedicated utility class and making them public. Even better, make them instance methods and use the Singleton pattern.