JAVA default value design reason [duplicate] - java

This question already has answers here:
Why must local variables, including primitives, always be initialized in Java?
(8 answers)
Closed 6 years ago.
In JAVA world, field variables have default values if you don't initialize them, while local variables don't.
I have considered a lot and searched a lot but I still don't understand. Why does JAVA world design like that? By the way, I think it has something to do with heap and stack.

Local variables are much easier to check that a variable is always initialised in a relatively limited scope when you can determine the code paths. It doesn't always get it right but does a good job unless the code is confusing.
final fields also have to be initialised, though only once. When one constructor calls another, it can get confused.
For non final fields, it is very hard to ensure a field is initialised before it is used for all possible code paths. e.g. how can it ensure a setter is always called before a getter if those calls are made from another class which might be changed in the future.
Instead the JVM leaves default values and makes it your problem to worry about.

Well, it is very good design in my opinion.
The compiler is trying to check if programmer did not make any mistakes. Local variable should be initialized manually to avoid unexpected problems because it is usually used to do some additional calculations or actions and with default value it can be very difficult to track such a bug in the future. It is programmer responsibility to initialize local variable properly and use it in short block of code.

Related

Is it better to use local or global variables

Is it better to use local or global variables?
Let's say talking about 2000+ lines of android(java) service class, and all service is working on 'request' object and similar shared objects.
If I make everything local(keep inside of function), I need to pass many variables every time, or override same function many times. I need to make sure that objects, and sub objects are not null too.
If I make some variables global(across the class) I can share them, use them across the functions. Which I think will make everything easier.
What are the good sides and bad sides of defining variables inside of function or defining globally. In practice, and in theory(readability etc).
Is there suggested way?
Thank you.
Always prefer local over global. If you need to pass the data in as multiple parameters, so be it. At least then you're explicitly saying what data your function depends on. Having too many parameters is certainly a problem, but offloading some of them as globals isn't the answer.
If you rely on globals, it may not be as clear where certain data is coming from. If the globals are mutable, you'll have a mess on your hands as soon as you start to try to debug a difficult problem since it may not be obvious when certain global variables are being modified.
Note though that immutable constant globals aren't bad. If you have a constant that's needed in many functions (like PI for example), it makes sense to make it global. Immutable constants don't suffer from the drawbacks mentioned above since they can't change.
You wrote a 2000+ lines of service class. You completed the project. Cool ! Now after a month, you got a bug reported and are required to fix it.
Lets go through 2 different cases :
CASE 1
You are back on the service code. You see that the func1() uses globalVariabl1. Okay, but whats its value by now ? How does it change ? Who mutates the globalVariabl1 before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out.
CASE 2
You are back to you code, and see that the func0() fetches something and then passes it to func1(param1) as a parameter. You clearly know what the data is, how does it gets here.
In what case will it be easier to resolve the bug ?
Most of the time, CASE 2 will make it lot easier.
Local variables
Local variables would always help you. Even when you write the code and using local variables, the call statement will itself tell you that this function depends on this particular data. It helps you to be careful about what you are passing around.
Global variables
Global variables are okay when they represent the state of the class/object, or even when they are Constant (which should in general be all UPPERCASE letters). They can also be good when you just need to access the value frequently, and you know that the variable will always be initialised when you use it (for example initialising it inside onCreate())
There are no global variables in Java. You are referring to member variables. The basic rule is that variables should have the smallest possible enclosing scope.
I know the question is already answered and I upvoted Carcigenicate's answer.
To elaborate on his point I would suggest you try Test Driven Development practices. As soon as you start writing your code in conjunction with Unit test you will realize how bad Global variables can be and you will realize that you are writing code that cannot be tested without having to implement unnecessary Dependency Injection.
One more thing. Global variables are a huge mistake any time you start dealing with multiple threads and concurrency. It doesn't sound like you are dealing with that but keep it in mind any time you decide to make a Global variable.
It all depends on the scope of the variable. If you feel that a certain variable will take multiple values by passing through various functions then use local variables and pass them in function calls.
If you feel that a certain variable you need to use will have constant value, then declare it as a global variable.

Need to know about one PMD rule [duplicate]

This question already has answers here:
When should one use final for method parameters and local variables?
(15 answers)
Closed 10 years ago.
I use PMD tool to find errors in java code if any. One common suggestion PMD gives is that "Local variable {local_variable} could be declared final". Is it necessary to declare all local variables as final if it's state is not changed further?
Is it necessary to declare all local variables as final if it's state is not changed further?
No it is not necessary, except in one situation: if you need to access that variable within an anonymous class.
Is it good practice to make all local variable final when they don't change?
This is obviously subjective - I personally think that it clutters the code unnecessarily and that if you follow good coding practice, your methods should be short enough and self-explanatory enough that making your variables final should not be required.
Well it's also a problem of the language design to set variables explicitly to final and to have the final keyword appear all around. In scala the default is to have everything final and immutable, pushing a more functional design. If you wonder why use final, have a look at scala - that should give you some ideas.
I would consider it bad style not to use final by the way. Final variables - well or constants in that sense - cannot be changed. That is kind of a programming contract. You simply have less side-effects in code with final variables. If you leave that out you could also leave out all the private fields. Why bother?
In eclipse you can add all the required final fields and lots of other things considered "cleaner" automatically, when you open the dialog "Source/Clean Up..." (so I guess it's called "Clean Up" because not using final would be considered unclean).
It's up to you - use it - or leave it. Use it - and look especially at the code where the final could not be applied. Maybe that code could be improved to be final?
So: Yes! It is good practice!

java :Why the Local variable should be declared final [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?
I am using PMD to see the code violations.
Inside a webService Method, I have this below code
public ServiceRequest getData()
{
Status status = new Status();
// code
}
What PMD is suggesting me is that, this local variable status could be declared as final.
My question is, making it final would result in any performance improvements or if not what benefits the code could get?
Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23
clearly communicates your intent
allows the compiler and virtual machine to perform minor optimizations
clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."
This is also discussed in this question: Can excessive use of final hurt more than do good?
final indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.
I prefer to make fields final because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.
I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.
So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...

What kind of optimization does `final` enable? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Does use of final keyword in Java improve the performance?
So there's a class-level object variable that's allocated upon object creation and stays put for the lifetime of the object:
class MyClass
{
private Rect rc = new Rect();
//...
}
What do I gain be declaring it final? Same question for method-level variables.
it is all completely implementation specific.
main reason to use final is to ensure that variable value is not allowed to be change over time. it's a matter of you code logic and not optimization.
Declaring variables final does have benefits that come from immutability. If used properly your code can be more thread safe, provided the variable you're making final does not have internal state that could be changed unexpectedly and effect other threads.
See the other answers here too about JVM optimizations.
Final has one obvious use, where it makes the object/variable immutable, now can this feature help in performance gains?
Quoting: The Final Word On the final Keyword, the performance gain you get using final is:
A field doesn't need to be ever reloaded, since its value is
guaranteed never to change.
But I see a flaw in the above statement, the value won't be reloaded if it's set only once and final guarantees that it will never be reloaded again, but this does not mean using final directly helps you in performance gain, the performance gain we get here is due to the property that if we make sure we do not set the to something else, it will anyway, won't be reloaded.
So, you answer:
Although, it is implementation specific to the JVM and atleast in the HotSpot, you will get no performance gains from using final. Read more: Does use of final keyword in Java improve the performance?
IBM also says you won't get ant performance gain out of final.
This might not give you 100% answer. But i have a point which i know.
There is lot of optimization gained by the jvm when you declare variables as final.
I remember a good example where i have if-else conditions in my program and in the condition since i used final variable, complier has evaluted which part of if-else is valid and it stripped out the other lines and i have seen it with javap. I will get you that example soon.
It allows for some optimization via memoization. For example, if you have a Rectangle class with final height and final width, then your rectangle's area function only needs to compute it once, since it knows that height and width cannot change.
I doubt that final fields have a hughe impact on performance, unless you have shared object in multiple threads.
However declaring methods final or even classes will help the jit to determine wether a method can be overridden, or can't. If the jit is certain the method is no where overwritten he might remove the method lookup and use a direct jump (jump subroutine). Also Jits like to inline small final methods.
Besides the obvious compile-time protection from modifications (*) you do gain some form of optimized access to its value. The compiler may for example replace the references of primitive variables with literal values. The runtime can for example place copies of the its content in each thread's private memory space to avoid accessing main memory. It does depend on each JVM implementation.
For local variables you do again have gains, both at compile-time and at run-time, mostly in the form of thread-access optimizations. Bear in mind though, that you will only ever notice these gains in hot spots of your code, code that executes hundreds or thousands of times per second.
(*) final only protects from compile-time modifications after the introduction of Accessible Objects.

Why would one mark local variables and method parameters as "final" in Java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
In Java, you can qualify local variables and method parameters with the final keyword.
public static void foo(final int x) {
final String qwerty = "bar";
}
Doing so results in not being able to reassign x and qwerty in the body of the method.
This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.
My personal opinion is that it is a waste of time. I believe that the visual clutter and added verbosity is not worth it.
I have never been in a situation where I have reassigned (remember, this does not make objects immutable, all it means is that you can't reassign another reference to a variable) a variable in error.
But, of course, it's all personal preference ;-)
Making a parameter final guarantees that the value used at any location in the method refers to the value passed. Otherwise you have to parse mentally all the code above a given location to know what value the parameter has at that point.
Hence, not using final makes your code less readable, and maintainable, all by itself :)
Final local variables depend on intent, and is less important in my point of view. Depends on what goes on.
In the case of local variables, I tend to avoid this. It causes visual clutter, and is generally unnecessary - a function should be short enough or focus on a single impact to let you quickly see that you are modify something that shouldn't be.
In the case of magic numbers, I would put them as a constant private field anyway rather than in the code.
I only use final in situations where it is necessary (e.g., passing values to anonymous classes).
Because of the (occasionally) confusing nature of Java's "pass by reference" behavior I definitely agree with finalizing parameter var's.
Finalizing local var's seems somewhat overkill IMO.
Yes do it.
It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.
A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.
final has three good reasons:
instance variables set by constructor only become immutable
methods not to be overridden become final, use this with real reasons, not by default
local variables or parameters to be used in anonimous classes inside a method need to be final
Like methods, local variables and parameters need not to be declared final. As others said before, this clutters the code becoming less readable with very little efford for compiler performace optimisation, this is no real reason for most code fragments.
Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.
Making local variables and method parameters final is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.
Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using final ...
Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.
The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.
Edit
In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
We do it here for the local variables if we think they will not be reassigned or should not be reassigned.
The parameters are not final since we have a Checkstyle-Check which checks for reassigning parameters. Of course nobody would ever want to reassign a parameter variable.

Categories