I came across this method in the JDK
From com.sun.org.apache.xml.internal.serializer.Version;
public static int getDevelopmentVersionNum()
{
try {
if ((new String("")).length() == 0)
return 0;
else
return Integer.parseInt("");
} catch (NumberFormatException nfe) {
return 0;
}
}
Is this doing anything more than return 0?
I feel like I am missing something. I can only assume this is generated code. ;)
It looks like this file is generated from the following Version.src file by textual substitution. So, when #version.DEVELOPER# variable is empty, the code in question is generated. length() check is needed to return 0 in this case.
I think "" is replaced with some string from a configuration file before release. In this case it is empty, but it may also contain a number. If you consider "" to be a variable, this code makes some sense.
The javadoc on the method indicates that it's meant to designate a development drop that is work in progress. So I would say it makes as much sense as anything else that's meant for internal development use only. It could be that they "wash away" any actual version information from this method once they do a release. Either way, I would not place any significance on it. Unless you are a developer at oracle, working on this particular package.
Yes, there's probably a generator/preprocessor, which outputs a string in both if's.
If this string is a number, the method returns its value as a number. If it's empty (as in this case) or not a number, it returns 0.
Looks like the original xalan has a similiar implementation - at least I found the same lines for xalan 2.7.1 at grepcode
It really doesn't make any sense, to much effort for a method that always returns 0 ;) But from looking at the javaDoc of Version and this method I get the impression that all of this is (or was) work in progress - some sort of implementation stub where one can simply enter (hardcode) a version number. For now, the else block and the catch block are unreachable code.
Maybe Version.java is/will be autogenerated and the processor may generate this method with a real value instead of "" - in that case it would make sense to secure the method, as the value from the config file may not represent an integer.
Related
Let's say I do something like this in Java 8 (Android specifically)
String name = someObject.getName() != null ? someObject.getName() : "null";
and the method getName() might have a lot of calls to other methods to resolve the name. Also suppose I'm calling this code quite often.
Would it be better, performance wise, to do something like this instead?
String name = someObject.getName();
name = name != null ? name : "null";
This looks like an optimization possible, called CSE; a JVM AFAIK does that (but not sure about Android).
But this highly depends on what getName does, if it allocates internally other objects and does some other things. Unfortunately I can't even tell how to prove me wrong or right here (might need to investigate); honestly I have a habit of doing this myself. For example:
for(int i=0;i<list.size();++i){
}
I try to always extract the int size = list.size() before the loop; even if this in my understanding is subject to scalar replacement optimization.
The second version is calling getName one time, while the first, in case is not null, it's calling that 2 times... so if it is very heavy, the second version is better.
As Arnaud said, you have to consider if the value can change between the two calls: in this case you will get a performance boost, but a risk to get an "old" value.
Assume I have a Java method
public X findX(...)
which tries to find an Object of type X fulfilling some conditions (given in the parameters). Often such functions cannot guarantee to find such an object. I can think of different ways to deal with this:
One could write an public boolean existsX(...) method with the same signature which should be called first. This avoids any kind of exceptions and null handling, but probably you get some duplicate logic.
One could just return null (and explain this in javadoc). The caller has to handle it.
One could throw a checked exception (which one would fit for this?).
What would you suggest?
The new Java 8 Optional class was made for this purpose.
If the object exists then you return Optional.of(x) where x is the object, if it doesn't then return Optional.empty(). You can check if an Optional has an object present by using the isPresent() method and you can get the object using get().
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
If you can't use Optional I would go with option 2.
In the case of 1. You'd be doing double work, first you have to check if X exists, but if it does, you're basically discarding the result, and you have to do the work again in findX. Although the result of existsX could be cached and checked first when calling findX, this would still be an extra step over just returning X.
In the case of 3. To me this comes down to usability. Sometimes you just know that findX will return a result (and if it doesn't, there is a mistake somewhere else), but with a checked exception, you would still have to write the try and (most likely empty) catch block.
So option 2 is the winner to me. It doesn't do extra work, and checking the result is optional. As long as you document the null return, there should be no problems.
Guava (potentially other libraries, too) also offers an Optional class that might be worth exploring if your project uses Guava since you seem to not use Java 8.
If you
don't/can't/won't use Java 8 and its accompanying Optional type
don't want another library dependency (like Guava) for a single class implementation
but
you want something more robust than methods that can return null for which you have to have a check in all consumers (which was the standard before Java 8)
then writing your own Optional as an util class is the easiest option.
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
I have found myself using the following practice, but something inside me kind of cringes every time i use it. Basically, it's a precondition test on the parameters to determine if the actual work should be done.
public static void doSomething(List<String> things)
{
if(things == null || things.size() <= 0)
return;
//...snip... do actual work
}
It is good practice to return at the earliest opportunity.
That way the least amount of code gets executed and evaluated.
Code that does not run cannot be in error.
Furthermore it makes the function easier to read, because you do not have to deal with all the cases that do not apply anymore.
Compare the following code
private Date someMethod(Boolean test) {
Date result;
if (null == test) {
result = null
} else {
result = test ? something : other;
}
return result;
}
vs
private Date someMethod(Boolean test) {
if (null == test) {
return null
}
return test ? something : other;
}
The second one is shorter, does not need an else and does not need the temp variable.
Note that in Java the return statement exits the function right away; in other languages (e.g. Pascal) the almost equivalent code result:= something; does not return.
Because of this fact it is customary to return at many points in Java methods.
Calling this bad practice is ignoring the fact that that particular train has long since left the station in Java.
If you are going to exit a function at many points in a function anyway, it's best to exit at the earliest opportunity
It's a matter of style and personal preference. There's nothing wrong with it.
To the best of my understanding - no.
For the sake of easier debugging there should be only one return/exit point in a subroutine, method or function.
With such approach your program may become longer and less readable, but while debugging you can put a break point at the exit and always see the state of what you return. For example you can log the state of all local variables - it may be really helpful for troubleshooting.
It looks like there a two "schools" - one says "return as early as possible", whereas another one says "there should be only one return/exit point in a program".
I am a proponent of the first one, though in practice sometimes follow the second one, just to save time.
Also, do not forget about exceptions. Very often the fact that you have to return from a method early means that you are in an exceptional situation. In your example I think throwing an exception is more appropriate.
PMD seems to think so, and that you should always let your methods run to the end, however, for certain quick sanity checks, I still use premature return statements.
It does impair the readability of the method a little, but in some cases that can be better than adding yet another if statement or other means by which to run the method to the end for all cases.
There's nothing inherently wrong with it, but if it makes you cringe, you could throw an IllegalArgumentException instead. In some cases, that's more accurate. It could, however, result in a bunch of code that look this whenever you call doSomething:
try {
doSomething(myList);
} catch (IllegalArgumentException e) {}
There is no correct answer to this question, it is a matter of taste.
In the specific example above there may be better ways of enforcing a pre-condition, but I view the general pattern of multiple early returns as akin to guards in functional programming.
I personally have no issue with this style - I think it can result in cleaner code. Trying contort everything to have a single exit point can increase verbosity and reduce readability.
It's good practice. So continue with your good work.
There is nothing wrong with it. Personally, I would use else statement to execute the rest of the function, and let it return naturally.
If you want to avoid the "return" in your method : maybe you could use a subClass of Exception of your own and handle it in your method's call ?
For example :
public static void doSomething(List<String> things) throws MyExceptionIfThingsIsEmpty {
if(things == null || things.size() <= 0)
throw new MyExceptionIfThingsIsEmpty(1, "Error, the list is empty !");
//...snip... do actual work
}
Edit :
If you don't want to use the "return" statement, you could do the opposite in the if() :
if(things != null && things.size() > 0)
// do your things
If function is long (say, 20 lines or more), then, it is good to return for few error conditions in the beginning so that reader of code can focus on logic when reading rest of the function. If function is small (say 5 lines or less), then return statements in the beginning can be distracting for reader.
So, decision should be based on primarily on whether the function becomes more readable or less readable.
Java good practices say that, as often as possible, return statements should be unique and written at the end of the method. To control what you return, use a variable. However, for returning from a void method, like the example you use, what I'd do would be perform the check in a middle method used only for such purpose. Anyway, don't take this too serious - keywords like continue should never be used according to Java good practices, but they're there, inside your scope.
I extracted someone's APK (Android app) to see the Java source code and saw a lot of return; code, even on void methods.
For example:
public void doSomething(){
do{
return; //This line makes the code below unreachable and can't compile in Eclipse
switch(num){
...
default:
return;
}
}while(...)
...
}
How come the app seems to run well on my phone?
I guess return; is like a shortcut to break from the method. Is that right?
If the method returns void then return; just exits out of the method at that statement, not running the following statements.
Yes, that is correct. Look at the bottom of http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html:
The return Statement
The last of the branching statements is the return statement. The
return statement exits from the current method, and control flow
returns to where the method was invoked. The return statement has two
forms: one that returns a value, and one that doesn't. To return a
value, simply put the value (or an expression that calculates the
value) after the return keyword.
return ++count; The data type of the returned value must match the
type of the method's declared return value. When a method is declared
void, use the form of return that doesn't return a value.
return;
To answer your first question: I assume this code is decompiled. Note that decompilers are not one to one converters of binary dex code to whatever Java code has been used to generate these binaries. They often have problems with parsing different control structures like loops and switches. Besides, the binary may be obfuscated, meaning that after compilation the binary is modified in a way to be fully operational, but harder to decompile and reverse engineer (basically to prevent what you're trying to do here :) ). They can add dead code, like return statement that shouldn't be there, mangle loops and if statements to confuse decompiled code, etc.
return keyword is used basically in a void method ,it helps to break the conditional statement to come out of method.