I'm writing a method along these lines:
if (hasFoo()) {
return calculateFoo();
} else if (hasBar()) {
return calculateBar();
} else {
return calculateBaz();
}
The getters are rather expensive and the has...() checks would either duplicate a lot of the logic or just have to reuse the getters. I could have the has...() methods store the result of the get...() in a field and make the getter lazy, but it would be nice for has...() not to have any side effects. I could write this with nested try{} catch{} blocks, but that doesn't look elegant. seems like there should be a better solution to this...
EDIT: changed get...() to calculate...() to make it clear that they're expensive.
int result = 0;
if (hasFoo()) {
result = getFoo();
} else if (hasBar()) {
result = getBar();
} else {
result = getBaz();
}
return result;
is the idiom I prefer to use - makes it far easier to inspect variable values while debugging.
I see nothing wrong in doing
Object fooBarBaz = null;
if (hasFoo()) {
foo = getFoo();
} else if (hasBar()) {
fooBarBaz = getBar();
} else {
fooBarBaz = getBaz();
}
return fooBarBaz;
I prefer it this way:
if (hasFoo()) {
return calculateFoo();
}
if (hasBar()) {
return calculateBar();
}
return calculateBaz();
All a matter of taste and convention.
I am not sure if this is your case, but I would try to fully refactor the code. Currently, as far as I understand, your code looks something like this (example):
boolean hasFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
if (do.getF() != null && do.getO() != null) {
return true;
} else {
return false;
}
}
Foo getFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
Foo result = new Foo(do.getF(), do.getO());
return result;
}
Basically what happens here is that the same code is used to check if Foo can be returned and to construct the Foo itself too. And I would refactor it to this:
/**
* #returns instance of Foo or null if Foo is not found
*/
Foo getFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
F f = do.getF();
if (f == null) {
return null; //Foo can not be created
}
O o = do.getO();
if (o == null) {
return null; //Foo can not be created
}
return new Foo(f,o);
}
Now your original code would become similar to this:
Result r;
r = getFoo();
if (r == null) {
r = getBoo();
}
if (r == null) {
r = getDoo();
}
return r;
This is not an "is it OK to do multiple returns" problem - your multiple returns are fine.
This is a refactoring and/or state storage problem.
If you have:
bool hasXXX() {
// do lots of stuff
...
return has_xxx;
}
and
double calculateXXX() {
// do the same lots of stuff
...
// do some more stuff
...
return xxx;
}
then the complexity of the problem depends on whether the hasXXX() calculation produces lots of intermediate values that are necessary for calculateXXX().
You likely need something like:
bool checked_xxx = false;
double xxx_state;
bool hasXXX() {
// do expensive stuff
...
// save temporary state variables
xxx_state = ...
// remember that we've been here
checked_xxx = true;
// send back the required value
return has_xxx;
}
double calculateXXX() {
// make sure that hasXXX was called, and is valid
if (!checked_xxx && !hasXXX()) {
// should never happen - you called calculateXXX when hasXXX() == false
throw new RuntimeException("precondition failed");
}
// use the previously calculated temporary state variables
...
// send back the final result
return xxx;
}
EDIT: If I'm interpreting your comments correctly, it sounds like you actually want something like:
Result result = calculateFoo();
if (result != null) {
return result;
}
result = calculateBar();
if (result != null) {
return result;
}
return calculateBaz();
... where each of the calculate methods returns null if the corresponding has method returns false. Now if null is a valid "real" return value, you could always wrap the result so that calculateFoo returns a value which can basically say, "Yes, I've got a valid value and it's X" or "no, I haven't got a valid value" (a "maybe" type).
Original answer
I would keep your code exactly as it is. I see no problems with having multiple return statements when that's the clearest approach - and in this case I believe it is.
You're making it clear that once you've reached each of the "leaf" parts, you know exactly what the return value is, and the only other code which should be executed before leaving the method is any clean-up code in finally blocks.
Having a single exit point makes sense in languages which don't have try/finally or GC (where you really want to make sure you do all the cleanup in a single place) but in Java, I think returning when you know the result states your intention more clearly than using a separate local variable.
Having said that, another alternative to consider is using the conditional operator, laying out your code so it's obviously going through a series of tests and returning as soon as it finds the first "match":
return hasFoo() ? getFoo()
: hasBar() ? getBar()
: getBaz();
The disadvantage is that this pattern looks a little odd the first time you see it - but once you get used to it, I find it a really neat way of encoding this sort of logic.
Instead of doing hasXXX() and calculateXXX() you could factor those calculations out to separate objects eg
public interface CalculationModel {
Object calculate();
}
public class FooCalculationModel implements CalculationModel {
#Override
public Object calculate() {
// Perform Foo calculations
return result;
}
}
and your if-statement can then be replaced with:
return getCalculationModel().calculate();
You will need some way of deciding the CalculationModel of course, but this would then replace the hasFoo(), hasBar() etc methods.
you could do something like this :
Object bar;
if ((bar = getFoo()) != null) {
return bar;
} else if ((bar = getBoo()) != null) {
return bar;
} else {
return getBaz()
}
this way you only need to call the get methods, but not the has ones
EDIT
this is the same in a more readable format that also elminates the need to call the has methods
Object bar = getFoo()
if (bar == null) {
bar = getBoo()
}
if (bar == null) {
bar = getBaz()
}
return bar;
Related
Which way of returning from condition is better , Like the process1 and process 2 both does the same. But I want to know better way returning.
In both cases I don't want to enter inside of loop, I just want to return. I would like to know that, Is there any performance difference If I put return before control passes to end. I don't want Java Virtual Machine to check end of loop and returning from there. I thought If I put return Immediately when the condition not satisfied, then I could see minor performance difference and also code readability. Please suggest me the best way.
Let us consider the below scenarios.
Process1:
public Method()
{ //Method
Company company = new Company(); //Object
if (null != Address && null = Address.location()) //Condition
{
return company; //I want to return
}
for (Location location: Address.location())
{
//forloop
}
return company; //return
}
Process2:
public Method()
{
Company company = new Company();
if (null != Address && null != Address.location())
{
//enters loop
}
return company; // return
}
There will be some performance impact. Iterating complete objects from the for loop to verify the condition.
For example:
We can write like this.
if(condition is false){
return ;
else{
for(DataType ref: collection){
if(true){
return;// return from here, so that it will not iterate remaining elements.
}
}
}
ex 2:
if there is a logic after the if and that should not be executed, if the object is null.
if(object is null){
return ;
}
//Remaining logic here will not be executed, if the object is null. it's a good way of writing.
ex 3:
if there is no logic after the if and else, then directly return from the end of method.
if(object is null){
return
}else{
//process logic and return.
}
you can write something like this.
if(object is not null){
// return either from here.
}
return here is also fine...
Saw in a blogpost that this kind of code drives the author insane.. Why?
public boolean foo() {
boolean b = bar();
if (b == true) {
return true;
}
else {
return false;
}
}
Because there is a much shorter version of it:
public boolean foo() {
return bar();
}
As others have noted, the whole function foo may be redundant. There are however situations where it cannot be eliminated, for example if it is defined in an interface you are implementing or if bar is private.
The construct if (b == true) is especially dangerous for inexperienced programmers, as it could be wrongly written as if (b = true). This problem is not caught by the compiler but would silently always execute the true branch of the if.
Because it could be written as
public boolean foo() {
return bar();
}
The code is unnecessarily complex.
Because the call to foo() (and the entire function itself) can be replaced with bar().
Anytime you write:
if (something == true) {
return true;
} else {
return false;
}
All you're doing is returning the value of something, so why not just return something;? And at that point in the code you provided in OP, the entire function has no point to exist since it's just returning the return value of another function.
Another similar use case (and equally annoying) is:
Foo foo = getFoo();
if (foo == null) {
return null;
} else {
return foo;
}
of all above answers, I think you don't even need to call foo().
just use
if(bar())
directly at the place where you are calling foo()
no need of foo() function at all
Often in java I have to get a value of a property of an object which is deep in this object. For example, if I'm sure that all my sub-objects are not null, I can do that :
public function getDeepValue(A a) {
String value = a.getB().getC().getListeD().get(0).getE().getValue();
return value;
}
But in case of sub objects of the parent can be null, I have to test every object.
To do that, I see 2/3 solutions :
First, step by step :
public function getDeepValue(A a) {
if(a == null){
return null;
}
B b = a.getB();
if(b == null) {
return null;
}
C c = b.getC();
if(c == null){
return null;
}
List<D> ds = c.getListeD();
if(ds == null || ds.size() == 0){
return null;
}
D d = ds.get(0);
if(d == null) {
return null;
}
E e = d.getE()
if(e == null){
return null;
}
return e.getValue();
}
Second, test all in one if block, soooo dirty :
public function getDeepValue(A a) {
if(a != null && a.getB() != null && a.getB().getC() != null && a.getB().getC().getListeD() != null && a.getB().getC().getListeD().size() > 0 && a.getB().getC().getListeD().get(0) != null && a.getB().getC().getListeD().get(0).getE() != null){
return a.getB().getC().getListeD().get(0).getE().getValue();
}
return null;
}
Third solution, using a try catch block :
public function getDeepValue(A a) {
try {
return a.getB().getC().getListeD().get(0).getE().getValue();
} catch(NullPointerException e) {
return null;
} catch(IndexOutOfBoundsException e) {
return null;
}
}
Solution 1 seems not too bad but needs a lot of code. It is generally the solution I use.
Solution 2 is for me really dirty...
In paper, I realy like solution 3, but is it a good solution in term of performances ?
Is there any others acceptables solutions ?
Thanks for help, I hope my english is not too bad..
Regards
Solution #3 looks simple, but it can potentially hide a whole host of problems. It might be an adequate solution if you have full access to all of the classes in the chain and you know what's going on in each method and you can guarantee those methods won't cause problems with your try/catch and you're never going to change them... that's a lot of conditions to make it a worthwhile solution, but I can conceive that it's possibly a useful sufficient one.
Solution #2 looks horrid to me, especially if one or more of the get methods is a bottleneck (such as a slow database query or using a blocking network connection). The earlier in the chain such a potential bottleneck, the worse it would potentially be, as you're calling it over and over again. This of course depends on the implementation of the methods in question (even if one of them is slow, the result could be cached, for example), but you shouldn't need to know that in your client code. Even with efficient or trivial implementations, you've still got the overhead of repeated method calls you oughtn't need.
Solution #1 is the best of the three, but it's likely not the best possible. This solution takes more lines of code than the other two, but it doesn't repeat itself and it isn't going to be tripped up by the implementations of the other methods. (Note: If you do not have access to the classes in the chain for refactoring, I would use this solution.)
A better solution than #1 would be to refactor the classes so that the client code doesn't need to know about this chain at all. Something along these lines:
class Client {
public Mumble getDeepValue(A a) { return a == null ? null : a.getDeepValue(); }
}
class A {
private B b;
public Mumble getDeepValue() { return b == null ? null : b.getDeepValue(); }
}
class B {
private C c;
public Mumble getDeepValue() { return c == null ? null : c.getDeepValue(); }
}
class C {
private List<D> ds;
public Mumble getDeepValue() {
D d = ds == null || ds.size() == 0 ? null : ds.get(0);
return d == null ? null : d.getDeepValue();
}
}
class D {
private E e;
public Mumble getDeepValue() { return e == null ? null : e.getMumble(); }
}
class E {
private Mumble m;
public Mumble getMumble() { return m; }
}
As you can see, the longest chain any of these classes has is to access the public members of an element of a collection that is a private member of the class. (Essentially ds.get(0).getDeepValue()) The client code doesn't know how deep the rabbit hole goes, only that A exposes a method which returns a Mumble. Client doesn't even need to know that the classes B, C, D, E, or List exist anywhere!
Additionally, if I were designing this system from the ground up, I would take a good long look at whether it could be restructured such that the actual Mumble object wasn't so deep. If I could reasonably get away with storing the Mumble within A or B, I'd recommend doing it. Depending on the application, that may not be possible however.
in terms of performance solution 3 is the best one. In addition It is neat and easy to understand , For example looking at a loop example:
int[] b = somevalue;
for(int i=0;i<b.length;i++){
//do something
}
in this case for every iteration we execute the condition. However, there is another approach for it which uses try and catch
int[] b = somevalue;
try{
for(int i=0;;i++){
//do something
}
}catch(IndexOutOfBoundException e){
// do something
}
on the second solution,the loop keeps going until we reach the end of the loop which then it throws IndexOutOfBoundException as soon as we reach the end of the array. meaning we don't check for the condition no more. thus faster.
Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}
I want to write a vim script to do the following:
if I have the following in my Java code,
Z z = obj1.foo().bar().foo1().bar1()
it should be replaced by
if(obj1 != null) {
T1 o1 = obj1.foo();
if(o1 != null) {
T2 o2 = o1.bar();
if(o2!=null) {
T3 o3 = o2.foo1();
if(o3 != null) {
z = o3.bar1();
}
else
z = null;
}
else
z = null;
}
else
z = null;
}
else
z = null
I want to write a vi command that takes as arguments a comma-separated list of Types T1,T2 ... and so on to give me this big thing.
How do I learn about vimscripting?
Like those who have commented on your question, I believe there is a better way to deal with your problem.
Here are my concerns with your idea:
That code isn't very readable; it will make it more difficult and effort-intensive to debug or enhance your code in the future
Your approach will make adjustments even in cases where a null reference is impossible
There may be circumstances in your code where returning null is inappropriate; some of these may already be handled in a better way
I suspect a script like that will actually introduce bugs or compile-time errors; here's one example off the top of my head
// Be sure to cal foo.bar().foobar() in special cases
public Foo bar() {
// do work...
}
becomes...
// Be sure to cal if(foo != null) {
Bar bar = foo.bar();
if (bar != null) {
Foobar foobar = bar.foobar();
in special cases
}
}
public Foo bar() {
// do work...
}
Instead, use a static analysis tool (or more than 1) like FindBugs, which is really good at catching likely null pointer de-references.