which order is better for field declaring - java

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.

Related

Is static a useful modifier for a private string [duplicate]

This question already has answers here:
Should a private final field be static too?
(5 answers)
Closed 3 years ago.
In my team we had a small discussion if a field declared 'private static final' in a class has any advantages from just declaring it 'private final'.
For example if I have the following line in my class:
private static final String a = "a String";
Is this really better than just declaring it like this:
private final String a = "a String";
If it would be a variable that can be used outside of this class, declaring it static makes total sense. But as it is private I see no real advantage apart from a static variable being only created once and is than referenced in all objects. We have lots of tests and those define variables like this. Those tests are only run once when the system starts and are no longer needed after that. Apart from that is there anything I am missing?
In short:
You use private final when you only need to set the value once, but the value needs to be different for each instance of that class.
You use private static final when all instances of your class need to have access to one unchanging value. It is useful for avoiding magic strings / numbers and enhancing readability, particularly if your value is a longer string. If you start defining too many of these, consider moving them to a configuration file.
So static in combination with final and private is certainly useful, but staticin general requires careful, deliberate usage. Don't just slap it on everything; instead, your default action should be to analyze whether or not you need it, and implement accordingly.

when exactly are we supposed to use "public static final String"?

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.

Quick Java question about private static final keywords for fields

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.

Should a "static final Logger" be declared in UPPER-CASE?

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.

Java: refactoring static constants

We are in the process of refactoring some code. There is a feature that we have developed in one project that we would like to now use in other projects. We are extracting the foundation of this feature and making it a full-fledged project which can then be imported by its current project and others. This effort has been relatively straight-forward but we have one headache.
When the framework in question was originally developed, we chose to keep a variety of constant values defined as static fields in a single class. Over time this list of static members grew. The class is used in very many places in our code. In our current refactoring, we will be elevating some of the members of this class to our new framework, but leaving others in place. Our headache is in extracting the foundation members of this class to be used in our new project, and more specifically, how we should address those extracted members in our existing code.
We know that we can have our existing Constants class subclass this new project's Constants class and it would inherit all of the parent's static members. This would allow us to effect the change without touching the code that uses these members to change the class name on the static reference. However, the tight coupling inherent in this choice doesn't feel right.
before:
public class ConstantsA {
public static final String CONSTANT1 = "constant.1";
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
after:
public class ConstantsA extends ConstantsB {
public static final String CONSTANT1 = "constant.1";
}
public class ConstantsB {
public static final String CONSTANT2 = "constant.2";
public static final String CONSTANT3 = "constant.3";
}
In our existing code branch, all of the above would be accessible in this manner:
ConstantsA.CONSTANT2
I would like to solicit arguments about whether this is 'acceptable' and/or what the best practices are.
A class with only static fields is a code smell. It's not a class.
Some people use interfaces, so they can implement it to use the constants more easily. But an interface should be used only to model a behaviour of a class. (http://pmd.sourceforge.net/rules/design.html#AvoidConstantsInterface) Using static imports from Java 5 removes the need for simple constant usage at all.
Are your constants really Strings, or just used as Strings. If they are different options for some type (so called enumerations), you should used typesafe enumerations, using enum in Java 5 or the Enum provided by Commons Lang. Of course, converting your code to use enums might be a little work.
You should at least split the constants to groups of related constants in files with proper business name. Moving the final members is easy in IDE and will update all usages.
If you can afford it, convert them to enums then. (Think about using about a script to do that, often it's possible.) Class hierarchies are only usefull, if there is a relation between the constants/enums. You can keep the Strings if you have to but still think about them as entities, then extends might make sense for some (describing is-a relation). First enums can be simple classes made by yourself if serializing is not a problem. Enums are always favourable due to their type safe nature and the extra name showing intend or business/domain specific things.
If the constants are really String constants use a Properies or ResourceBundle, which can be configured by plain text files. Again you can script the refactoring using the constant names as resource bundle keys and generate both files automatically.
I don't like it, but it's probably the best you can do right now.
The right answer would be to break up the constants into coherent groups, fixing the code breaks as you go along. In C#, I'd use enums.
Peter Kofler has already discussed how you might wish to better organize constants. I'll share how to automate the transition:
The eclipse "Inline" refactoring can automatically replace constants by their defintion, saving you from having to hunt down and change each usage manually. So you'd simply change the code to:
public class ConstantsA {
public static final String CONSTANT1 = "constant.1";
public static final String CONSTANT2 = ConstantsB.CONSTANTFOO;
public static final String CONSTANT3 = ConstantsB.CONSTANTBAR;
}
public class ConstantsB {
public static final String CONSTANTFOO = "constant.2";
public static final String CONSTANTBAR = "constant.3";
}
... and then have eclipse inline COONSTANT2 and CONSTANT3 (while all affected projects are checked out, if you can't do that, look into refactoring scripts), and you're done.
I've seen this done by putting the static final String on an interface, so that you can 'implement' it and not have to worry about what to do when you need a different base class. It's just as accessible that way.
In general though, enums are pretty good at what you are trying to do, and may get rid of the "I'm not sure" feeling you are experiencing, as that's the intention of enums.
I think what you are doing is fine. Yes, the classes are tightly-coupled, but that is kind of the point -- you want to be able to reference only a single class to see all of your project-wide constants.
You do have to be diligent to ensure that ConstantsB contains only constants that are generalizable amongst all your projects, and ConstantsA contains only project-specific constants. If, later on, you realize that there is a constant in ConstantsB that you seem to be overriding in your subclasses a lot, then that's an indication it should've never been put in ConstantsB in the first place.
I think what you've got is a good first step. The next step is to gradually replace all references to ConstantsA.CONSTANT2 and ConstantsA.CONSTANT3 with ConstantsB.CONSTANT2 and ConstantsB.CONSTANT3 until you can remove the extends.
Most IDEs can be configured to show a warning if you refer to a superclass constant via a subclass, and I'd guess static analysis tools like FindBugs can do it, too.
One idea that might be slightly cleaner:
make all the constants classes interfaces
move all the constants out of ConstantsA and call it something like LegacyConstants
have LegacyConstants extend all the other, modular Constants interfaces
deprecate LegacyConstants
The goal would be not to have any inheritance between the Constants interfaces. LegacyConstants would be the only place there's any inheritance, it wouldn't declare any constants of its own, and when it's no longer used -- when every class that did use it instead refers to the proper Constants interface -- you've finished refactoring.
When you extract your constants, have the old class reference the constant defined in the new class. There's really no need to create an inheritance relationship here.
I could be wrong, but I don't think we need constants at all. It just means that you can't change the value of the constants and you probably should.

Categories

Resources