Private variables/methods in anonymous class? - java

I have created an anonymous class in which I declare a few variables and methods. My java teacher tells me to make these private. I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway, so I prefer to have no modifier at all. Who is right and what makes more sense? See below for example code where I choose no modifier for 'map' and 'convert' rather than making them private.
Collections.sort(list, new Comparator<String>(){
public int compare(String a, String b){
return convert(a).compareTo(convert(b));
}
Map<String, String> map = new HashMap<String, String>();
String convert(String s) {
String u = map.get(s);
if (u == null)
map.put(s, u = s.toUpperCase());
return u;
}
});

I would be tempted to make them private simply for the fact that if you refactor the code and pull the anonymous class out as a standard class (Intellij, for example, can do this at the click of a button), having private fields is what you really want. You won't have to go and rework your classes to match your standard.

Personally I would make them private (and final where possible) anyway - it's just a good habit to be in in general.
To put it another way: if you had to put an access modifier on (if, say, the keyword package was also used as an access modifier) what would you choose? Private, presumably - after all, you don't actually want to grant any other class access, do you?
Now, having decided that private is the most logically appropriate access modifier, I would make that explicit in the code.
Then again, I'd quite possibly not create an anonymous inner class with a member variable anyway - I'd be tempted to turn that into a named nested class instead.

Your professor is right.
Make all class variable private and expose them via properties (if not anonymous).
The general rule of thumb is to keep member data such as variable including your Map object private.

Default modifier is not the same as the private modifier, there're subtle differences.
However, in your case it's more a religious question whether to make convert() default or private. I don't see any advantage in making it private though.
Anyway, your code has a memory leak as the String Cache is never cleared :-P
Also, for even shorter/less code, use the Comparator String.CASE_INSENSITIVE_ORDER:
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

It really doesn't matter, but it's probably a good idea to keep your teacher happy as he/she will be grading you.

I'd say it's a matter of style. You can't access the member map outside out of the anonymous class, but it might be best to define them as private for consistency with other classes.
If this were my code, I would say that if a class is complicated enough to need data members, it might be worth pulling it out into a separate class, in which case I'd certainly make the data members private.

The key point is when you say "I don't see how changing the modifier makes any difference since these variables and methods are private to the anonymous class anyway"... you're assuming a lot about how your class is going to be used. Treat every class like it will be passed around and used in a variety of ways, in other words, use modifiers as appropriate. Besides, it makes the intent of class clear. It's not like Java is a terse language anyway, so you might as well be clear.

I don't see much benefit to marking things private just for the hell of it. It won't really gain you anything and someone reading the code might attach some significance to the choice when there really isn't any.

I would question the need for all this complexity. Take a look at: String.compareToIgnoreCase()

You want these fields to be private, so mark them private.If a member is marked neither public not private then something suspicious is going on. Also mark fields that shouldn't change final. Keeping things standardised means less thinking, or at least less thinking on the irrelevant, and less to change when modifying code.
From a language point of view, the only real difference is that if you have extended a base class in the same package, you have now hidden fields or overridden "package-private" (default access) methods. The members can also be accessed via reflection (without setAccessible) by code in the same package (this can have mobile-code security implications).

difference between default and protected.
protected:
object/method is accessible to all classes that are in the same package, and also accessible to sub/extension classes.
default:
object/method is accessible to all classes that are in the same package.
What is your intention of your object/method and code modifier accordingly.
Do not allow yourself to be confused when you come back to the code after six months because in huge projects you want to know that that object/method is or is not accessed anywhere else.
In three weeks, not just months, you would forget what the intended accessibility of those objects, 101% guaranteed. Then if you had a huge project and you had a hundred modifiers that were not specific and you desperately wanted to update the code, you would be frustrated by the compulsion to run reference check on those 100 objects/methods. May be someone took your jar and found the hidden cookies in them and used them, then you changed your code and broke someone's code.
Code your modifiers according to your intention unless you are either one or more of these:
you have no further desire to work
in large java projects.
you are a
extremely intelligent high
functioning autistic person who has
an indexed memory of every event of
your life and can write a completely functional peer-peer file sharing service
within two weeks on a lap top in a
coffee shop.
you deliberately use it
as another tool to obfuscate your
code.

Related

Why do we make private fields instead of package local

Is there any overhead when using default access level on class field in Java?
I mean "any", even nanoseconds on startup.
I heard JVM makes a graph of scopes for fields, that could be a possible reason for overhead.
I'm too lazy to write the private keyword. Is there any good reason to write private keyword instead of package-local? Package local seems to be local enough.
"is there any good reason to write private"?
Yes there is a good reason. You do not want your private members to be accessed.
See this site for a summary of the access modifiers and when and why you should use them,
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
private = it is not okay for them to be changed other than the mother class.
no modifier = it is okay for them to be changed by any class within the same package.
protected = same as no modifier + it is okay to be changed by a subclass
public = it is okay for them to be changed in general.
If you clicked the link above you would heed warning to their recommendation
Use the most restrictive access level that makes sense for a
particular member. Use private unless you have a good reason not to.
If you put no modifier you are effectively saying,
"I explicitly want other programmers to change these fields if their class is in the same package as mine."
You should always put private unless otherwise and by doing this you are saying,
"I do not want other programmers to change these fields."
You ask about elementary OOP knowledge
You see OOP has 4 basic principles
Inherritance
Abstraction
Polymorphism
Encapsulation -this is when private or protected keyword arrices on the scene
By these keywords you can restrict acces to certain fields of an object so they cant be "seen" from outside
And now for your question
I'm too lazy to write the private keyword. Is there any good reason to write private keyword instead of package-local?
Encapsulation helps the developer to make the code more flexible and maintainable .With well encapsulation implementation, one can change one part of the code easily without affecting the other part of the code.

Java Class That Has 90% Static Members. Good Practice Or What?

I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.
The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?
I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.
As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.
In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.
ADDED
I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.
There is no perfect fix, YMMV, but I'd consider a single static method, something like
World World.getWorld(String name)
and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".
Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)
It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.
Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.
Well, what you are doing is definitely an option. Or you could use a singleton pattern:
public class World {
private static World instance = new World();
private World() {
}
public static World getInstance() {
return instance;
}
}
Now just use World.getInstance() everywhere to have a unique object of this type per application.
I would say it's definitely not a good practice.
I've not seen your code, but having several static variables in a class that other classes access freely seems to indicate that you're not really using object orientation/classes but more just writing procedural code in Java. Classes should generally encapsulate/hide all their variables - static or not - from access from other classes so that other classes don't depend on how the class is implemented.
The static part also causes problems with making threads work (global variables are hard to lock in a good way so that nothing deadlocks) and with unit testing (mocking is all but impossible)
I also agree with the other posters, if you need "global variables", at least make them singletons. That allows you to change strategy easier later and does not lock you to one world.
Edit: I'm definitely not advocating singletons as a good pattern here if someone read it like that, but it does solve some problems with static variables, esp. regarding testing/mocking compared to just statics so I'd say it's a ever so slightly lighter shade of gray :) It is also a pattern that is easier to gradually replace with better patterns by for example using a IoC container.
I think it is fine as long as you don't need anything more sophisticated, in other words, static fields are OK as long as different objects (including subclasses if there will be any) do not need different values.
You code by yourself, refactoring is easy with modern tools, me says don't fix it until it is broken, and focus on the algorithmic aspects of your project.
Perhaps you may think to encapsulate all those static fields within a different static class, as it is a good principle to "keep what changes seperate from what does not". Chances are one day you will want to initiate that static class with different values, for example want to read the initial values from an XML file and/or registry, add behaviour, etc. so instead of a static class you will implement it with a Singleton pattern.
But clearly that is not the concern of today. Till then, enjoy!
You may wish to look into implementing this class as a singleton, while there is nothing particularly wrong with your approach it may lead to some inflexibility further down the road.
Also you should take in to consideration the purpose of static members which is to be a member of the class and 'act' on/with the class not an instance of it. For example the static method in a singleton returns either a new instance of the class if one doesn't already exist or returns the instance, and because the method is static you do not instantiate a new one. This is probably worth a read because it can be somewhat confusing when determining the appropriate use of static members
I'm not sure what you are really talking about from your short description, so I'll try this:
public class Level {
static List<Mushroom> mushrooms;
static List<Coin> coins;
...
}
Is that you were describing?
You asked if this is "good practice" and I can tell you that this looks very odd, so, no, it's not.
You gain absolutely nothing by doing this. You make it impossible to have more than one Level, which brings no advantage, but it could cause trouble in the future.
I didn't understand your last paragraph where you say you made most things static to save memory. You would usually create one Level and it would be passed around (without cloning) to the various classes/methods that read from it or modify it.

Why can attributes in Java be public?

As everybody knows, Java follows the paradigms of object orientation, where data encapsulation says, that fields (attributes) of an object should be hidden for the outer world and only accessed via methods or that methods are the only interface of the class for the outer world. So why is it possible to declare a field in Java as public, which would be against the data encapsulation paradigm?
I think it's possible because every rule has its exception, every best practice can be overridden in certain cases.
For example, I often expose public static final data members as public (e.g., constants). I don't think it's harmful.
I'll point out that this situation is true in other languages besides Java: C++, C#, etc.
Languages need not always protect us from ourselves.
In Oli's example, what's the harm if I write it this way?
public class Point {
public final int x;
public final int y;
public Point(int p, int q) {
this.x = p;
this.y = q;
}
}
It's immutable and thread safe. The data members might be public, but you can't hurt them.
Besides, it's a dirty little secret that "private" isn't really private in Java. You can always use reflection to get around it.
So relax. It's not so bad.
For flexibility. It would be a massive pain if I wasn't able to write:
class Point {
public int x;
public int y;
}
There is precious little advantage to hide this behind getters and setters.
Because rigid "data encapsulation" is not the only paradigm, nor a mandatory feature of object orientation.
And, more to the point, if one has a data attribute that has a public setter method and a public getter method, and the methods do nothing other than actually set/get the attribute, what's the point of keeping it private?
Not all classes follow the encapsulation paradigm (e.g. factory classes). To me, this increases flexibility. And anyway, it's the responsibility of the programmer, not the language, to scope appropriately.
Object Oriented design has no requirement of encapsulation. That is a best practice in languages like Java that has far more to do with the language's design than OO.
It is only a best practice to always encapsulate in Java for one simple reason. If you don't encapsulate, you can't later encapsulate without changing an object's signature. For instance, if your employee has a name, and you make it public, it is employee.name. If you later want to encapsulate it, you end up with employee.getName() and employee.setName(). this will of course break any code using your Employee class. Thus, in Java it is best practice to encapsulate everything, so that you never have to change an object's signature.
Some other OO languages (ActionScript3, C#, etc) support true properties, where adding a getter/setter does not affect the signature. In this case, if you have a getter or setter, it replaces the public property with the same signature, so you can easily switch back and forth without breaking code. In these languages, the practice of always encapsulating is no longer necessary.
Discussing good side of public variables... Like it... :)
There can be many reasons to use public variables. Let's check them one by one:
Performance
Although rare, there will be some situations in which it matters. The overhead of method call will have to be avoided in some cases.
Constants
We may use public variables for constants, which cannot be changed after it is initialized in constructor. It helps performance too. Sometimes these may be static constants, like connection string to the database. For example,
public static final String ACCEPTABLE_PUBLIC = "Acceptable public variable";
Other Cases
There are some cases when public makes no difference or having a getter and setter is unnecessary. A good example with Point is already written as answer.
Java is a branch from the C style-syntax languages. Those languages supported structs which were fixed offset aliases for a block of memory that was generally determined to be considered "one item". In other words, data structures were implemented with structs.
While using a struct directly violates the encapsulation goals of Object Oriented Programming, when Java was first released most people were far more competent in Iterative (procedural) programming. By exposing members as public you can effectively use a Java class the same way you might use a C struct even though the underlying implementations of the two envrionments were drastically different.
There are some scenarios where you can even do this with proper encapsulation. For example, many data structure consist of nodes of two or more pointers, one to point to the "contained" data, and one or more to point to the "other" connections to the rest of the data structure. In such a case, you might create a private class that has not visibility outside of the "data structure" class (like an inner class) and since all of your code to walk the structure is contained within the same .java file, you might remove the .getNext() methods of the inner class as a performance optimization.
To use public or not really depends on whether there is an invariant to maintain. For example, a pure data object does not restrict state transition in any fashion, so it does not make sense to encapsulate the members with a bunch of accessors that offer no more functionality that exposing the data member as public.
If you have both a getter and setter for a particular non-private data member that provides no more functionality than getting and setting, then you might want to reevaluate your design or make the member public.
I believe data encapsulation is offered more like an add-on feature and not a compulsory requirement or rule, so the coder is given the freedom to use his/her wisdom to apply the features and tweak them as per their needs.Hence, flexible it is!
A related example can be one given by #Oli Charlesworth
Accesibility modifiers are an implementation of the concept of encapsulation in OO languages (I see this implementation as a way to relax this concept and allow some flexibility). There are pure OO languages that doesn't have accesibility modifiers i.e. Smalltalk. In this language all the state (instance variables) is private and all the methods are public, the only way you have to modify or query the state of an object is through its instance methods. The absence of accesibility modifiers for methods force the developers to adopt certain conventions, for instance, methods in a private protocol (protocols are a way to organize methods in a class) should not be used outside the class, but no construct of the language will enforce this, if you want to you can call those methods.
I'm just a beginner, but if public statement doesn't exists, the java development will be really complicated to understand. Because we use public, private and others statements to simplify the understanding of code, like jars that we use and others have created. That I wanna say is that we don't need to invent, we need to learn and carry on.
I hope apologize from my english, I'm trying to improve and I hope to write clearly in the future.
I really can't think of a good reason for not using getters and setters outside of laziness. Effective Java, which is widely regarded as one of the best java books ever, says to always use getters and setters.
If you don't need to hear about why you should always use getters and setters skip this paragraph. I disagree with the number 1 answer's example of a Point as a time to not use getters and setters. There are several issues with this. What if you needed to change the type of the number. For example, one time when I was experimenting with graphics I found that I frequently changed my mind as to weather I want to store the location in a java Shape or directly as an int like he demonstrated. If I didn't use getters and setters and I changed this I would have to change all the code that used the location. However, if I didn't I could just change the getter and setter.
Getters and setters are a pain in Java. In Scala you can create public data members and then getters and or setters later with out changing the API. This gives you the best of both worlds! Perhaps, Java will fix this one day.

the use of private keyword

I am new to programming. I am learning Java now, there is something I am not really sure, that the use of private. Why programmer set the variable as private then write , getter and setter to access it. Why not put everything in public since we use it anyway.
public class BadOO {
public int size;
public int weight;
...
}
public class ExploitBadOO {
public static void main (String [] args) {
BadOO b = new BadOO();
b.size = -5; // Legal but bad!!
}
}
I found some code like this, and i saw the comment legal but bad. I don't understand why, please explain me.
The most important reason is to hide the internal implementation details of your class. If you prevent programmers from relying on those details, you can safely modify the implementation without worrying that you will break existing code that uses the class.
So by declaring the field private you prevent a user from accessing the variable directly. By providing gettters and setters you control exactly how a user may control the variable.
The main reason to not just make the variable public in the first place is that if you did make it public, you would create more headaches later on.
For example, one programmer writes public getters and setters around a private member variable. Three months later, he needs to verify that the variable is never "set" to null. He adds in a check in the "setFoo(...)" method, and all attempts to set the variable will then be checked for "setting it to null". Case closed, and with little effort.
Another programmer realizes that putting in public getters and setters around a private member variable is violating the spirit of encapsulation, he sees the futility of the methods and decides to just make the member variable public. Perhaps this gains a bit of a performance boost, or perhaps the programmer just wants to "write it as it is used". Three months later, he needs to verify that the variable is never "set" to null. He scans every access to the variable, effectively searching through the entire code base, including all code that might be accessing the variable via reflection. This includes all 3rd party libraries which has extended his code, and all newly written modules which used his code after it was written. He then either modifies all calls to guarantee that the variable is never set to null. The case is never closed, because he can't effectively find all accesses to the exposed member, nor does he have access to all 3rd party source code. With imperfect knowledge of newly written modules, the survey is guaranteed to be incomplete. Finally he has no control over the future code which may access the public member, and that code may contain lines which set the member variable to null.
Of course the second programmer could then break all existing code by putting "get" and "set" methods around the variable and making it private, but hey, he could have done that three months earlier and saved himself the explanation of why he needed to break everyone else's code.
Call it what you will, but putting public "get" and "set" methods around a private member variable is defensive programming which has been brought about by many years (i.e. decades) of experience.
Anything public in your class is a contract with the users of the class. As you modify the class, you must maintain the contract. You can add to the contract (new methods, variables, etc.), but you can't remove from it. Idealy you want that contract to be as small as possible. It is useful to make everything private that you can. If you need direct access from package members, make it protected. Only make those things public which are required by your users.
Exposing variables means that you are contracting forever, to have that variable and allow users to modify it. As discussed above, you may find you need to invoke behaviour when a variable is accessed. This can be be done if you only contract for the getter and setter methods.
Many of the early Java classes have contracts which require them to be thread safe. This adds significant overhead in cases where only one thread can access the instance. Newer releases have new classes which duplicate or enhance the functionality but drop the syncronization. Hence StringBuilder was added and in most cases should be used instead of StringBuffer.
Its considered bad mainly because you loose control over who can change the value and what happens when the value changes.
In tiny application written by you for you it won't seem that important but as you start developing for larger and larger applications having control over who changes what and when becomes critical.
Imagine from your example above, you publish library as is, other people use it, then you decide you wanted to calculate another value in your bad class when the size changes ... suddenly the bad00 class has no way of knowing and you can't change it because other people rely on it.
Instead if you had a set method you could extend it to say
void SetSize(int newSize)
{
size = newSize;
DoCalculation;
}
You can extend the functionality without breaking other peoples reliance on you.
I highly recommend the book Effective Java, it contains a lot of useful information about how to write better programs in Java.
Your question is addressed in items 13 and 14 of that book:
Item 13: Minimize the accessibility of classes and members
Item 14: In public classes, use accessor methods, not public fields
You shouldn't allow implementations to alter your records directly. Providing getters and setters means that you have exact control over how variables get assigned or what gets returned, etc. The same thing goes for the code in your constructor. What if the setter does something special when you assign a value to size? This won't happen if you assign it directly.
It's a common pet-peeve of many programmers - Java code with private fields and public accessors and mutators. The effect is as you say, those fields might as well been public.
There are programming languages that voice for the other extreme, too. Look at Python; just about everything is public, to some extent.
These are different coding practices and a common thing programmers deal with every day. But in Java, here's my rule of thumb:
If the field is used purely as an attribute, both readable and writeable by anyone, make it public.
If the field is used internally only, use private. Provide a getter if you want read access, and provide a setter if you want write access.
There is a special case: sometimes, you want to process extra data when an attribute is accessed. In that case, you would provide both getters and setters, but inside these property functions, you would do more than just return - for example, if you want to track the number of times an attribute is read by other programs during an object's life time.
That's just a brief overview on access levels. If you're interested, also read up on protected access.
This is indeed used to hide the internal implementation. This also helps is providing extra bit of logic on your variables. Say you need to make sure that the value passed for a varable should not be 0/null, you can provide this logic in the set method. Also in the same way you can provide some logic while getting the value, say you have a object variable which is not initialised and you are accessing that object, in this case you cand provide the logic to null check for that object and always return an object.
C# programmers use this equally as much, or maybe more frequently than I see in Java. C# calls it properties where in Java it is accessors/mutators
For me it makes sense to have getter and setter methods to encapsulate the classes so that no class can change the instance variables of another class.
Okay. We are talking about Objects here. The real world objects. If they are not private,the user of your class is allowed to change. What if for a Circle class, and for the radius attribute/property of the Circle class, the user sets value as '0'. It doesn't make sense for a Circle to exist with radius as '0'. You can avoid such mistakes if you make your attributes private and give a setter method and in which and throw an Exception/Error (instructing the user ) that it is not allowed to create a Circle with radisu as '0'. Basically, the objects that are created out of your class - are meant to exist as you wished to have them exist. This is one of the ways to achieve it.
As stated earlier, the reason for making a variable private is to hide it from the outside. But if you make a getter AND a setter then you may as well make the variable itself public. If you find yourself later in a position that you made the wrong choice, then you must refactor your code from using the public variable into using the getter/setter which may not be a problem. But it can be a problem if other code, which you do not control, starts depending on your code. Then such a refactoring will break the other code. If you use getters and setters from the start you will reduce that risk in exchange for a little effort. So it depends on your situation.
It depends on who access these public variables. Most likely, only by people inside your company/team. Then it's trivial to refactor them into getters/setters when necessary. I say in this case, it's better to leave the variables public; unless you are forced to follow the java bean convention.
If you are writing a framework or a library intended for the public, then you shouldn't expose variables. It's impossible for you to change them into getters/setters later.
But the 2nd case is more rare than the first; people apply extremely unreasonable assumptions when it come to software engineer, as if they are not writing code, instead they are carving code in stone. And as if the whole world is watching while you code - in reality, nobody will ever read your code except yourself

Using the "final" modifier whenever applicable 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 10 years ago.
In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.
Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.
What are your thoughts on this and what do you follow?
I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final modifiers anywhere, but when you think about it...
Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.
At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on (you can take it from me ;-)
I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final I'll do it.
Obsess over:
Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.)
Final static fields - Although I use enums now for many of the cases where I used to use static final fields.
Consider but use judiciously:
Final classes - Framework/API design is the only case where I consider it.
Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation.
Ignore unless feeling anal:
Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.
You really need to understand the full use of the final keyword before using it. It can apply to and has differing affects on variables, fields, methods and classes
I’d recommend checking out the article linked to below for more details.
Final Word On the final Keyword
The final modifier, especially for variables, is a means to have the compiler enforce a convention that is generally sensible: make sure a (local or instance) variable is assigned exactly once (no more no less). By making sure a variable is definitely assigned before it is used, you can avoid common cases of a NullPointerException:
final FileInputStream in;
if(test)
in = new FileInputStream("foo.txt");
else
System.out.println("test failed");
in.read(); // Compiler error because variable 'in' might be unassigned
By preventing a variable from being assigned more than once, you discourage overbroad scoping. Instead of this:
String msg = null;
for(int i = 0; i < 10; i++) {
msg = "We are at position " + i;
System.out.println(msg);
}
msg = null;
You are encouraged to use this:
for(int i = 0; i < 10; i++) {
final String msg = "We are at position " + i;
System.out.println(msg);
}
Some links:
The final story (free chapter of the book "Hardcore Java")
Some final patterns
Definite assignment
I'm pretty dogmatic about declaring every possible variable final. This includes method parameters, local variables, and rarely, value object fields. I've got three main reasons for declaring final variables everywhere:
Declaring Intention: By declaring a final variable, I am stating that this variable is meant to be written to only once. It's a subtle hint to other developers, and a big hint to the compiler.
Enforcing Single-use Variables: I believe in the idea that each variable should have only one purpose in life. By giving each variable only one purpose, you reduce the time it takes to grok the purpose of that particular variable while debugging.
Allows for Optimization: I know that the compiler used to have performance enhancement tricks which relied specifically on the immutability of a variable reference. I like to think some of these old performance tricks (or new ones) will be used by the compiler.
However, I do think that final classes and methods are not nearly as useful as final variable references. The final keyword, when used with these declarations simply provide roadblocks to automated testing and the use of your code in ways that you could have never anticipated.
Effective Java has an item that says "Favour immutable objects". Declaring fields as final helps you take some small steps towards this, but there is of course much more to truly immutable objects than that.
If you know that objects are immutable they can be shared for reading among many threads/clients without synchronization worries, and it is easier to reason about how the program runs.
I have never been in a situation where having a final keyword on a variable has stopped me from making a mistake, so for the moment I think it's a giant waste of time.
Unless there is a real reason for doing it (as in you want to make a specific point about that variable being final) I would rather not do it since I find it makes the code less readable.
If, however, you don't find it makes the code harder to read or longer to write then by all means go for it.
Edit: As a clarification (and an attempt to win back down-votes), I'm not saying don't mark constants as final, I'm saying don't do stuff like:
public String doSomething() {
final String first = someReallyComplicatedExpressionToGetTheString();
final String second = anotherReallyComplicatedExpressionToGetAnother();
return first+second;
}
It just makes code (in my opinion) harder to read.
It's also worth remembering that all final does is prevent you from reassigning a variable, it doesn't make it immutable or anything like that.
Final should always be used for constants. It's even useful for short-lived variables (within a single method) when the rules for defining the variable are complicated.
For example:
final int foo;
if (a)
foo = 1;
else if (b)
foo = 2;
else if (c)
foo = 3;
if (d) // Compile error: forgot the 'else'
foo = 4;
else
foo = -1;
Sounds like one of the biggest argument against using the final keyword is that "it's unnecessary", and it "wastes space".
If we acknowledge the many benefits of "final" as pointed out by many great posts here, while admitting it takes more typing and space, I would argue that Java should have made variables "final" by default, and require that things be marked "mutable" if the coder wants it to be.
I use final all the time for object attributes.
The final keyword has visibility semantics when used on object attributes. Basically, setting the value of a final object attribute happens-before the constructor returns. This means that as long as you don't let the this reference escape the constructor and you use final for all you attributes, your object is (under Java 5 semantics) guarenteed to be properly constructed, and since it is also immutable it can be safely published to other threads.
Immutable objects is not just about thread-safety. They also make it a lot easier to reason about the state transitions in your program, because the space of what can change is deliberately and, if used consistently, thoroughly limited to only the things that should change.
I sometimes also make methods final, but not as often. I seldomly make classes final. I generally do this because I have little need to. I generally don't use inheritance much. I prefer to use interfaces and object composition instead - this also lends itself to a design that I find is often easier to test. When you code to interfaces instead of concrete classes, then you don't need to use inheritance when you test, as it is, with frameworks such as jMock, much easier to create mock-objects with interfaces than it is with concrete classes.
I guess I should make the majority of my classes final, but I just haven't gotten into the habbit yet.
I have to read a lot of code for my job. Missing final on instance variables is one of the top things to annoy me and makes understanding the code unnecessarily difficult. For my money, final on local variables causes more clutter than clarity. The language should have been designed to make that the default, but we have to live with the mistake. Sometimes it is useful particularly with loops and definite assignment with an if-else tree, but mostly it tends to indicate your method is too complicated.
final should obviously be used on constants, and to enforce immutability, but there is another important use on methods.
Effective Java has a whole item on this (Item 15) pointing out the pitfalls of unintended inheritance. Effectively if you didn't design and document your class for inheritance, inheriting from it can give unexpected problems (the item gives a good example). The recommendation therefore is that you use final on any class and/or method that wasn't intended to be inherited from.
That may seem draconian, but it makes sense. If you are writing a class library for use by others then you don't want them inheriting from things that weren't designed for it - you will be locking yourself into a particular implementation of the class for back compatibility. If you are coding in a team there is nothing to stop another member of the team from removing the final if they really have to. But the keyword makes them think about what they are doing, and warns them that the class they are inheriting from wasn't designed for it, so they should be extra careful.
Another caveat is that many people confuse final to mean that the contents of the instance variable cannot change, rather than that the reference cannot change.
Even for local variables, knowing that it is declared final means that I don't need to worry about the reference being changed later on. This means that when debugging and I see that variable later on, I am confident that it is referring to the same object. That is one less thing I need to worry about when looking for a bug.
A bonus is that if 99% of variables are declared final, then the few variables which really are variable stand out better.
Also, the final lets the compiler find some more possible stupid mistakes that might otherwise go unnoticed.
Choosing to type final for each parameter in each method will produce so much irritation both for coders and code readers.
Once irritation goes beyond reasonable switch to Scala where arguments are final by default.
Or, you can always use code styling tools that will do that automatically for you. All IDEs have them implemented or as plugins.
Final when used with variables in Java provides a substitute for constant in C++. So when final and static is used for a variable it becomes immutable. At the same time makes migrated C++ programmers pretty happy ;-)
When used with reference variables it does not allow you to re-reference the object, though the object can be manipulated.
When final is used with a method, it does not allow the method to be over-ridden by the subclasses.
Once the usage is very clear it should be used with care. It mainly depends on the design as using final on the method would not help polymorphism.
One should only use it for variables when you are damn sure that the value of the variable will/should never be changed. Also ensure that you follow the coding convention encouraged by SUN.for eg: final int COLOR_RED = 1; (Upper case seperated by underscore)
With a reference variable, use it only when we need a an immutable reference to a particular object.
Regarding the readability part, ensue that comments play a very important role when using the final modifier.
I never use them on local variables, there is little point for the added verbosity. Even if you don't think the variable should be reassigned, that will make little difference to the next person altering that code that thinks otherwise, and since the code is being changed, any original purpose for making it final may no longer be valid. If it is just for clarity, I believe it fails due to the negative effects of the verbosity.
Pretty much the same applies to member variables as well, as they provide little benefit, except for the case of constants.
It also has no bearing on immutability, as the best indicator of something being immutable is that it is documented as such and/or has no methods that can alter the object (this, along with making the class final is the only way to guarantee that it is immutable).
But hey, that's just my opinion :-)
I set up Eclipse to add final on all fields and attributes which are not modified. This works great using the Eclipse "save actions" which adds these final modifiers (among other things) when saving the file.
Highly recommended.
Check out my blog post of Eclipse Save Actions.
For arguments I'm think they're not needed. Mostley they just hurt readabillity. Rreassigning an argument variable is so insanely stupid that I should be pretty confident that they can be treated as constants anyway.
The fact that Eclipse colors final red makes it easier to spot variable declarations in the code which I think improves readbillity most of the time.
I try to enforce the rule that any and all variables should be final it there isn't an extremley valid reason not to. It's so much easier to answer the "what is this variable?" question if you just have to find the initilization and be confident that that is it.
I actually get rather nervous around non-final variables now a days. It's like the differnce between having a knife hanging in a thread abouve your head, or just having it you kitchen drawer...
A final variable is just a nice way to lable values.
A non-final variable is bound to part of some bug-prone algorithm.
One nice feature is that when the option to use a variable in out of the question for an algorithm most of the time the sollution is to write a method instead, which usually improves the code significantly.
I've been coding for a while now and using final whenever I can. After doing this for a while (for variables, method parameters and class attributes), I can say that 90% (or more) of my variables are actually final. I think the benefit of NOT having variables modified when you don't want to (I saw that before and it's a pain sometimes) pays for the extra typing and the extra "final" keywords in your code.
That being said, if I would design a language, I would make every variable final unless modified by some other keyword.
I don't use final a lot for classes and methods, thought. This is a more or less complicated design choice, unless your class is a utility class (in which case you should have only one private constructor).
I also use Collections.unmodifiable... to create unmodifiable lists when I need to.
Using anonymous local classes for event listeners and such is a common pattern in Java.
The most common use of the final keyword is to make sure that variables in scope are accessible to the even listener.
However, if you find yourself being required to put a lot of final statements in your code. That might be a good hint you're doing something wrong.
The article posted above gives this example:
public void doSomething(int i, int j) {
final int n = i + j; // must be declared final
Comparator comp = new Comparator() {
public int compare(Object left, Object right) {
return n; // return copy of a local variable
}
};
}
I use it for constants inside and outside methods.
I only sometimes use it for methods because I don't know if a subclass would NOT want to override a given method(for whatever reasons).
As far as classes, only for some infrastructure classes, have I used final class.
IntelliJ IDEA warns you if a function parameter is written to inside a function. So, I've stopped using final for function arguments. I don't see them inside java Runtime library as well.
I hardly use final on methods or classes because I like allowing people to override them.
Otherwise, I only use finally if it is a public/private static final type SOME_CONSTANT;
Marking the class final can also make some method bindings happen at compile time instead of runtime.
Consider "v2.foo()" below - the compiler knows that B cannot have a subclass, so foo() cannot be overridden so the implementation to call is known at compile time. If class B is NOT marked final, then it's possible that the actual type of v2 is some class that extends B and overrides foo().
class A {
void foo() {
//do something
}
}
final class B extends A {
void foo() {
}
}
class Test {
public void t(A v1, B v2) {
v1.foo();
v2.foo();
}
}
Using final for constants is strongly encouraged. However, I wouldn't use it for methods or classes (or at least think about it for a while), because it makes testing harder, if not impossible. If you absolutely must make a class or method final, make sure this class implements some interface, so you can have a mock implementing the same interface.

Categories

Resources