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.
Related
In my codebase, I found a class like this:
public final class Klass
{
private static final long LONG_NUMBER = 10.0;
private Klass() {}
public static double calcSomethingUsingLongNumberAndParam(double param)
{
...
return something;
}
}
My IDE (IntelliJ IDEA) offers one 'improvement' to this class - change it to an enum. As a test, I made the change, and noted no other refactors done on any of the member fields or methods, not to any calls to the static methods contained.
Here is the generated Enum:
public enum Klass
{
;
private static final long LONG_NUMBER = 10.0;
private Klass() {}
public static double calcSomethingUsingLongNumberAndParam(double param)
{
...
return something;
}
}
Is there a benefit to changing a final class to an enum, or is this a quirk of the IDE?
My answer originally said that sure there are benefits, enums supersede old-style POJO singletons (which this is a special case of) in almost every way. However, it depends a bit on the use case and actual code involved. If you just replace "final class" with "enum", as IDE seems to be doing in this case, the benefits are minimal. Also, one of the main benefits of using enum is a better type checking for finite values, but since you seem to be using only a single, numeric value and it is private, it's of no benefit here.
Pros on using an enum vs. constant utility class:
Enums get away with almost the same functionality with less code - you don't need to declare functions or values as static, nor do you need a private constructor, which are just boilerplate that enum offers out of the box
it is immediately clear with enums that they are not meant to be instantiated, whereas for a class like this, it might need more investigation and a look at its details as a whole
with a class like this it is far easier for someone updating the code to mess up the singleton pattern by accident if he/she doesn't notice it's meant to be that way
Cons:
enum class itself are effectively final, but their internal design depends on the possibility to make subclasses for the enum values, so their protection from subclassing seems to me a bit hacky.
So, if this class is part of interface offered as an external library and we can be quite confident no one will change its own implementation, it is actually a bit more safe than using an enum here. However, if this code is maintained (especially by different developers) - and any code should be, I would argue an enum has more pros to offer, as it more clearly communicates its intent. Even the only con I could come up with, removal of protection from subclassing, seems quite marginal as enums are effectively final anyway outside their defining class.
For more discussion on the benefits of enums, see What are enums and why are they useful?. There is also another discussion on the benefits of having a final keyword in a constant utility class such as yours: Final Keyword in Constant utility class - the conclusion I get from that discussion is that the only benefit is that it is explicitly forbidden to subclass it, which wouldn't work anyway since you wouldn't be able to override the static stuff.
TLDR; recommendation to replace with enum seems reasonable, at least if you omit the things you don't have to explicitly declare with enums. However the differences are related to the readability and maintainability, not any difference in behaviour.
There is no outright benefit to changing this class to an enum.
The only thing it affords you is the ability to omit the private constructor (and the final on the class).
But you'd also need either a single value (that you don't need), or just have a random hanging ; to separate the (empty) value list from the rest of the class body.
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.
From time to time I see something like this:
class Clazz {
private int _goodName;
private int _anotherGoodName;
...
}
I don't get it. It's hard and unusual to read such code. What are the pros?
It's a naming convention used by some people to indicate "these are private variables".
Personally I'm not a fan as I think you can leave off the underscore and achieve the same result, but to each his own. I think it may have it's roots in pre-IDE days when you might be viewing a method and the visibility/ownership of certain variables is not always clear.
The examples of members and methods prefixed with an underscore I've seen use the convention to indicate that you shouldn't touch that member or method, when you can't make it private. I read it as 'here be dragons', never had a reason to use it myself.
An example is the _jspService() method in servlet development. Check out the linked JavaDocs.
It's just a matter of preference. Some people like to add a '_' to all private members variables of a class, other's dont. I personally do not like it but again it's preference.
Naming conventions are all about what's comfortable for the person writing the code to read/replicate (though they should be about whats easy for everyone to read)
I have a friend who uses this convention along with something like:
private int m_myVariable;
for all of his fields etc. It denotes it as a member of the particular class you're looking in but it gets very very annoying to read if you don't do the same.
If it is a likely scenario that you could have a member variable, a property and a parameter all refer to the same thing, it makes perfect sense to distinguish:
private string _myVariable;
public MyClass(string myVariable)
{
//do stuff.
_myVariable = myVariable;
}
public string MyVariable
{
get
{
return _myVariable;
}
}
I used to use these conventions in my code:
Non-final, static fields begin with an underscore.
private static SomethingOrOther _goodName;
Parameters end with an underscore.
public void doSomething(Object goodParam_, String stringToo_) {
}
And while you may consider it hard to read in the declaration of the variable, the point is to make sure they pop when reading the code in which they're used and to ensure that they are always different than any non-static fields, parameters and locally defined variables.
Another benefit of standards like this, i think, is when others come along to modify the code, they can quickly identify static fields and parameters which makes comprehension of the code happen more readily rather than having to always refer back to definitions.
I don't generally consider a convention for instance fields because access to them is almost exclusively through s/getters.
I've moved away from this with Java code, preferring instead to have my IDE always fully qualify with this for instance fields and with the class name for static fields and always using final on every variable that doesn't change, even method parameters. The interesting thing about going this route is that it encourages good naming practice, at least for me, because i like my variables to read nicely when prefixed with this or the class name.
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.
In Java, when should static non final variables be used?
For example
private static int MY_VAR = 0;
Obviously we are not talking about constants here.
public static final int MY_CONSTANT = 1;
In my experience I have often justified them when using a singleton, but then I end up needing to have more than one instance and cause myself great headache and re-factoring.
It seems it is rare that they should be used in practice. What do you think?
Statistics-gathering might use non-final variables, e.g. to count the number of instances created. On the other hand, for that sort of situation you probably want to use AtomicLong etc anyway, at which point it can be final. Alternatively if you're collecting more than one stat, you could end up with a Statistics class and a final reference to an instance of it.
It's certainly pretty rare to have (justifiably) non-final static variables.
When used as a cache, logging, statistics or a debug switch are the obvious reasonable uses. All private, of course.
If you have mutable object assigned to a final field, that is morally the same as having a mutable field.
Some languages, such as Fan, completely disallow mutable statics (or equivalent).
In my experience static non-final variables should only be used for singleton instances. Everything else can be either more cleanly contained by a singleton (such as a cache), or made final (such as a logger reference). However I don't believe in hard and fast rules, so I would take my advice with a grain of salt. That said I would suggest carefully examining any case where you consider declaring a non-final static variable aside from a singleton instance and see if it can be refactored or implemented differently -- i.e. moved into a singleton container or use a final reference to a mutable object.
Static variables can be used to control application-level behaviour, for example specifying global logging level, server to connect with.
I've met such use cases in old appliations, usually coming from other companies.
Nowadays using static variables for such purposes is obviously bad practice, but it wasn't so obvious in, say, 1999. No Spring, no log4j, no Clean code from R.C.Martin etc.
Java language is quite old now, and even if some feature is strongly discouraged now, it was often used in the beginnings. And because of backward compatibility it's unlikely to change.
I think wrapping your statics and providing access via singletons (or at a minimum via static methods) is generally a good idea, since you can better control access and avoid some race condition and synchronization issues.
A static variable means that it is available to the class as a whole so both examples are available to the class as a whole. Final means that the value cannot be changed. So I guess the question is when do you want to a value to be available to an entire class and it cannot be changed after it has been instantiated. My guess would be a constant available to all instantiations of that class. Otherwise if you need something like a population counter then the non-final variable.
Personally for class non-final variables I use the CamelCase notation. It is clear from code that it is a class variable since you have to reference it as such: FooBar.bDoNotRunTests.
On that note, I prefix class instance variables with the this to distinguish them from local scope variables. ex. this.bDoNotRunTests.