Splitting Declaration and Assignment = Good Practice? [closed] - java

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 9 years ago.
Being an avid user of NetBeans, I keep getting suggestions to split my variable declarations and assignments when I introduce a new variable. As a super quick example off the top of my head, let's take this Java line:
String someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
versus:
String someInput;
someInput = JOptionPane.showInputDialog(null, "- Enter something: ");
NetBeans seems to prefer the latter (I wouldn't know about other IDEs, though). While it clearly works both ways, which would be considered 'good practice', if at all? Or s it purely a matter of personal preference?
(Obviously splitting the two means an extra line that you could've just combined into one, but that's beside the point.)

There's no reason to split the declaration and the assignment if you're just going to have them on consecutive lines. I'd only split them if the assignment were conditional, or if it needed to go in a separate code block (like a try/catch, or if the assignment goes in a constructor, etc.).

A common pattern that traces back to early statically typed programming is to declare all the variables you need at the top of the block they need to be scoped in, and then assign to those values subsequently.
With that said, as long as you're able to clearly communicate the intent of your code to the people you work on it with, or yourself in a year's time, it shouldn't really matter.
Let us change our traditional attitude to the construction of programs: Instead of imagining that our
main task is to instruct a computer what to do, let us
concentrate rather on explaining to human beings what
we want a computer to do. -- Donald Knuth

This was an option added to NetBeans somewhere between 7.0 and 7.3. If you don't like this hint it can be changed by unchecking:
Tools > Options > Editor > Hints > Suggestions > Split Declaration

Netbeans suggests this as it can speed up coding, for example consider this assignment
final String myString = "somevalue"
You then decide that actually the value depends on some boolean
final String myString;
if(something) {
myString = "somevalue"
} else {
myString = "someothervalue"
}
To convert one from to the other you can use the code hint to spilt declaration and assignment and the if...else template to generate the code in very few steps.
In general if you are assigning unconditionally then there is not reason to split declaration and assignment.

I don't think it's a big deal. Pick a style you like, and stick to it throughout (if you're in a team, it helps if everyone is laying out their code similarly).
I personally prefer to initialize my variables right at the point of declaration. For that reason, I would prefer the former over the latter.

Code Complete, which is well regarded by most of the programming community, suggests in its page 241 that as a matter of defensive programming you can either initialize each variable as it's declared (your first option) or initialize it close to where it is first used (your second option).
Nevertheless, the book suggests that the second option is better because if you use the first option, your variable may have changed between its declaration and its usage.
In your case, the difference between declaration and usage in the second case is a single line. Hence, the book's concerns do not apply. Nevertheless, its concerns are legitimate and this may be the reason Netbeans designers included this tip (even though they overused it).

Related

Questions about Java code styles [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.
So I have seen a lot of different coding styles, but I'm only going to talk about two big ones. I use a style where I just name everything like their class name when used in a general sense, like this:
String str = "This is some text";
But over at Java Practices, I see a style where they will put an 'I' in front of Interfaces class names, or they put 'f' or 'a' in front of object names. Take this snippet from "Don't subclass JDialog or JFrame"':
/**
Constructor.
<P>Called when adding a new {#link Movie}.
*/
MovieView(JFrame aParent) {
fEdit = Edit.ADD;
buildGui(aParent, "Add Movie");
fStandardDialog.display();
}
Why do programmers code in this style? Do a lot of people use it? And also, do professional programmers use this style?
Thanks in advance :)
This my personal opinion.
I prefer not to use prefixes on interface (or anything else for that matter). I just prefer to call it what it is. Interfaces are meant to represent an object (or part of it) without making any implication towards it's actual implementation.
Say you have a Car interface. And AudiA4 could be an implementation of that car. If you just bought a new Audi A4, you say, "I bought a new AudiA4" to those you think care about the kind of car you bought. To others, you can say "I bought a new Car". Certainly, you never say, I bought a new IAudiA4 or a new ICar.
The JFrame naming came about because it's a Swing Frame and Swing came after AWT (the original Java windowing toolkit, which already had a Frame class). Since both AWT and Swing where available at the same time, they used the 'J' prefix to demarcate the toolkits (note that JFrame extends Frame, btw). They could have called it SwingFrame but the 'J' prefix was apparently a good choice to represent the Swing package. So basically this prefix is just a naming choice, not a convention similar to the 'I' for interfance (or Impl suffix for implementations you see sometimes as well)
My point is you always have to name your classes and interface according to exactly what they represent. No more, no less. No point having a CarImpl class. Who cares that it's an implementation. Which implementation is it? Why does it need its own class? What more do I get when I use a CarImpl? What happens when I make a second implementation, I call it CarImpl2? All this is very constraining and doesn't bring much value.
Call it what it is. That's the only rule I'd set forth.
All this being said, the Eclipse project, amongst many others, does indeed use the I-for interface notation (WIKI). But it's their choice. I've seen professionals use it as well. I don't like it, but generally speaking, I respect the team's naming convention.
There is a book about such things - Code Complete by Steve McConnell
I might be wrong but the only universal convention I've seen when naming Java variables is using Camel-Case notation, that's regarding the format of the name.
As for the name itself, I've always found useful to name the variables according to what they actually are. In your String example, although you mention this would be in a general purpose variable, I would still give it a more meaningful name, like:
String message = "This is some text";
Or:
String msg = "This is some text";
Some of the Java libraries I've seen source code from tend to be quite verbose when naming variables, others just use single letter names when the variable is used in a reduced context:
public Rectangle setLocation(Point p) {
return setLocation(p.x(), p.y());
}
I think the main goal when naming variables (or anything else for that matter) is always to communicate in the best way possible the intent of what you were trying to do.
Code styles help make it easier for developers to read and understand each others code. Java conventions prescribe the use of short and descriptive identifiers, but unfortunately short and descriptive cannot always be achieved together so you may have to compromise shortness for clarity hence: atmosPres - still clear but short, atmosphericPressure - this can't be mistaken, atm - because everyone just knows ATM, right?, ap - WTF?
I first encountered the practice of prefixing variable names with a three letter type identifier while developing programs in C# - it helps the reader know what data type is contained in a variable without having to look for its declaration (due to short memory or maybe laziness?). Arrays are also prefixed with I e.g IList to distinguish them from other data types (and for what purpose, I just dunno).
For me, the worst code conventions are in C++ (if indeed there are any at all) - there's a mix of case types for data types and variables, conflicting method and function naming styles and endless cryptic abbreviation which all make it hard for non-regular C++ coders to read and understand C++ code.
What you're describing is sometimes referred to as "Hungarian notation", though it's not "Hungarian" in the truest sense of the term.
Basically, the idea is to differentiate between different classes of variables -- instance variables, local variables, parameters, et al. This serves two basic purposes:
It helps avoid name collisions, where, say, there might naturally (using "descriptive" variable naming) be an instance variable ralphsLeftFoot and a local variable ralphsLeftFoot. Using a prefix allows the two to co-exist, and, especially in languages where the local might (without warning message) "hide" the instance variable, prevents unintended changes in semantics from such collisions.
It makes the scope of variables obvious, so that, during maintenance, one does not accidentally assume that a local variable has instance scope or vice-versa.
Is this approach worthwhile? Many developers use a subset of the scheme, apparently to good effect. For instance, many Objective-C developers will name the instance variable behind a "property" with a leading "_" character, to clearly differentiate between the two and to avoid accidentally using the instance variable when the property was intended.
Likewise, many developers in a number of languages will prefix instance variables with a letter (often "m") to differentiate them from "normal" local/parameter variables.
What's probably most important is to pick a style that you (and your team) likes and stick with it. If the team likes the prefixes then use the prefixes. If the team prefers something else, stick with that. Of course, changing preferences, when a better choice is "revealed" to you, is OK, but don't switch back and forth willy-nilly.
So I have seen a lot of different coding styles, but I'm only going to
talk about two big ones. I use a style where I just name everything
like their class name when used in a general sense, like this:
String str = "This is some text";
That is awful. Imagine if someone were reading your code, trying to understand what it was doing, and they came across a variable named str. It doesn't convey any meaning to the person who has to read this code as to your intentions.
Conventions are used by and for people to improve readability, and thus the overall quality of software. Without a convention, any project that has more than one developer will suffer from varying styles that will only hurt the readability of the code. If you want to know what professionals do, look around on the internet for various conventions.

What taxonomy for variables do you use? [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.
I'd seen in old codes variables written with its datatype like:
double dblMyVar;
int intYourVar;
String strTheirVar;
But, nowadays, it seems to be old-fashioned. The advantages of this approach is that you can instantly see the type of a certain variable everywhere it is. But I do dislike long variable names. Whenever I can I name my variables in a single char, like:
private Product p = new Product();
There's a modern "good practice" or convention for naming variables? What do/does you/your company use?
When in doubt, consult the Java Language Specification (JLS). Here's the section regarding Naming Conventions.
// class member only if needed
private Product product;
// instantiates before using it
product = new Product();
Declaring the variable type in the name is pretty useless, as the IDE will show you its type on mouse-over. However, using single char names can be pretty confusing for other developers (specially if you have tons of variables) and goes against the self-documenting principle.
This notation is called "Hungarian" and was popularized by Microsoft, use it if it works for you: http://en.wikipedia.org/wiki/Hungarian_notation
It depends on the language.
About C#:
As it's a strongly typed language, adding the type of the variable as a prefix of the name of the variable (Hungarian notation) is not recommended anymore (too much verbosity and redundant information)
Starting variable names that are public with an upper case is a convention (for instance MyVariable): pascal case
Starting variable names that are private with a lower case (or an underscore then a lower case) is a convention too. Using underscore or not is a matter of personal preferences (for example: _myVariable or myVariable): camel case
Naming temporary variables (such as the variable used in a for loop) with a single letter (i, j, z...) is generally OK if the usage is limited to a small scope.
But it's all about personal preferences.
EDIT: General Naming Conventions on MSDN.
y_xName, y is l/m/p/s for local/member/parameter/static. x could be i for int, f for float, p for pointer, etc.. Perhaps sp for shared pointer.. Rarely anything for most types of object/references.. I prefer code to be self explanatory, hence no names like just "p" or "m_p". Say what it is. If it's a short snippet where it's really just a generic "product" of some sort I might name it l_Product for instance. I see no point in making tiny code, even if you're trying to stay withing 76(?) characters line width, breaking the line at a proper place then indenting can make it look alright and you still see from the verbose names what is actually happening.
Well that's just my take on it..
The only time you should be using "single letter variables" is within a very short piece of code, such as "foreach(var i in item)" or "using(var p = new Product())". Of course that comes down to your own preference, but there's a very nifty little addon for Visual Studio called StyleCop. It has a whole lot of styling checks for pretty much everything, and coupled with ReSharper it can do it real time and even fix things for you.

Standard for programming 'beautiful' code 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.
I'm reading some books about coding standard in Java.
I always loved beautiful and clean code.
But there are some things that bother me. For example, a method name should start with a lowercase word, and if it has a second word, it should be start with a uppercase character. But the standard for variables is the same thing. I think this is a little confusing.
So I'm asking you guys, what's your coding standard in Java?
Like:
How do you name objects, methods, classes, etc.
If you have more than one object from same class, how do you name the second one?
If you have one object in the argument of a method and you have another object from the same class inside this method, how you do name both of them?
What is the best trade-off for performance/code beauty, a lot of small methods, or some longer methods?
Feel free to say something more. =)
Mostly following the Java code convention.
I try to not make it matter what kind of class an object is. If I for instance have five different strings, the name of each variable should describe what information/content the variable represents, and not that is is a string.
I find it often silly to try coming up with variations of a variable just because it exists both as a method argument and a class variable. I mostly use the same name with this syntax this.theVariable = theVariable
A method should be as short as possible: as few lines as possible, and as few nested levels as possible (i.e. max one if-statement, and not ifs inside ifs etc.)
Robert Martin's Clean Code is highly recommended!
Just to address one specific point, because it's one I commonly see people doing horrific things with:
If you have more than one object from same class, how do you name the second one?
By their purpose, surely. If you have two different objects of the same class, you must be using them for different purposes, so name it after that purpose. I think all of these examples would be pretty self-explanatory to most readers:
public void copyAddresses(Customer source, Customer destination) {
public void sendMessage(Mailbox sender, Mailbox recipient) {
public void changeContactCompany(User contact, Company from, Company to) {
public void eatWatermelon(Bowl servingBowl, Bowl bowlForSeedSpitting) {
or whatever... you get the idea.
You should start with the official Java Code Conventions.
They will explain why code conventions are needed, different conventions and, what your question seems to be about, naming conventions. They add various examples too.
What is the best trade-off for
performance/code beauty, a lot of
small methods, or some longer methods?
"Premature optimization is the root of all evil" - Donald Knuth
Remember:
Make it work.
Make it right.
Make it fast.
You should only worry about performance if it is warranted; if the current code is too slow to meet requirements.
In that case you should find the 'hot-spots' and optimize those. Check if performance is good enough. If not, repeat.
Well since most of these are easily googled I will add my own standard Java naming practices:
I usually suffix the name of classes of what they extend or implement.
In other words Spring MVC controllers are suffixed with "Controller". This makes it easy in Eclipse to do a Crtl-Shift-R *Controller.
Second if I find I need to aggregate a whole bunch of static methods in a class I usually suffix that class with "Utils". I got this from Apache Commons and has just stuck.
Finally derived methods that do special expensive stuff and are transient I avoid calling them getXXX. The reason is to avoid problems with serializers.
Look here at the official guide

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.

Would it be useful to change java to support both static and dynamic types? [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 9 years ago.
What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:
String str = "Hello";
var temp = str;
temp = 10;
temp = temp * 5;
Would that be possible?
Would that be beneficial?
Do any languages currently support both and how well does it work out?
Here is a better example (generics can't be used but the program does know the type):
var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String
if(username.length() == 0) {
//Error
}
C# has a "var" keyword used in the manner you describe, but it ends up being a strongly typed variable based on the types of values that type checking suggests will go into it.
Can you explain the difference between your example and
String str = "Hello";
Object temp = str;
temp = 10;
Dynamic typed variables just have type Universal, such that every other type is a subtype of Universal. Any language where all types inherit from such a universal type (such as Java modulo unboxed values) already have this capability. As for usefulness - depends on what you're doing. I prefer a fully static type system where it's easy to create safe tagged unions so I can put whatever values I need into a variable, but in a more controlled way than Universal.
Yes, it would be beneficial, but not for the example you are showing. I think something like this would be better
public void f(var o)
{
o.method();
}
and I could call f with any object with a method called method() without needing to introduce an interface. It's nice for places where there is a convention, but not necessarily an interface. It would also be useful for interop with languages with a dynamic dispatch.
Would that be possible?
Hardly. Java is a C-like language, which was initially designed to support only static typing. It will take a lot of time to introduce this feature to Java and I don't think developers will spend time on that.
Would that be beneficial?
No. Java is a traditional language, and static typing is one of the base principles or it's architecture. In fact, static-typing is still more popular in programming (you can check the interesting statistics here).
Do any languages currently support that and how well does it work out?
Well, there are a lot of languages which support dynamic typing, but I guess you know this. If the language supports dynamic typing, it doesn't make sense to introduce static typing to this language...
Also, feature which you show in your example can be implemented with static typing. jon gave you an example with "Object" class in Java. You can do similar with void* in C/C++. Still, this doesn't make language dynamic-typed.
#Lou: It would be just syntactic sugar for:
void doSth(Object foo) throws Exception{
Method m = foo.getClass().getMethod("foo", String.class);
m.invoke(foo, "baz");
}
I do use reflection, but I prefer it to be ugly so it's not abused.
Dynamic typing certainly has its uses.
However, I don't think it would make sense adding this to Java - Java is designed as a statically typed language and it would be too large a philosophical and architectural shift to try and graft on dynamic types at this point.
If you want proper dynamic typing but
still want to be part of the Java
ecosystem, take a look at one of the
other great JVM languages that
supports dynamic typing: e.g. Clojure
and Groovy.
Dynamically typed languages make coding somewhat simpler and faster, but they do so at the cost of pushing bugs from compile-time (very easy to find) to run-time (hard to find and unpredictable). If Java introduced it and it became prevalent, I would look for another language that cared more about code quality, and my time.
I'm doing a lot of Flex development at work as a front end to my Java work, and it frustrates me to no end that when I am working on a Flex method with parameters, most of the time the developer used Object for the parameter type, and I have absolutely no idea what properties/methods it will have without running the program with breakpoints and hoping I've tested all possible calls to the method. And even when they used a specific class for the parameter, there's no saying that properties/methods haven't been added or deleted from it.

Categories