Naming convention for constant objects Java - java

For constant primitive types and data-structure like objects (Strings, Object versions of primitives) the convention seems to be full caps with underscores separating words. Does this convention carry through to things such as thread pools?
Example:
public static final int MAX_SPEED = 500;
public static final ExecutorService THREAD_POOL = Executors.newCachedThreadPool();

In Java constant variables are declared using “static final” modifiers. And such variables must contain only UpperCase charachters and multiple words must be seperated using ‘_’.
1 static final char END_OF_FILE = 'e';
2 myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Conventions was created just to improve readability of code. So its your choice to use them or leave them. But if you do use them, your code will look professional. Java Compiler does expect you to use these conventions. But there are some languages where, the way you name your variables, indicates to the compiler what type of variable it is. For instance, in Ruby, for declaring a constant variable you have to use only Uppercase for entire name of the variable. Ruby compiler identifies constant variables in that way only!
for more details
Java naming convention for static final variables

I dont think that there is any such convention or rule for this. But yes as a good practice people follow what you are doing that names are in full caps and for seperation of words using underscore.
Does this convention carry through to things such as thread pools?
Yes you can follow this.
From JLS:
6.8.5 Constant Names
The names of constants in interface types should be, and final
variables of class types may conventionally be, a sequence of one or
more words, acronyms, or abbreviations, all uppercase, with components
separated by underscore "_" characters. Constant names should be
descriptive and not unnecessarily abbreviated. Conventionally they may
be any appropriate part of speech. Examples of names for constants
include MIN_VALUE, MAX_VALUE, MIN_RADIX, and MAX_RADIX of the class
Character.
I will say it is all a matter of preference.

Related

When should we use an enum over a regular constant variable?

An enum is a specialized class that holds a set of constants. If we wanted to declare a field (variable) to be a constant in Java, we would use the keyword final. When should we use an enum over a regular constant variable?
Advantage of enum: type-safety
For example, considering the months, if we have constants as int (static final int JANUARY = 1)1 then a variable or method parameter must be declared as int and would accept any integer value , valid or not(e.g. setMonth(123) or setMonth(0)).
If we have an enum, then the variables or method parameters can only accept its values - errors (wrong constants) can be detected at compile time (exception: null which can also be assigned/passed instead of an enum, like any reference type).
1: not the same definition as from Calendar (JANUARY = 0)
Official Oracle tutorial Enum Types:
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
Enums are typically used for groups of constants that are related. For example, shirt_sizes may be an enum of Small, Medium, Large, X-Large and so on. These will always be the same and we know what they are at the time we write the program.
If you want further reading that helps to explain why we use enums, check out this article https://crunchify.com/why-and-for-what-should-i-use-enum-java-enum-examples/

Java Singleton Class Final Variable Naming Convention

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.

Coding conventions: final class instance in CAPITAL_LETTERS?

Constants (final) of primitive types should be written in CAPITAL_LETTERS. But what about a class instance? For example, when it is passed as a function parameter, is called from inner class and should be declared final. Are all parameters supposed to be final? Should it be this way then:
public static void myFunction(
final MyClass CLASS_INSTANCE) {
// Code.
}
CAPITAL_LETTERS... What about a class instance?
Nope. That would be weird. Parameters use camel case. The fact that something is final doesn't affect conventions around case.
Are all parameters supposed to be final?
No. Declare things final if they shouldn't ever change. That often applies to a parameter, but not always.
Declaring something final does two things: it helps pick up bugs where something never gets initialised or can be changed after initialisation; and it acts as a hint to the compiler to allow some optimisations.
No, final parameters should not be written in all-uppercase -- they're not constants.
The terms constant and final are not synonymous.
Uppercase is indeed used for constants, as specified by early Java naming conventions.
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_").
But not all variables declared final are constants. From the Java language specification, section 4.12.4, "Final variables":
A constant variable is a final variable of primitive type or type String that is initialized with a constant expression (§15.28).
Parameters are not constants. They're not initialized with a constant expression. And in your example, the parameter is not a primitive type or String.
Therefore, parameters are specified in mixed case, with an initial lowercase first letter.
To start with a nitpick: Java does not really have constants. It has final static variables, which -- for all intents and purposes -- often behave like constants. But they behave differently (and unexpectedly) in some rare situations, even when they have a primitive type.
Anyway, by convention, variables which behave like constants are given name in capitals. For example, java.awt.Color defines constants RED and BLUE of type Color. (It also defines constants red and blue, but since RED and BLUE were added later, I suspect the Sun/Oracle people considered those names a mistake.)
But parameters are not constants and do not behave like them. For every method invocation they can have a different value. Thus parameters are always named in camel case, even if they are declared final.
And should parameters be declared final? When, here is where convention stops and mere taste begins. Some people say yes, some people say no. I belong to the "no" camp. Making a parameter final could help prevent introducing bugs by giving a compiler error if you try to modify it. However, if your method body is so long that you actually require this help, then your method should probably be refactored. On the other side, I find parameter lists without final keywords everywhere easier to read and clearer, so I tend to leave them out.

final static variables and their use [duplicate]

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.

Generic type parameter naming convention for Java (with multiple chars)?

In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.
Something like....
Map<Key,Value>
Instead of this...
Map<K,V>
But when it comes to methods, the type-parameters look like java-classes which is also confusing.
public void put(Key key, Value value)
This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.
Alternatives I guessed or found...
Map<KEY,VALUE>
Map<TKey,TValue>
Oracle recommends the following in Java Tutorials > Generics > Generic Types:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
I'd stick to it to avoid the confusion among the developers and possible maintainers.
Append Type
A good discussion can be found in the comments on the DZone page, Naming Conventions for Parameterized Types.
See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: Append the word Type.
Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In OOP, a class essentially defines a new data type.) So call it a “Type”.
Mueller’s example, drawn from the original post’s article:
public interface ResourceAccessor < ResourceType , ArgumentType , ResultType > {
public ResultType run ( ResourceType resource , ArgumentType argument );
}
Append T
A duplicate Question provides this Answer by Andy Thomas. Note the excerpt from Google’s style guide that suggests a multi-character type name should end in a single uppercase T.
Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.
This differs from the convention suggested by Sun with the introduction of generics in 2004. However:
More than one convention exists.
Multi-character names are consistent with other Java styles, such as Google’s style for Java.
The readable names are (surprise!) more readable.
Readability
In some interfaces I wrote I’d like to name generic type parameter with more than one character to make the code more readable.
Readability is good.
Compare:
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
or, with Google’s multi-character convention:
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
Google style
The Google Java Style Guide allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT, FooBarT).
Issues
“Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.” – from the Oracle tutorials, “Generic types”
Single-character names are not the only way to distinguish type parameters from class names, as we’ve seen above.
Why not just document the type parameter meaning in the JavaDoc?
It’s true that the #param JavaDoc elements can provide a longer description. But it’s also true that the JavaDocs are not necessarily visible. (For example, there’s a content assist in Eclipse that shows the type parameter names.)
Multi-character type parameter names don’t follow the Oracle convention!
Many of Sun’s original conventions are followed nearly universally in Java programming.
However, this particular convention is not.
The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle’s in this case are minor. You and your team can choose a convention that best meets your needs.
You can use javadoc to at least give users of your generic class a clue. I still don't like it (I agree with #chaper29) but the docs help.
eg,
/**
*
* #param <R> - row
* #param <C> - column
* #param <E> - cell element
*/
public class GenericTable<R, C, E> {
}
The other thing I have been known to do is use my IDE to refactor a class breaking the convention. Then work on the code and refactor back to single letters. Makes it easier for me anyway if many type parameters are used.
The reason why the official naming convention reccommends using single letter is the following:
Without this convention, it would be difficult to tell the difference
between a type variable and an ordinary class or interface name.
I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.
Code with generic type as displayed in IntelliJ Idea 2016.1
Because of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.
Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.

Categories

Resources