Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to write methods that return void?

I am working on a complex enterprise application coded in java that is driven by complex object compositions. For example : In a particular scenario, to perform an action this is the flow:

login() -> 
Followed by defined sequence of 10 to 20 method calls in different classes -> 
Followed by a logout()

Within the framework, almost all the actions including the login, logout, and many of the 10 to 20 method calls have no return types. Any erroneous behavior is handled by the framework. Say, in login

public void login(){
try{
 //login actions
 //chained sequence of calls

}catch(){
 // framework handling exceptions and other rollback options
}
}

The intermediate 10 to 20 actions are method calls on different objects at different levels of hierarchy of the framework.

A random class would look like this :

class someobject{

def variable

void action1(){ do something on variable }
void action2(){ do something on variable }
...
}

The variable changes state often and these actions have a sequence defined only by the framework which I find very annoying.

I'd say, Probably if there were appropriate return types at all or at least some of these methods, as in say boolean in the case of login(), life would be a lot easier. Because of this tight adherence to a series of void returning functions, I find it difficult to debug through to understand the flow and also unit testing became a nightmare to me.

So now, I am under the impression that it is always better to write functions that return something, especially when there is a chain of actions involved. So, Is this a safe presumption? I'd want to take your opinions on this. Do correct me if I am wrong.

like image 433
Vamsi Emani Avatar asked Apr 26 '12 10:04

Vamsi Emani


1 Answers

The most basis testability of a method is via its return code. In the case of login you need (as you noted) to be able to test whether you are now logged in, and a boolean return is the obvious way. Otherwise you have to check some property, which seems unnecessarily non-atomic and complex (though might be needed for other reasons).

To me, this argument extends to any meaningful method. Using void return codes is pretty common but more as a result of old habits than for good design reasons. Simple property setters are a counter-example though, and I am sure there are others.

like image 54
Steve Townsend Avatar answered Sep 20 '22 13:09

Steve Townsend