Conventionally, can a set() method return a value in Java? -
i learning how write neat , organized code in java. can set()
method return value or there more efficient/readable way of doing this?
public class car { private boolean mhasaxles; private boolean mhastires; private tires mtires; public setaxels(boolean hasaxles) { mhasaxels = hasaxles; } public boolean hasaxles() { return mhasaxles; } public boolean settires(tires tires) { if(hasaxles()){ mtires = tires; mhastires = true; return true; // returns true if able set tires } return false; // returns false because car did not have axels // therefore, tires not set } }
in example, question settires()
method. should class check whether car has axles when setting tires or should logic left class uses car
? should settires()
method called else since returns value?
strictly conventionally - no, setter returns void.
having said that, free return boolean
if wish - conventions broken (even in internal java api's) , method signature, including it's return type, should inspire interested developer navigate code see why boolean
returned.
to make clearer, might want use different method name, e.g. settiresifable(tires tires)
, or alternatively return void
, throw exception per below:
public void settires(tires tires){ if(!hasaxels()) { throw new illegalstateexception("no axels!"); } mtires = tires; mhastires = true; }
incidentally, mhastires
redudant, can check if tires == null
.
lastly, can avoid m
or hungarian notation in java (as per convention), this:
public setaxels(boolean hasaxels){ this.hasaxels = hasaxels; }
Comments
Post a Comment