According to Is it wrong to use a boolean parameter to determine behavior?, I know the importance of avoid using boolean parameters to determine a behaviour, eg:
original version
public void setState(boolean flag){
if(flag){
a();
}else{
b();
}
c();
}
new version:
public void setStateTrue(){
a();
c();
}
public void setStateFalse(){
b();
c();
}
But how about the case that the boolean parameter is used to determine values instead of behaviours? eg:
public void setHint(boolean isHintOn){
this.layer1.visible=isHintOn;
this.layer2.visible=!isHintOn;
this.layer3.visible=isHintOn;
}
I'm trying to eliminate isHintOn flag and create 2 separate functions:
public void setHintOn(){
this.layer1.visible=true;
this.layer2.visible=false;
this.layer3.visible=true;
}
public void setHintOff(){
this.layer1.visible=false;
this.layer2.visible=true;
this.layer3.visible=false;
}
but the modified version seems less maintainable because:
it has more codes than the original version
it cannot clearly show that the visibility of layer2 is opposite to the hint option
when a new layer (eg:layer4) is added, I need to add
this.layer4.visible=false;
and
this.layer4.visible=true;
into setHintOn() and setHintOff() separately
So my question is, if the boolean parameter is used to determine values only, but not behaviours (eg:no if-else on that parameter), is it still recommended to eliminate that boolean parameter?
setHint(boolean isHintOn)
as a private method, and add publicsetHintOn
andsetHintOff
methods that respectively callsetHint(true)
andsetHint(false)
. – Mark Amery Jan 10 '18 at 12:21SetTrue
andSetFalse
methods (as opposed to a singleSetState
method) simply requires the decision logic to be moved outside the method that implements each. There would hardly ever be a legitimate reason for exposing such methods publicly - and the only legitimate reason for having them internally would be if each is extremely complex. It would be different if we were talking about sequenced Begin/End methods - then it would of course stink to parameterise a single method asSetTransaction(bool BeginOrEnd)
. – Steve Jan 10 '18 at 14:00setHint(true|false)
. Potato potahto. At least use something likesetHint
andunsetHint
. – Konrad Rudolph Jan 10 '18 at 14:21is
at the beginning.isValid
etc. So why change that for two words? Besides, "more natural" is in the eye of the beholder. If you want to pronounce it as an English sentence, then for me it would be more natural to have "if the hint is on" with a "the" tucked in. – Mr Lister Jan 10 '18 at 19:32setState(bool)
, but something likesetActive(bool)
. Then it is (boolean ;)) logic thatsetActive(false)
removes the active flag. On the other handsetActive() / setInactive()
has the problem that you do not communicate if this is the same flag. There could be a (ugly named)setNotInactive()
,unsetInactive()
or similar method. – allo Jan 11 '18 at 14:19