Java: static variable declaration best practices [closed] - java

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.

Related

private static throughout code [closed]

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.

Maintaining state of the application using only static variables and static methods in class [closed]

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.

Singleton or class with all static members [closed]

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.

Why do we need final class in java? [duplicate]

I am reading a book about Java and it says that you can declare the whole class as final. I cannot think of anything where I'd use this.
I am just new to programming and I am wondering if programmers actually use this on their programs. If they do, when do they use it so I can understand it better and know when to use it.
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
First of all, I recommend this article: Java: When to create a final class
If they do, when do they use it so I can understand it better and know when to use it.
A final class is simply a class that can't be extended.
(It does not mean that all references to objects of the class would act as if they were declared as final.)
When it's useful to declare a class as final is covered in the answers of this question:
Good reasons to prohibit inheritance in Java?
If Java is object oriented, and you declare a class final, doesn't it stop the idea of class having the characteristics of objects?
In some sense yes.
By marking a class as final you disable a powerful and flexible feature of the language for that part of the code. Some classes however, should not (and in certain cases can not) be designed to take subclassing into account in a good way. In these cases it makes sense to mark the class as final, even though it limits OOP. (Remember however that a final class can still extend another non-final class.)
In Java, items with the final modifier cannot be changed!
This includes final classes, final variables, and final methods:
A final class cannot be extended by any other class
A final variable cannot be reassigned another value
A final method cannot be overridden
One scenario where final is important, when you want to prevent inheritance of a class, for security reasons. This allows you to make sure that code you are running cannot be overridden by someone.
Another scenario is for optimization: I seem to remember that the Java compiler inlines some function calls from final classes. So, if you call a.x() and a is declared final, we know at compile-time what the code will be and can inline into the calling function. I have no idea whether this is actually done, but with final it is a possibility.
The best example is
public final class String
which is an immutable class and cannot be extended.
Of course, there is more than just making the class final to be immutable.
If you imagine the class hierarchy as a tree (as it is in Java), abstract classes can only be branches and final classes are those that can only be leafs. Classes that fall into neither of those categories can be both branches and leafs.
There's no violation of OO principles here, final is simply providing a nice symmetry.
In practice you want to use final if you want your objects to be immutable or if you're writing an API, to signal to the users of the API that the class is just not intended for extension.
Relevant reading: The Open-Closed Principle by Bob Martin.
Key quote:
Software Entities (Classes, Modules,
Functions, etc.) should be open for
Extension, but closed for
Modification.
The final keyword is the means to enforce this in Java, whether it's used on methods or on classes.
The keyword final itself means something is final and is not supposed to be modified in any way. If a class if marked final then it can not be extended or sub-classed. But the question is why do we mark a class final? IMO there are various reasons:
Standardization: Some classes perform standard functions and they are not meant to be modified e.g. classes performing various functions related to string manipulations or mathematical functions etc.
Security reasons: Sometimes we write classes which perform various authentication and password related functions and we do not want them to be altered by anyone else.
I have heard that marking class final improves efficiency but frankly I could not find this argument to carry much weight.
If Java is object oriented, and you declare a class final, doesn't it
stop the idea of class having the characteristics of objects?
Perhaps yes, but sometimes that is the intended purpose. Sometimes we do that to achieve bigger benefits of security etc. by sacrificing the ability of this class to be extended. But a final class can still extend one class if it needs to.
On a side note we should prefer composition over inheritance and final keyword actually helps in enforcing this principle.
final class can avoid breaking the public API when you add new methods
Suppose that on version 1 of your Base class you do:
public class Base {}
and a client does:
class Derived extends Base {
public int method() { return 1; }
}
Then if in version 2 you want to add a method method to Base:
class Base {
public String method() { return null; }
}
it would break the client code.
If we had used final class Base instead, the client wouldn't have been able to inherit, and the method addition wouldn't break the API.
A final class is a class that can't be extended. Also methods could be declared as final to indicate that cannot be overridden by subclasses.
Preventing the class from being subclassed could be particularly useful if you write APIs or libraries and want to avoid being extended to alter base behaviour.
In java final keyword uses for below occasions.
Final Variables
Final Methods
Final Classes
In java final variables can't reassign, final classes can't extends and final methods can't override.
Be careful when you make a class "final". Because if you want to write an unit test for a final class, you cannot subclass this final class in order to use the dependency-breaking technique "Subclass and Override Method" described in Michael C. Feathers' book "Working Effectively with Legacy Code". In this book, Feathers said, "Seriously, it is easy to believe that sealed and final are a wrong-headed mistake, that they should never have been added to programming languages. But the real fault lies with us. When we depend directly on libraries that are out of our control, we are just asking for trouble."
If the class is marked final, it means that the class' structure can't be modified by anything external. Where this is the most visible is when you're doing traditional polymorphic inheritance, basically class B extends A just won't work. It's basically a way to protect some parts of your code (to extent).
To clarify, marking class final doesn't mark its fields as final and as such doesn't protect the object properties but the actual class structure instead.
TO ADDRESS THE FINAL CLASS PROBLEM:
There are two ways to make a class final. The first is to use the keyword final in the class declaration:
public final class SomeClass {
// . . . Class contents
}
The second way to make a class final is to declare all of its constructors as private:
public class SomeClass {
public final static SOME_INSTANCE = new SomeClass(5);
private SomeClass(final int value) {
}
Marking it final saves you the trouble if finding out that it is actual a final, to demonstrate look at this Test class. looks public at first glance.
public class Test{
private Test(Class beanClass, Class stopClass, int flags)
throws Exception{
// . . . snip . . .
}
}
Unfortunately, since the only constructor of the class is private, it is impossible to extend this class. In the case of the Test class, there is no reason that the class should be final. The Test class is a good example of how implicit final classes can cause problems.
So you should mark it final when you implicitly make a class final by making it's constructor private.
One advantage of keeping a class as final :-
String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.
Developer of this class wanted no one to change functionality of this class, so he kept it as final.
The other answers have focused on what final class tells the compiler: do not allow another class to declare it extends this class, and why that is desirable.
But the compiler is not the only reader of the phrase final class. Every programmer who reads the source code also reads that. It can aid rapid program comprehension.
In general, if a programmer sees Thing thing = that.someMethod(...); and the programmer wants to understand the subsequent behaviour of the object accessed through the thing object-reference, the programmer must consider the Thing class hierarchy: potentially many types, scattered over many packages. But if the programmer knows, or reads, final class Thing, they instantly know that they do not need to search for and study so many Java files, because there are no derived classes: they need study only Thing.java and, perhaps, it's base classes.
Yes, sometimes you may want this though, either for security or speed reasons. It's done also in C++. It may not be that applicable for programs, but moreso for frameworks.
http://www.glenmccl.com/perfj_025.htm
think of FINAL as the "End of the line" - that guy cannot produce offspring anymore. So when you see it this way, there are ton of real world scenarios that you will come across that requires you to flag an 'end of line' marker to the class. It is Domain Driven Design - if your domain demands that a given ENTITY (class) cannot create sub-classes, then mark it as FINAL.
I should note that there is nothing stopping you from inheriting a "should be tagged as final" class. But that is generally classified as "abuse of inheritance", and done because most often you would like to inherit some function from the base class in your class.
The best approach is to look at the domain and let it dictate your design decisions.
As above told, if you want no one can change the functionality of the method then you can declare it as final.
Example: Application server file path for download/upload, splitting string based on offset, such methods you can declare it Final so that these method functions will not be altered. And if you want such final methods in a separate class, then define that class as Final class. So Final class will have all final methods, where as Final method can be declared and defined in non-final class.
Let's say you have an Employee class that has a method greet. When the greet method is called it simply prints Hello everyone!. So that is the expected behavior of greet method
public class Employee {
void greet() {
System.out.println("Hello everyone!");
}
}
Now, let GrumpyEmployee subclass Employee and override greet method as shown below.
public class GrumpyEmployee extends Employee {
#Override
void greet() {
System.out.println("Get lost!");
}
}
Now in the below code have a look at the sayHello method. It takes Employee instance as a parameter and calls the greet method hoping that it would say Hello everyone! But what we get is Get lost!. This change in behavior is because of Employee grumpyEmployee = new GrumpyEmployee();
public class TestFinal {
static Employee grumpyEmployee = new GrumpyEmployee();
public static void main(String[] args) {
TestFinal testFinal = new TestFinal();
testFinal.sayHello(grumpyEmployee);
}
private void sayHello(Employee employee) {
employee.greet(); //Here you would expect a warm greeting, but what you get is "Get lost!"
}
}
This situation can be avoided if the Employee class was made final. Just imagine the amount of chaos a cheeky programmer could cause if String Class was not declared as final.
Final class cannot be extended further. If we do not need to make a class inheritable in java,we can use this approach.
If we just need to make particular methods in a class not to be overridden, we just can put final keyword in front of them. There the class is still inheritable.
Final classes cannot be extended. So if you want a class to behave a certain way and don't someone to override the methods (with possibly less efficient and more malicious code), you can declare the whole class as final or specific methods which you don't want to be changed.
Since declaring a class does not prevent a class from being instantiated, it does not mean it will stop the class from having the characteristics of an object. It's just that you will have to stick to the methods just the way they are declared in the class.
Android Looper class is a good practical example of this.
http://developer.android.com/reference/android/os/Looper.html
The Looper class provides certain functionality which is NOT intended to be overridden by any other class. Hence, no sub-class here.
I know only one actual use case: generated classes
Among the use cases of generated classes, I know one: dependency inject e.g. https://github.com/google/dagger
Object Orientation is not about inheritance, it is about encapsulation. And inheritance breaks encapsulation.
Declaring a class final makes perfect sense in a lot of cases. Any object representing a “value” like a color or an amount of money could be final. They stand on their own.
If you are writing libraries, make your classes final unless you explicitly indent them to be derived. Otherwise, people may derive your classes and override methods, breaking your assumptions / invariants. This may have security implications as well.
Joshua Bloch in “Effective Java” recommends designing explicitly for inheritance or prohibiting it and he notes that designing for inheritance is not that easy.

Should all methods that do not use instance variables be marked static

Suppose I have a class like this:
public class Car {
private double distanceDriven;
public void drive(double miles){
distanceDriven += miles;
}
public void driveInCanada(double kilometer){
distanceDriven += convertToMiles(kilometer);
}
private double convertToMiles(double km){
return km*0.621371192;
}
}
You can see that convertToMiles is:
not using any instance variables
is only used inside the class
Should it be declared as static? This does not change the functionality of the the function at all (see above). I think that it may affect:
readability
performance
other?
Should the convertToMiles function look like:
private double convertToMiles(double km){
or
private static double convertToMiles(double km){
For maximum stylistic hygiene, yes, private methods that don't use any object state, but only make sense inside the object, should be static.
That's the clearest (and strictest) way of indicating how they operate, and it will helpfully force you to be careful about your design around method-boundaries, and to think twice if you decide to go change one of them later to use object data.
FWIW, I don't suspect there's a relevant performance impact here (in theory the static is easier to call due to no implicit this reference). Also, you could go nuts being strict about this in your codebase, but it's certainly a reasonable goal to have.
N.B. Public methods require more consideration before marking them static; those can't change down the road without impact to callers, so "defaulting to tightness" isn't always the right choice.
If you're asking yourself this, they your design is already shaky. You should rip all those "static" functions out of the class and put them in a generic, reusable algorithm container static class.
Look at your code, what does convertToMiles have to do with a car? That's a generic algorithm that can be reused in multiple functions.
Using static might make a performance difference, however this is less likely if it is inlined as it won't be called as much.
static is useful as it makes it clear you are not accessing any member fields. This has picked up some bugs for me in the past when I marked a method as static but this produced an error (because it shouldn't have been using a member field)
You can get creative with the design and add layers and complexity which might be useful one day, but I would go with the YANGI principle and say it is unlikely you are going to want to change how kilo-meters are converted to miles, or if you do change it you are unlikely to want more than one way of doing it.
A definitive NO for ALL such methods.
For example it is perfect legal that such a method calculates an result (return value) only on its arguments, and the author would like to allow others to change the calculation in a subclass. (This is some kind of Template Method pattern.) -- And overriding a class can be only done if they are ..not.. static.
Btw: if you change your question and ask only for private methods, then I could not argue this way. But you asked for all kind of methods.
yes. Use static methods when you can.
private static double convertToMiles(double km){}
This will be the right one for your program code as convertToMiles() method has nothing to do with the instance variable.
But keep in mind this method is not reusable in other class by non-static members, if yes then the very purpose of static wont serve, as static avoids multiple object creation and memory wastage.

Categories