What's the accepted way to write Java methods where return value may be invalid? -
i come c programming background. want understand what's best way write java api value being returned, may invalid.
i have class implementing binary search tree. has method, getrootvalue() returns root's value.
c code-
boolean getrootvalue(int *answer) { if (root != null) { *answer = value; return true; } else { return false; } }
on user's end, like-
if (getrootvalue(&answer)) { //process valid answer }
the user calling function check return, , consider answer
valid if return value true
.
java skeleton code-
package algorithm; class bst { node root; class node { int value; node left; node right } //getrootvalue() }
user's end-
package user; import algorithm.bst; ... //bst.getrootvalue();
in java, correct way (considering root known bst , not user)? should send special class object contains both boolean , answer? if so, should class defined?
is there different method? should think differently bst class implementation?
there previous questions asking how return multiple values. that's not question. want know ideal way implement particular case, possibly may not require returning multiple objects.
i wouldn't write method. there's nothing special root need specific method value. entire method redundant. need root, , need value out of node (and left , right children too).
i write two methods:
node tree.getroot()
int node.getvalue()
.
the exceptional case mention met returning null
getroot()
, caller can readily detect.
Comments
Post a Comment