Getter, Setter, Worse or Better?

For­give the tech­ni­cal diver­sion, but this is a lit­tle unset­tling. I’ve been stub­born­ly cling­ing to the idea that I can get away with using inte­grat­ed getter/setter meth­ods in my code. I thought it was an ele­gant solu­tion to the clum­si­ness of mak­ing sep­a­rate meth­ods for get­ting and set­ting val­ues in my objects: sim­ply check to see if there is a val­ue passed to the method, mas­sage the val­ue any way I want, then return it. If no val­ue is sent, the val­ue gets returned with­out being set. One method, two uses. That’s a two birds with one stone solu­tion, right?

Maybe not. I’ve stum­bled on a sit­u­a­tion where it will be use­ful to return an error mes­sage any time some­one sets the val­ue incor­rect­ly, includ­ing an attempt to set the val­ue to a blank string. Using a com­bined getter/setter method, I’ll need to return an array of val­ues, start­ing with the (pos­si­bly new­ly set) val­ue and adding the error descrip­tion to the mix. Less ele­gant to check the out­put of the sec­ond ele­ment of an array to see whether the val­ue was set correctly.

Folks told me I should make sep­a­rate get­ters and set­ters and I did­n’t lis­ten. This could mean a lot of code to rewrite.

Leave a Reply