In Java, static final variables are constants and the convention is that they should be in upper-case. However, I have seen that most people declare loggers in lower-case which comes up as a violation in PMD.
e.g:
private static final Logger logger = Logger.getLogger(MyClass.class);
Just search googleor SO for "static final logger" and you will see this for yourself.
Should we be using LOGGER instead?
The logger reference is not a constant, but a final reference, and should NOT be in uppercase. A constant VALUE should be in uppercase.
private static final Logger logger = Logger.getLogger(MyClass.class);
private static final double MY_CONSTANT = 0.0;
To add more value to crunchdog's answer, The Java Coding Style Guide states this in paragraph 3.3 Field Naming
Names of fields being used as constants should be all upper-case, with underscores separating words. The following are considered to be constants:
All static final primitive types (Remember that all interface fields are inherently static final).
All static final object reference types that are never followed by "." (dot).
All static final arrays that are never followed by "[" (opening square bracket).
Examples:
MIN_VALUE, MAX_BUFFER_SIZE, OPTIONS_FILE_NAME
Following this convention, logger is a static final object reference as stated in point 2, but because it is followed by "." everytime you use it, it can not be considered as a constant and thus should be lower case.
From effective java, 2nd ed.,
The sole exception to the previous rule concerns “constant fields,”
whose names should consist of one or more uppercase words separated by
the underscore character, for example, VALUES or NEGATIVE_INFINITY. A
constant field is a static final field whose value is immutable. If a
static final field has a primitive type or an immutable reference type
(Item 15), then it is a constant field. For example, enum constants
are constant fields. If a static final field has a mutable reference
type, it can still be a constant field if the referenced object is
immutable.
In summary, constant == static final, plus if it's a reference (vs. a simple type), immutability.
Looking at the slf4j logger,
http://www.slf4j.org/api/org/slf4j/Logger.html
It is immutable. On the other hand, the JUL logger is mutable. The log4j logger is also mutable. So to be correct, if you are using log4j or JUL, it should be "logger", and if you are using slf4j, it should be LOGGER.
Note that the slf4j javadocs page linked above has an example where they use "logger", not "LOGGER".
These are of course only conventions and not rules. If you happen to be using slf4j and you want to use "logger" because you are used to that from other frameworks, or if it is easier to type, or for readability, go ahead.
I like Google's take on it (Google Java Style)
Every constant is a static final field, but not all static final fields are constants. Before choosing constant case, consider whether the field really feels like a constant. For example, if any of that instance's observable state can change, it is almost certainly not a constant. Merely intending to never mutate the object is generally not enough.
Examples:
// Constants
static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable
static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants
static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
If you are using an automated tool to check your coding standards and it violates said standards then it or the standards should be fixed. If you're using an external standard, fix the code.
The convention in Sun Java is uppercase for public static constants. Obviously a logger is not constant, but represents a mutable thing ( otherwise there would be no point calling methods on it in the hope that something will happen ); there's no specific standard for non-constant final fields.
If you google this, you might find that in some cases, the loggers are not defined as static final. Add some quick copy-n-paste to this, and this might explain it.
We use LOGGER in all our code, and this corresponds to our naming convention (and our CheckStyle is happy with it).
We even go further, taking advantage of the strict naming convention in Eclipse.
We create a new class with a code template of :
// private static final Logger LOGGER = Logger.getLogger(${enclosing_type}.class);
The logger is commented out, as initially we don't need it. But should we need it later, we just uncomment it.
Then in the code, we use code templates that expect this logger to be present.
Example with the try-catch template:
try {
${cursor} or some other template
} catch (Exception t) {
LOGGER.error("${methodName} ${method parameters}", t);
}
We have a few more templates that use it.
The strict convention allow us to be more productive and coherent with code templates.
I personally think it looks really big in upper-case. Moreover, since it's a class that it's not directly related to the class behaviour, I don't see a major problem in using logger instead of LOGGER. But if you are going to be strictly pedantic, then use LOGGER.
Don't forget that PMD will respect a comment with
// NOPMD
in it. This will cause PMD to skip the line from its checks, this will allow you to choose whichever style you want.
Usually constants are in uppercase.
Loggers, however, should not be static but looked up for every "new" of the containing class if using the slf4j facade. This avoids some nasty classloader issues in notably web containers, plus it allows the logger framework to do special stuff depending on the invocation context.
If your coding standards - if you have any - say that it should be uppercase then yes.
I don't see any stringent reason for one way or the other. I think it totally depends on your personal likes resp. your company coding standards.
BTW: I prefer "LOGGER" ;-)
I prefer 'logger', i.e. the lower case. The reason is not that it's a constant or not a constant (mutable or immutable). If we'd use that reasoning, we'd have to rename the variable if we change the logging framework (or if the framework changes the mutability of loggers).
For me, other reasons are more important.
A logger is a shadow object in the class and should not be very prominent as it does not implement the main logic. If we use 'LOGGER', it's an eye catcher in the code that attracts too much attention.
Sometimes loggers are declared at instance level (i.e. not as static), and even are injected as a dependency. I wouldn't like to change my code if I decide to change the way I obtain the logger. The code stability wrt. this (hypothetical in many cases) change is the other reason why I prefer the lower case.
Related
I understand that instance-level final variables follow the camel case naming conventions but I was wondering if it should be the case for a Singleton Class as well.
Would you treat final in a Singleton Class as a constant and follow the constants naming convention as follows:
private final SomeObject SOME_OBJECT;
OR, would you name it in camel case, following the normal variable naming conventions?
private final SomeObject someObject;
This keeps on popping up in multiple code reviews and I always have some grey area. Appreciate any thoughts on this.
According to typical Java coding standards and conventions, the ALL_CAPS identifier style is reserved for static final constants (and enum constants ...). In your case, the variable is final but not static, so that exception to the normal rules for variables does not apply.
That is my interpretation, and (I think) the most common interpretation. It is not the only interpretation. You and your team could choose to interpret the conventions differently, or even ignore them entirely1.
The most important thing is to be consistent across you / your team / your organization's common code base.
1 - ... though the latter would be unwise, IMO,
This is a topic that is more based on community opinion than on a set standard.
If it is at the class level, and it is final, and there is only one instance, assuming you are using it as a constant, in my opinion, I would use Underscore, as it is basically a constant, but it is initialized at runtime.
class AClass {
private final SomeObject SOME_OBJECT;
private initInstance() {
SOME_OBJECT = ...;
}
...
}
This might be a helpful link:
https://softwareengineering.stackexchange.com/questions/252243/naming-convention-final-fields-not-static
What this link boils down to is that while any answer will be opinionated, a good heuristic would be to ask yourself "is this behaving like a constant? or is it behaving like a write once field?"
If it is a constant that is made at runtime, DO_THIS.
If it is a field that you write to once, but manipulate later, doThis.
This question already has answers here:
private final static attribute vs private final attribute
(22 answers)
Closed 8 years ago.
I've created an interface with the following code
final static char RIVER = '~';
final static char PATH = 'Y';
The list will increase (not hundres or even tens but maybe at most 15 symbols)
Originally I was just coding the values directly into the object but I started wondering why I couldn't just create a single file with the global constansts (for the symbols on the map and only the symbols) for easy access.
I'm aware that per OO logic, encapsulation is how we should program. At the same time, final static variables exist so surely they do have a purpose.
My question then is there a reason for me to avoid using the global constants and go back to putting each symbol with each object? Does global constants have a role to play within OO programming at all or is it purely for Procedural Programming?
This is a project that only I will ever work on however I am using as a testbed to improve my standards and as such I would like to use the best method possible (in terms of standard).
Defining global constants in an interface is an anti-pattern. Either use classes to define constants and then use static imports. Or simply use enums, which gives more flexibility.
Defining global (public static) constants is okay. It helps to keep you code clear and maintainable, by giving certain values meaningful names.
What you should not do, is define global constants in an interface and then add an implements-clause to each class that uses these constants. The reason for this, that you pollute the public signature of your class in this way. Instead, alsways refer to the constants by their full name (e.g. SomeClass.SOME_CONSTANT) or statically import them (import SomeClass.SOME_CONSTANT).
I would not define all global constants in one single file however, but define each of them in the class or interface that makes the most sense, for example because they define methods that return these constants or where the constants are typical arguments.
There are several benefits in use the constants, these are some of them:
Readability: If you hard code the number, when you or some other programmer have to use the code, they have to know what the value means. If a constant is used, a meaningful name is provided.
Reusability: If the same constant needs to be used in several place, when a modification is needed, you only have to change the value in one place instead of all the places where the constant is used.
Maintainability: If you have your constants in a single place instead of multiple places in the code, it is easier to modify.
It is considered a bad practice to use interfaces to hold the constants, use classes instead. If the constants are related with the class, you can define the constants within the class. If they are general purpose constants and used in several classes, you can create an utility class to hold all the constants.
public class MyUtilityClass {
public static final int MY_INT_CONSTANT = 1234;
public static final String MY_STRING_CONSTANT = "example";
...
/* Create a private constructor to avoid creation of instances of this class */
private MyUtilityClass() {
}
}
Global constants are absolutely fine.
That having been said, do not even try programming without the maximum number* of compiler warnings enabled. If you had enough warnings enabled, your compiler would be telling you that fields in interfaces do not need to be declared final and they do not need to be declared static.
(* warnings that make sense. Every compiler has its own set of warnings that are rather nonsensical and best disabled, but these are generally few.)
Encapsulation is the mechanism which protects you from changes - for example, changing the implementation of a class, will not affect the rest of your code as long as the interface (the public or protected methods) does not change.
So you can apply this reasoning to your case. Will future changes of these constants affect the rest of the code? If not, then putting all those constants as final static instances in a single class is fine. But think of this. What if you want to change how you represent your map? (from the names of the variables I assume you're using them to represent a map) Maybe you want to use special objects which also have their own behaviour, not just how to represent them on the map. Then maybe you'll want to abstract those in new classes, and not use constants anymore. And this will affect all the code where you reference these constants - probably lots of classes.
Of course, you can start with this simple representation, and if at a later point you find it's not working anymore, then you can switch. This is what I would do. I don't think it's wrong.
I have seen much code where people write public static final String mystring = ...
and then just use a value.
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
UPDATE
Ok, thanks all for all your answers, I understand the meaning of those key (public static final). What I dont understand is why people use that even if the constant will be used only in one place and only in the same class. why declaring it? why dont we just use the variable?
final indicates that the value of the variable won't change - in other words, a constant whose value can't be modified after it is declared.
Use public final static String when you want to create a String that:
belongs to the class (static: no instance necessary to use it), that
won't change (final), for instance when you want to define a String constant that will be available to all instances of the class, and to other objects using the class, and that
will be a publicly accessible part of the interface that the class shows the world.
Example:
public final static String MY_CONSTANT = "SomeValue";
// ... in some other code, possibly in another object, use the constant:
if (input.equals(MyClass.MY_CONSTANT)
Similarly:
public static final int ERROR_CODE = 127;
It isn't required to use final, but it keeps a constant from being changed inadvertently during program execution, and serves as an indicator that the variable is a constant.
Even if the constant will only be used - read - in the current class and/or in only one place, it's good practice to declare all constants as final: it's clearer, and during the lifetime of the code the constant may end up being used in more than one place.
Furthermore using final may allow the implementation to perform some optimization, e.g. by inlining an actual value where the constant is used.
Finally note that final will only make truly constant values out of primitive types, String which is immutable, or other immutable types. Applying final to an object (for instance a HashMap) will make the reference immutable, but not the state of the object: for instance data members of the object can be changed, array elements can be changed, and collections can be manipulated and changed.
Static means..You can use it without instantiate of the class or using any object.
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest {
static final String str = "Hello";
public static void main(String args[]) {
// str = "world"; // gives error
System.out.println(str); // called without the help of an object
System.out.println(StringTest.str);// called with class name
}
}
Thanks
The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.
And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).
Hope it helps.
static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.
Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.
final indicates that the value cannot be changed once set. static allows you to set the value, and that value will be the same for ALL instances of the class which utilize it. Also, you may access the value of a public static string w/o having an instance of a class.
public makes it accessible across the other classes. You can use it without instantiate of the class or using any object.
static makes it uniform value across all the class instances.
It ensures that you don't waste memory creating many of the same thing if it will be the same value for all the objects.
final makes it non-modifiable value. It's a "constant" value which is same across all the class instances and cannot be modified.
You do not have to use final, but the final is making clear to everyone else - including the compiler - that this is a constant, and that's the good practice in it.
Why people doe that even if the constant will be used only in one place and only in the same class: Because in many cases it still makes sense. If you for example know it will be final during program run, but you intend to change the value later and recompile (easier to find), and also might use it more often later-on. It is also informing other programmers about the core values in the program flow at a prominent and combined place.
An aspect the other answers are missing out unfortunately, is that using the combination of public final needs to be done very carefully, especially if other classes or packages will use your class (which can be assumed because it is public).
Here's why:
Because it is declared as final, the compiler will inline this field during compile time into any compilation unit reading this field. So far, so good.
What people tend to forget is, because the field is also declared public, the compiler will also inline this value into any other compile unit. That means other classes using this field.
What are the consequences?
Imagine you have this:
class Foo {
public static final String VERSION = "1.0";
}
class Bar {
public static void main(String[] args) {
System.out.println("I am using version " + Foo.VERSION);
}
}
After compiling and running Bar, you'll get:
I am using version 1.0
Now, you improve Foo and change the version to "1.1".
After recompiling Foo, you run Bar and get this wrong output:
I am using version 1.0
This happens, because VERSION is declared final, so the actual value of it was already in-lined in Bar during the first compile run. As a consequence, to let the example of a public static final ... field propagate properly after actually changing what was declared final (you lied!;), you'd need to recompile every class using it.
I've seen this a couple of times and it is really hard to debug.
If by final you mean a constant that might change in later versions of your program, a better solution would be this:
class Foo {
private static String version = "1.0";
public static final String getVersion() {
return version;
}
}
The performance penalty of this is negligible, since JIT code generator will inline it at run-time.
Usually for defining constants, that you reuse at many places making it single point for change, used within single class or shared across packages. Making a variable final avoid accidental changes.
Why do people use constants in classes instead of a variable?
readability and maintainability,
having some number like 40.023 in your code doesn't say much about what the number represents, so we replace it by a word in capitals like "USER_AGE_YEARS". Later when we look at the code its clear what that number represents.
Why do we not just use a variable? Well we would if we knew the number would change, but if its some number that wont change, like 3.14159.. we make it final.
But what if its not a number like a String? In that case its mostly for maintainability, if you are using a String multiple times in your code, (and it wont be changing at runtime) it is convenient to have it as a final string at the top of the class. That way when you want to change it, there is only one place to change it rather than many.
For example if you have an error message that get printed many times in your code, having final String ERROR_MESSAGE = "Something went bad." is easier to maintain, if you want to change it from "Something went bad." to "It's too late jim he's already dead", you would only need to change that one line, rather than all the places you would use that comment.
public makes it accessible across other classes.
static makes it uniform value across all the class instances.
final makes it non-modifiable value.
So basically it's a "constant" value which is same across all the class instances and which cannot be modified.
With respect to your concern "What I don't understand is why people use that even if the constant will be used only in one place and only in the same class. Why declaring it? Why don't we just use the variable?"
I would say since it is a public field the constant value can also be used elsewhere in some other class using ClassName.value. eg: a class named Math may have PI as final static long value which can be accessed as Math.PI.
It is kind of standard/best practice.
There are already answers listing scenarios, but for your second question:
Why do they have to do that? Why do they have to initialize the value as final prior to using it?
Public constants and fields initialized at declaration should be "static final" rather than merely "final"
These are some of the reasons why it should be like this:
Making a public constant just final as opposed to static final leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.
Further, when a non-public, final field isn't also static, it implies that different instances can have different values. However, initializing a non-static final field in its declaration forces every instance to have the same value owing to the behavior of the final field.
This is related to the semantics of the code. By naming the value assigning it to a variable that has a meaningful name (even if it is used only at one place) you give it a meaning. When somebody is reading the code that person will know what that value means.
In general is not a good practice to use constant values across the code. Imagine a code full of string, integer, etc. values. After a time nobody will know what those constants are. Also a typo in a value can be a problem when the value is used on more than one place.
I think these are all clear explanations. But, Let me clarify it by giving a java inbuild example.
In java, most would have used System.out.println()
The system is a class and out is a PrintStream class.
So what java says is I will take care of the initialization of the out object(PrintStream) and keep the initialization private to myself in the System class.
public final class System {
public final static PrintStream out = null;
//Some initialization done by system class which cannot be changed as it is final.
}
You just access the println method statically without worrying about its initialization.
private static final Logger LOGGER = Logger.getLogger(AbstractDbClient.class);
protected Connection connection;
protected Connection connection;
private static final Logger LOGGER = Logger.getLogger(AbstractDbClient.class);
which order is better for field declareing? some books pointed that should order them by private/public/protected/etc, if base on this , the second code is better, but it seems looked bad. If incluse static final var or static var? which order rule is?
I suggest you keep it consistent, but I prefer to arrange fields in the order they are set as this makes it easier to understand the code and debug it. IMHO.
static final fields
final fields
mutable fields.
A common standard is to put all public variables on top, followed by protected, and then private. Some people put class/static variables on top before instance variables, and some put them after.
If you are working in a team that's writing new code, it would be best to get together and decide on a common convention. If you already have existing code that you are adding to, then go through it and figure out what convention the previous authors followed. You don't want a mix of styles in the same codebase.
Data layout actually has performance properties, besides ordering the fields as you feel comfortable with.
I tend to follow something like:
static final fields,
static fields
final fields
modifiable fields
volatile fields grouped by use cases
and sometimes
private field usedOnlyInFoo
method foo(){
}
More on the topic why data layout matters. While there is no formal way to enforce data layout in Java besides arrays/Direct Buffers usually the compiler (JVM) places the fields in their declaration order.
Personally I like all my statics at the top of a class and have all fields in public, protected, default, private order.
eg
public static final Integer a;
private static final Integer b;
public Integer c;
Integer d
private Integer d;
I also tend to add a line between teh statics and non static fields.
But it is a matter of opinion. Perhaps ask your peers whom you work with. It's better to be consistent on this sort of thing.
I'm declaring a field:
private static final String filename = "filename.txt";
First, does the order of private static final matter? If not, is there a standard accepted sequence or convention?
Second, the filename in my application is fixed. Is this the best was to store its value?
I use Checkstyle with Eclipse, which results in a warning if the declaration is in a different order to the one you've specified, citing the Java Language Specification (JLS). For example,
private final static String filename = "filename.txt";
results in
'static' modifier out of order with the JLS suggestions.
They have this page which lists the order they expect, though following the links on that page through to the JLS I can't see anything to back up their assertion of a suggested order.
Having said that, the order they suggest seems to correspond to the order in most of the code I've seen, so it seems as good a convention as any to adopt.
No. But that is the sequence I usually see used.
It's a reasonable choice, but some would prefer a configuration file, either Properties or another file format (e.g. XML). That way, you can change the filename without recompiling.
It's common in Java to give constants (static final values) an all-uppercase name, so I would write:
private static final String FILENAME = "filename.txt";
See also Code Conventions for the Java Programming Language. (Those are Sun's code conventions that the majority of Java programmers use).
The most accepted order of these keywords is private static final. Also you can remember the order of these keywords using PSF pattern that:
P => private / public / protected
S => static / abstract / ...
F => final
see: http://docs.oracle.com/javase/specs/jls/se5.0/html/classes.html#8.3.1
8.3.1 Field Modifiers
FieldModifiers:
FieldModifier
FieldModifiers FieldModifier
FieldModifier: one of
Annotation public protected private
static final transient volatile
...
If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for FieldModifier.
To complete the nice answer by #Hobo above by a current link
8.1.1. Class Modifiers
A class declaration may include class modifiers.
ClassModifier:
(one of)
Annotation public protected private
abstract static final strictfp
[...]
If two or more (distinct) class modifiers appear in a class
declaration, then it is customary, though not required, that they
appear in the order consistent with that shown above in the production
for ClassModifier.
The order doesn't matter, but you can always play around with it - there's only 6 possibilities to test.
I'm not aware of any convention, though I put the visibility modifier first (public/private/protected) so you can eyeball it and it lines up.
If it's fixed then you can do that, but I always think something is a constant only to discover later (during testing, for example) that I want to pass it in. An argument on the command line or a properties file works for that case, and is a minimum of effort to set up.