I know what static is, but just not sure when to use it.
static variable:
I only used it for constant fields. Sometimes there are tens of constants in a class, so using static constants can save lots of memory. Is there any other typical use cases?
static method:
I use it when I make a class about algorithms. For example, a class which provides different sorting algorithms. Is it against OOP design? I think it is better to maintain this way rather than implementing sorting algorithms inside each class that needs to use them. Am I wrong? What are some good use cases?
Also, are there any performance difference between using static and non-static fields/methods?
You are describing cases where you've used static, but this doesn't quite explain fundamentally why you would use static vs non-static - they are more than just keywords for constants and utility methods.
When something is not static (instance), it means that there is an instance of it for each instance of the class. Each one can change independently.
When something is static, it means there is only one copy of it for all instances of the class, so changing it from any location affects all others.
Static variables/methods typically use less memory because there is only one copy of them, regardless of how many instances of the class you have. Statics, when used appropriately, are perfectly fine in object oriented design.
If you have a method/variable that you only need one instance of (e.g. a constant or a utility method), then just make it static. Understand though that making a method static means it cannot be overridden. So if you have a method you want to override in a subclass, then don't make it static.
The general rule of thumb is - if you need only one copy of it, make it static. If you need a copy per instance, then make it non static.
Is there any other typical use cases?
Global Variables
Is it against OOP design?
Not exaclty, the point is that static methods are stateless since you don't need a particular instance of a class. My favorite approach is for utility methods (like Apache Commons). But you may be aware that some methods may be better placed as class members instead of static.
Also static methods can make class testability harder once you can't override these methods or replace by mock implementation.
Performance difference ?
There's a performance Android recommendation from Google that says "prefer static over virtual":
http://developer.android.com/training/articles/perf-tips.html#PreferStatic
I'm not sure it's true for JVM since Android uses a different VM, but it makes sense given the reasons the link points out:
If you don't need to access an object's fields, make your method static. Invocations will be about 15%-20% faster. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state."
My personal rule of thumb is that static things are "just hanging out there". They are things that (disclaimer, not entirely true) are global, but make sense to include with this one particular class.
Static fields are good if you find yourself loading some heavyweight objects repeatedly. For instance, the project I'm working on now has a toggle between two images. These are static fields that are loaded with the application and kept in memory, rather than reloading them every time and letting GC take care of the mess.
Apart from very specific situations, I use static (and final) variables for constants only. It's a totally valid to use them, of course.
I tend to avoid static utility methods, because they make it harder to write unit tests for the code (mocking the results of the method invocation). When you start developing Test Driven way, this issue becomes quite apparent. I prefer using dependency injection and singleton beans (though it depends on your needs and situation).
Static variables belong to a class, hence shared by all the objects, so memory usage is less if you really want the varible to be shared. If you declare the variable as public and static, then it is globally available for everyone.
Static methods are generally the utility methods, depending on the access modifier, those can be used within a class or across the classes. Static utility class will help to reduce the memory usage again because you need not to create the object to call those methods.
The static field has one value among all objects and they call it Class member also because it's related to the class.
You can use static filed as a utility.
an example just Assume we need to know how many instances we have :
class Counter
public class Counter {
public static int instanceCount ;
public Counter()
{
instanceCount++;
}
public int getInstanceCount()
{
return instanceCount;
}
}
After creating two instances of Counter Class. But they share the same instanceCount field because it's a static field so the value of instanceCount will become the same in firstCounter and secondCounter .
Class main
Counter firstCounter = new Counter();
// will print 1
System.out.println(co.getInstanceCount());
// will print 2
Counter secondCounter = new Counter();
System.out.println(co1.getInstanceCount());
Related
I am not very familiar with java. I created a jersey web server. There is different functions such as startRodio(), stopRadio(), setRadioIp()... I created one RequestHandler class to handle the http requests and one other Radio class that implement them. All the properties and methods of the Radio class are static. it looks like
Radio
class Radio{
public static boolean radionOn;
public static String radioIpadress;
public static boolean startRadio(){
radioOn = true;
// some other operation
}
...
RequestHandler
classe RequestHandler {
#path(/startRodio)
.....
if (!Rodio.radioOn)
Radio.startRadio();
Is it a good architecture for my programm? is it a good practice to make all the properties and method static in this way?
I would say, that making properties static in default as you have made above is not good practice at all.
If you have only one instance of such object as Radio is, then use singleton pattern and private properties with proper getters and setters. This is generally best approach, because you separate public interface from private implementation and change in the implementation (e.g. renaming variable) would cause problems in other parts of application and need of refactoring.
Static variables should serve just for some common properties for defined type/class. You can for example count existing instances of class in static variable.
Better avoid using static variables. This is not a good practice. Static variables have global scopes which leaves you testing so hard. Also anything can be able to modify the static variables. more over, using static is not thread safety. Also you don't have control over the static variable i terms of their creation and destruction. SO its not advisable to use statics.
Just don't use static variables. It directly couples several of
your classes.
You can use singletons in place of static if you're sure that you
need only one object.
Simply spoken: don't use static.
static is an abnormality in good OO design. It leads to direct coupling between your classes. It makes it hard to later replace "implementation"; and it makes it hard to write reasonable unit tests.
Meaning: by default, you do not use static. There might be situations when it is fine to use; but the example code you are showing does not at all look like you should be using static.
Instead, you should be defining an interface that denotes the functionality of your Radio; allowing for different implementations behind that interfaces.
It depends on what are you looking for.
Lets say you are creating 4 objects of Radio.
radioOne....,radioFour...
Now if you want all Radios to start at same time, you should go for static variable because static properties are characteristics of all objects of a class. They are not exclusive to any particular object and in practice they should be assessed using class like :
Radio.radionOn=true;
and not radioOne.radioOn=true;
So, I would suggest you to make only those properties static which will be common to all objects. If all the properties will fall under that ambit,
then it would mean you want only one object for the class because all your objects would behave the same .So better to have one object . In that case go for singleton pattern for object creation.
I have a global boolean variable which I use to disable all trading in my financial trading system.
I disable trading if there is any uncaught exception or a variety of other conditions (e.g. no money in account).
Should this variable be static or an instance variable? If its an instance I will need to add it to constructors of loads of classes...Not sure if its worth the hassle.
Thxs.
If it's an instance, then you probably want it to be a Singleton, and you'll provide a public static getter (or a factory, or DI if you care about testing).
If you access it from multiple threads, then it'd better be an AtomicBoolean in both cases.
Throughout your entire career, the number of times that you will have a valid use for a global variable will be countable in the fingers of one hand. So, any given time you are faced with a "to global or not to global" decision, most chances (by far) are that the correct answer is NOT. As a matter of fact, unless you are writing operating system kernels and the like, the rule of thumb should be "do not, under any circumstances, make any variable whatsoever, anywhere, anytime, global."
Note that wrapping access to a global variable in a global (static) method is just fooling yourself: it is still just a global variable. Global methods are only okay if they are stateless.
The link provided by #HermantMetalia is a good read: Why are static variables considered evil.
In your case, what you need is probably some kind of "Manager" object, a reference to which you pass as a construction time parameter to all of your major logic objects, which, among other things, contains a property called "isTradingAllowed" or something like that, so that anyone interested in this piece of information can query it.
I'd put it in a static field. But prefer to make it an AtomicBoolean to prevent threading issues :-)
public class TradeMaster {
private static final AtomicBoolean TRADING_ALLOWED = new AtomicBoolean(true);
public static void stopTrading() {
TRADING_ALLOWED.set(false);
}
public static boolean isTradingAllowed() {
return TRADING_ALLOWED.get();
}
}
Static Pros:
No need to pass references to instance to every class which will be using this
Static Cons:
May lead to difficult in testing - I think it should be fairly easy to test a static variable if you set the state of the variable before and after the test (assuming the tests are not running concurrently).
Conclusion:
I think the choice here depends on what your view of testing static variables is...For this simple case of one variable managing the state I really cant see the problem with using static. On the otherhand...its not really that hard to pass an instance to the constructors of the dependent classes so you dont really have any downside when using the instance approach.
It should be static since it will be shared by all the instances of
this class.
It should be static since you dont want to have a separate variable for all the objects.
Given that I would suggest that you read some good resources for static variable usage they work like charm unless you mess them..
If you want to make a variable constant for the class irrespective of how many instances are creted then use static method. But if the variable may change depending on the use by different instance of class then use instance variable.
Example
*
Here is an example that might clarify the situation. Imagine that you
are creating a game based on the movie 101 Dalmations. As part of that
project, you create a Dalmation class to handle animating the various
Dalmations. The class would need instance (non-static) variables to
keep track of data that is specific to each Dalmation: what its name
is, how many spots it has, etc..
*
But you also need to be able to keep track of how many Dalmations have
been created so you don't go over 101. That can't be an instance
variable because it has to be independent of specific Dalmations. For
example, if you haven't created any Dalmations, then this variable has
to be able to store zero. Only static variables exist before objects
are created. That is what static variables are for - data that applies
to something that is beyond the scope of a specific instance of the
class.
So I have a question regarding best practices. Basically I'm doing the following to make accessing members of different classes easier:
class myClass1 {
public static int var1;
public static String var2;
//...
public static void method1() {
//...
}
}
And then in other classes I can just access myClass1 members with myClass1.var1, myClass1.var2, myClass1.method1(). Another design pattern I see is to not use static at all and just do myClass1 instance = new myClass1(); and then do instance.method1(); or whatever.
I remember hearing something somewhere about static being bad... relating to global objects or whatever. But it's been a while since intro to computer science, heh.
Anyways, beginner Java programmer just looking to get some insight into best practices. Thanks.
The semantics of static vs. non-static member variables and methods are completely different. Non-static variables are members of instances of the class; each instance has its own copy. Static variables are members of the class itself; they're not tied to any particular instance.
Similarly, non-static methods operate on instances of the class, static methods aren't tied to a particular instance.
You should use static/non-static as the problem requires. This isn't a question of best practices.
In general having all the members fields/methods public static is considered bad practice for Object Oriented Programming paradigm. It takes all the notions of object encapsulation and data security. Any client of your class is free to tamper your data any time. This kind of practice is very similar to defining global variables and functions in procedural languages like C.
There are several reasons why this is a bad idea:
Public field. Using public fields makes it practically impossible to write thread-safe code. It also makes it hard to maintain or modify your code. On a theoretical level it violates encapsulation, which is one of the basic ideas of OO with all its consequences. For example if you have complex state, where not every combination of field values is valid, you're in trouble.
Static field. Although static fields have their legitimate uses, it should be kept to a minimum. They aren't inherited, which can easily lead to confusion and at the best of times it's a ticking time bomb.
All in all: don't use static fields unless it is necessary, and even then they should be private.
The notable exception is obviously static and final fields (aka. constants) which can be declared public without too many dangers.
Generally speaking one never makes static variables except for static final variables which are then like constants. The primary reason is that more than one thread can then change the state of the global variable at the same time leading to unpredictable state of every object instance of that class.
As per Object oriented fundamental concerns :
Variable should not be accessible outside the class. So they should be private not public except interface case. This is applicable to Static variable as well.
You want to access the variable use public method. In case of static variable you will static public method.
It depends entirely what you are doing. If your class just holds stateless utility functions then this may be OK. If you are trying to any kind of real OOP design, then this doesn't make sense.
If you use instances of classes to model objects in the 'real world', then they will need instance variables, and should have instance methods to act upon that data. Each instance encapsulates that data and provides suitable behaviour.
This question already has answers here:
Difference between static class and singleton pattern?
(41 answers)
Closed 5 years ago.
How is a singleton different from a class filled with only static fields?
Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:
A non-static class can be extended. Polymorphism can save a lot of repetition.
A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.
Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.
A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.
Let's me sum up :)
The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:
Singleton can be extended. Static not.
Singleton creation may not be threadsafe if it isn't implemented properly. Static not.
Singleton can be passed around as an object. Static not.
Singleton can be garbage collected. Static not.
Singleton is better than static class!
More here but I haven't realized yet :)
Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea for not using this God object (believe me, you will tend to put all the "interesting" stuffs to this class) and use a normal class named "Context" or something like that instead.
A singleton can be initialized lazily, for one.
I think, significant thing is 'object' in object oriented programing. Except from few cases we should restrict to usage of static classes. That cases are:
When the create an object is meaningless. Like methods of java.lang.Math. We can use the class like an object. Because the behavior of Math class methods doesn't depend on the state of the objects to be created in this class.
Codes to be used jointly by more than one object method, the codes that do not reach the object's variables and are likely to be closed out can be static methods
Another important thing is singleton is extensible. Singleton can be extended. In the Math class, using final methods, the creation and extension of the object of this class has been avoided. The same is true for the java.lang.System class. However, the Runtime class is a single object, not a static method. In this case you can override the inheritance methods of the Runtime class for different purposes.
You can delay the creation of a Singleton object until it is needed (lazy loading). However, for static method classes, there is no such thing as a condition. If you reach any static member of the class, the class will be loaded into memory.
As a result, the most basic benefit to the static method class is that you do not have to create an object, but when used improperly, it will remove your code from being object-oriented.
The difference is language independent. Singleton is by definition: "Ensure a class has only one instance and provide a global point of access to it. " a class filled with only static fields is not same as singleton but perhaps in your usage scenario they provide the same functionality. But as JRL said lazy initiation is one difference.
At least you can more easily replace it by a mock or a stub for unit testing. But I am not a big fan of singletons for exactly the reason you are describing : it are global variables in disguise.
A singleton class will have an instance which generally is one and only one per classloader. So it can have regular methods(non static) ones and they can be invoked on that particular instance.
While a Class with only static methods, there is really no need in creating an instance(for this reason most of the people/frameworks make these kind of Util classes abstract). You will just invoke the methods on class directly.
The first thing that comes to mind is that if you want to use a class with only static methods and attributes instead of a singleton you will have to use the static initializer to properly initialise certain attributes. Example:
class NoSingleton {
static {
//initialize foo with something complex that can't be done otherwise
}
static private foo;
}
This will then execute at class load time which is probably not what you want. You have more control over this whole shebang if you implement it as a singleton. However I think using singletons is not a good idea in any case.
A singleton is a class with just one instance, enforced. That class may have state (yes I know static variables hold state), not all of the member variables or methods need be static.
A variation would be a small pool of these objects, which would be impossible if all of the methods were static.
NOTE: The examples are in C#, as that is what I am more familiar with, but the concept should apply to Java just the same.
Ignoring the debate on when it is appropriate to use Singleton objects, one primary difference that I am aware of is that a Singleton object has an instance that you can pass around.
If you use a static class, you hard-wire yourself to a particular implementation, and there's no way to alter its behavior at run-time.
Poor design using static class:
public class MyClass
{
public void SomeMethod(string filename)
{
if (File.Exists(filename))
// do something
}
}
Alternatively, you could have your constructor take in an instance of a particular interface instead. In production, you could use a Singleton implementation of that interface, but in unit tests, you can simply mock the interface and alter its behavior to satisfy your needs (making it thrown some obscure exception, for example).
public class MyClass
{
private IFileSystem m_fileSystem;
public MyClass(IFileSystem fileSystem)
{
m_fileSystem = fileSystem;
}
public void SomeMethod(string filename)
{
if (m_fileSystem.FileExists(filename))
// do something
}
}
This is not to say that static classes are ALWAYS bad, just not a great candidate for things like file systems, database connections, and other lower layer dependencies.
One of the main advantages of singletons is that you can implement interfaces and inherit from other classes. Sometimes you have a group of singletons that all provide similar functionality that you want to implement a common interface but are responsible for a different resource.
Singleton Class :
Singleton Class is class of which only single instance can exists per classloader.
Helper Class (Class with only static fields/methods) :
No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.
These few lines from this blog describes it nicely:
Firstly the Singleton pattern is very
useful if you want to create one
instance of a class. For my helper
class we don't really want to
instantiate any copy's of the class.
The reason why you shouldn't use a
Singleton class is because for this
helper class we don't use any
variables. The singleton class would
be useful if it contained a set of
variables that we wanted only one set
of and the methods used those
variables but in our helper class we
don't use any variables apart from the
ones passed in (which we make final).
For this reason I don't believe we
want a singleton Instance because we
do not want any variables and we don't
want anyone instantianting this class.
So if you don't want anyone
instantiating the class, which is
normally if you have some kind of
helper/utils class then I use the what
I call the static class, a class with
a private constructor and only
consists of Static methods without any
any variables.
I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.
One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods are more suited to utilitarian types of operations where the behavior is set in stone. Things like base 64 encoding or calculating a checksum for instance.
I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C.
You need to think about the messages the object you are designing responds to. Those will always be your instance methods. If you think about your objects this way, you'll almost never have static methods. Static members are ok in certain circumstances.
Notable exceptions that come to mind are the Factory Method and Singleton (use sparingly) patterns. Exercise caution when you are tempted to write a "helper" class, for from there, it is a slippery slope into procedural programming.
If the implementation of a method can be expressed completely in terms of the public interface (without downcasting) of your class, then it may be a good candidate for a static "utility" method. This allows you to maintain a minimal interface while still providing the convenience methods that clients of the code may use a lot. As Scott Meyers explains, this approach encourages encapsulation by minimizing the amount of code impacted by a change to the internal implementation of a class. Here's another interesting article by Herb Sutter picking apart std::basic_string deciding what methods should be members and what shouldn't.
In a language like Java or C++, I'll admit that the static methods make the code less elegant so there's still a tradeoff. In C#, extension methods can give you the best of both worlds.
If the operation will need to be overridden by a sub-class for some reason, then of course it must be an instance method in which case you'll need to think about all the factors that go into designing a class for inheritance.
My rule of thumb is: if the method performs anything related to a specific instance of a class, regardless of whether it needs to use class instance variables. If you can consider a situation where you might need to use a certain method without necessarily referring to an instance of the class, then the method should definitely be static (class). If this method also happens to need to make use of instance variables in certain cases, then it is probably best to create a separate instance method that calls the static method and passes the instance variables. Performance-wise I believe there is negligible difference (at least in .NET, though I would imagine it would be very similar for Java).
If you keep state ( a value ) of an object and the method is used to access, or modify the state then you should use an instance method.
Even if the method does not alter the state ( an utility function ) I would recommend you to use an instance method. Mostly because this way you can have a subclass that perform a different action.
For the rest you could use an static method.
:)
This thread looks relevant: Method can be made static, but should it? The difference's between C# and Java won't impact its relevance (I think).
Your default choice should be an instance method.
If it uses an instance variable it must be an instance method.
If not, it's up to you, but if you find yourself with a lot of static methods and/or static non-final variables, you probably want to extract all the static stuff into a new class instance. (A bunch of static methods and members is a singleton, but a really annoying one, having a real singleton object would be better--a regular object that there happens to be one of, the best!).
Basically, the rule of thumb is if it uses any data specific to the object, instance. So Math.max is static but BigInteger.bitCount() is instance. It obviously gets more complicated as your domain model does, and there are border-line cases, but the general idea is simple.
I would use an instance method by default. The advantage is that behavior can be overridden in a subclass or if you are coding against interfaces, an alternative implementation of the collaborator can be used. This is really useful for flexibility in testing code.
Static references are baked into your implementation and can't change. I find static useful for short utility methods. If the contents of your static method are very large, you may want to think about breaking responsibility into one or more separate objects and letting those collaborate with the client code as object instances.
IMHO, if you can make it a static method (without having to change it structure) then make it a static method. It is faster, and simpler.
If you know you will want to override the method, I suggest you write a unit test where you actually do this and so it is no longer appropriate to make it static. If that sounds like too much hard work, then don't make it an instance method.
Generally, You shouldn't add functionality as soon as you imagine a use one day (that way madness lies), you should only add functionality you know you actually need.
For a longer explanation...
http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It
http://c2.com/xp/YouArentGonnaNeedIt.html
the issue with static methods is that you are breaking one of the core Object Oriented principles as you are coupled to an implementation. You want to support the open close principle and have your class implement an interface that describes the dependency (in a behavioral abstract sense) and then have your classes depend on that innterface. Much easier to extend after that point going forward . ..
My static methods are always one of the following:
Private "helper" methods that evaluate a formula useful only to that class.
Factory methods (Foo.getInstance() etc.)
In a "utility" class that is final, has a private constructor and contains nothing other than public static methods (e.g. com.google.common.collect.Maps)
I will not make a method static just because it does not refer to any instance variables.