views:

22

answers:

2

I more than once saw code of the form:

DiceThrower dt = new DiceThrower();
dt.throw(); //this is a void method
int result = dt.getResult();

instead of

DiceThrower dt = new DiceThrower();
int result = dt.throw();

My question is...why? Isn't it better to have the throw method returning the result? By not doing so, I could even incurr in sometimes forgetting about calling throw() before getResult(), accessing always old values of getResult(). Having both the operation and the result in the same method would circumvent that.

What is your oppinion on the matter?

Thanks

+2  A: 

I'd use this pattern if you would need to use the data often, and it's expensive to (re)generate. But then memoization would probably be better, so the caller doesn't have to care.

calmh
+1  A: 

You could even support both. Throw could return the value but it would also be available via getResult(). As noted above, if it's expensive to throw you want to cache the value in case it's needed more than once.

Paul Rubel