Coding conventions: final class instance in CAPITAL_LETTERS? - java

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.

Related

What is true reason for initiliazing need of final varibles before use

I know that:
A blank final class variable must be definitely assigned by a static initializer of the class in which it is declared, or a compile-time error occurs.
A blank final instance variable must be definitely assigned at the end of every
constructor of the class in which it is declared, or a compile-time error occurs.
Why final variable cannot be assigned just once at any time instead of just at declare time?
The corollary to this, for non-final variables, is the initial value of a variable. Every field receives an initial value depending on its type - usually a variant of 0 or null.
It's implied here that, if you're declaring a variable to be final, then you have a specific value in mind that you wish that variable to be assigned and not have changed later in its run. Java doesn't know what value that is, and it likely takes away the convenience of automatically declaring those values for you so to not interfere with the developer's intentions.
That and requiring that all final variables be initialized is to support all variables being definitely assigned before their use. You can use a non-final field that you don't initialize to some value - it'll likely be null though - but you can't use a local variable that you haven't initialized yet for the same reason.
First it is not something against null. The following is legal too:
final String ABC;
{
ABC = null;
}
static final String DEF;
static {
DEF = null:
}
final String GHI = null;
It was the following decision:
When a final field or a local variable is not initialized it can very
well be a bug, forgetting to initialize.
(For normal fields it would be too much boiler code, and zeroing of fields is provided.)
For local variables you might find this obvious. As final variables can only be assigned once, and it was decided that this should happen only during construction (otherwise you would need administration of whether the variable was initialized).
Language design decisions are always a trade off between flexibility and error prevention. In this case, there are some simple questions to check:
In case, there is a code path in which a final variable is not assigned:
How likely is it that the developer declares a final variable just to hold the default value, null, 0 or false?
In contrast, how likely is it that the developer has forgotten the initialization or overlooked a possible code path, in other words, rejecting this code prevents a nasty bug?
How much work is it for the developer, to write the explicit assignment, if (s)he really wants the default value?
I think, trying to answer these questions should lead to the rationale behind this design decision.
This is the place for an important clarification. In case of local variables, all variables must be initialized before use. The restriction is only lifted for non-final heap variables, read, fields and array elements.
In case of arrays, it should be obvious why developers are not enforced to write explicit default values when arrays can be instantiated for lengths up to 2³¹ elements. For non-final instance fields, this decision can be discussed. But such a discussion would be outside the scope of Stackoverflow…

Naming convention for constant objects 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.

Why shouldn't all function arguments be declared final?

Ok, so I understand why we should declare an argument to be final from this question, but I don't understand why we shouldn't...
Since Java always uses pass by value, this means that we can't return a new value through the given argument, we can only overwrite it, and make the argument useless therefore, because we don't use the passed value...
Is the only benefit of non-final method arguments in Java the fact that you don't have to make a local variable of the arguments' type?
P.S. This question was triggered by PMD's rule of MethodArgumentCouldBeFinal
I can think of only 2 reasons not to make a parameter final:
to save the use of a local variable if you need to overwrite the parameter's value in some edge cases (for instance to put a default if the param is null etc.).
However, I wouldn't consider that a good practice in general.
to save 6 characters per parameter, which improves readability.
Reason 2 is what leads me not to write it most of the time. If you assume that people follow the practice of never assigning a new value to a parameter, you can consider all parameters as implicitly final. Of course, the compiler won't prevent you from assigning a parameter, but I can live with that, given the gain in readability.
It prevents you from making unintentional error in your code. Rule of thumb here is to make each field and each function argument you know you shouldn't change (I mean reference, you still can change value) in your code as final.
So basically its a mean to prevent programmer from shooting their foot. Nothing more.
Whether you've to declare a local variable final or not (method parameter comes under this), is more of the requirement than a convention. You'll not get a certain answer saying you should always use final or you should never use final. Because that is really a personal preference.
I personally mark the parameters or local variables final when I really don't want their values to be changed, and it even shows my intention to other developers not to overwrite the values. But I don't do it for every parameters. Also for some, using final seems to be noise, as that really increases the code base.
Rule of thumb: Don't use it.
Final cannot stop you changing objects, only its reference, and this is because objects in java are, usually, not inmutable.
Take a look to this code:
class Example{
// think about this class as a simple wrapper, a facade or an adapter
SomeClass inner = new SomeClass();
setInnet(Someclass inner){
this.inner = inner;
}
// delegate methods.....
}
Now, in a method:
private void (final Example examp){
....
examp will be always the same object, but inner can vary... And inner is the important object here, the one which makes everything!
This may be an extreme example, and you may think that inner could be final but, if it's a utillery class, maybe it shouldn't. Also it's easy to find a more common example:
public void (final Map map){;
....
//funny things
....
//and then, in a line, someone does:
map.clear()
// no we have the same reference... but the object has change...
....
So, my point against final in arguments is that it's not guaranteed that all the code inside a final class is inmutable and so the final word can end lying you and mascarading a bug...
By putting final in params you can only show wishes, not facts, and for that you should use comments, not code. Moreover: it's a standar (de facto) in java that all arguments are only input arguments (99% of the code). Thus, final word in params is NOISE because it exists and means nothing.
And I don't like noise. So I try to avoid it.
I only use final word to mark the inner variables that will be used in an anonymous inner class (you can avoid marking it if they are effectively final, but it's cleaner and more readable).
UPDATED
final means 'assigned once' which in applied to method arguments means nothing in a program's logic nor in its design.
You can assign the arguments to a new object inside a method and outside there will not be any change.
The only difference putting final in arguments will be that you will not be able to assign that entities to another objects. Assigning arguments is something which may be ugly and something to avoid but its only a style problem and, at that point, the style problem should be the assignation itself and not the ausence of 'final' word.
I think that final is useless in arguments (and so, noise), but if someone is able to find a use of it I'll be happy to learn it. What can I achieve putting 'final' that cannot achieve without putting it?

Why do we declare constants, and is it necessary to make them static?

I know that constants are those variables whose values cannot be changed, but if no part of the program changes their value, are they still required to be declared final? And it also seems that they must be static. Why is that?
You are actually asking several questions at once which I am trying to answer.
Why use constants at all?
Constants are used to avoid magic numbers/strings in your code. If you have a string that appears in several occasions of your code, once you have to change that string you only need to change the constant definition and not every occurrence of the string in your code. Also if a constant is only used once it is often a good thing because of its better visibility.
The final keyword.
Its purpose (at least in this context) is twofold. One is to make it impossible to a programmer to change the value. You might have forgotten that it is a constant. The other is to tell the compiler that the value cannot change at runtime. This can be used to create optimized bytecode (e.g. the constant could be removed and every occurrence replaced by its value by the compiler).
The static keyword.
In Java everything is a Class. And every Class can have several instances (objects). If you dont mark your constant as static then every object has "its own constant". Since you dont want that it makes sense to mark it as static. Static fields (or methods) do exist only once per class (as opposed to once per object of the class).
It is certainly possible to declare non-static finals:
class Employee {
final String empId;
public Employee(String empId) { this.empId = empId; }
}
In other cases you want the field to be constant across all instances of the class:
class Color {
final static int BLACK = 0xFFFFFF;
}
As to why you want to declare them final at all instead of just not changing them ever,
It increases program readability, it tells the reader of program something about its behavior that would otherwise have to be in documentation
Compiler reminds if you attempt to change it by mistake
Because static belongs to class rather than any instance.
When it is static single copy shared across all the instances. Where as instance member have the individual copy.
consider you need to increase/decrease game score (count), in each stage (Stage class) of your game.
Normally when you're going to use a constant value on your code, you declare a final static variable. That prevents you from spreading "magic values" around the code, which is not a good practice, for mantainability and legibility reasons.
If you don't declare them final, code made by other people (or you, in case you forget your initial intention) may modify the variable.
If you don't declare them static, every instance of the class you create will have a copy of it, also you'll have to create an instance to get the value. That's not what you want, usually.
We declare constants because we will always need some "magic numbers" that are fixed in the code. Using constants means that they are easier to spot, and that when you change them you will change all of them with a edit.
Imagine that your code defines that your window will show 15 records, and that you will consider people as adults when they are 15 years old. Without constants, changing the size of the windows means that you will have to find the 15 ocurrences, do not miss any, and do not change a 15 that means age by mistake.
The static part is because you do not want to instantiate an object to get a data that is not related to a particular instance (that is exactly what static means, btw, not only when used for constants).
It's not strictly necessary, but it's recommended for reasons of memory-efficiency:
If you don't declare your constant as static every instance of the class (possibly thousands of them) that is created will keep it's own value of (or at least a reference to) that constant in memory, whereas a static member is only kept once per class - and since it's constant anyway, that's sufficient.

Can the methods in an Enum type change the state of the instances of an Enum?

If Enums are an answer for getting rid of compile time constants , why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums ? Those methods can never change the state of the Enum instances or can they ? If they are allowed to change the state , then the invariant of an Enum type ie some type that exports a few constants will break IMHO.
Java enums are really just classes with some special treatment by the compiler and runtime. So yes, method calls on an enum instance can certainly change its state. I'm not sure what you mean with "then the invariant of an Enum type ie some type that exports a few constants will break".
Who says enums can only be a bunch of constants? The essence of an enum type is that you have a predefined fixed number of instances which you can refer to by name - and Java enums implement that. But why would a language not be allowed to have enums that are more powerful than that?
If you don't want the extra power, nobody forces you to use it. You can have Java enums without fields or methods, and they'll behave pretty much exactly like C enums.
Enums are compile-time constants, but their members aren't. It's usually not a good idea to change enum members at runtime, but it is possible. For this reason, you can't use an enum's members where compile-time constants are called for (e.g. in annotation parameters).
Hardly anything in Java is really a constant when you go try hard to mess things up. E.g. a String constant contains a char array. Arrays are not immutable. Here's an example of the mess you can make using inlined String constants:
public static void main(final String[] args) throws Exception {
final Field valueField = String.class.getDeclaredField("value");
valueField.setAccessible(true);
System.arraycopy("frog".toCharArray(), 0,
(char[]) valueField.get(Boolean.TRUE.toString()), 0, 4);
System.out.println(Boolean.parseBoolean("frog")); // true
System.out.println(Boolean.parseBoolean("true")); // false
}
So, Java constants in most cases are just constants as long as your application is well-behaved.
why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums
Reasons are to allow replacing switch-statements with polymorphism and generally make programs more Object Oriented by allowing to define methods on the data.
Search for "type-safe enum pattern". Java Enums are an implementation of this design pattern on language level.

Categories

Resources