#builder

1 messages · Page 1 of 1 (latest)

minor sierra
#

the builder pattern is commonly used in libraries and sdks. if i have many parameters like this

public Player(float strength, float constitution, float fortitude, float dexterity, 
float intelligence, float charisma, float wisdom, float willpower, float perception){}

i can break it down into smaller units but if that's not possible is the builder pattern a viable option?

eager nacelleBOT
#

<@&987246399047479336> please have a look, thanks.

steep panther
#

builder pattern is useful when you have multiple constructors, instead you'd call a single constructor with Player.Builder and add as many values as you'd like.

#

so if you have multiple constructors, then yes, otherwise builder would just make calling a player even longer.

minor sierra
#

yes it's normally used for that case which is why im asking if it can possibly be a viable option here. the problem i see with builder here is that you can forget to assign a required field but with a constructor you're forced to assign a value

slow dove
steep panther
#

or set a default value

minor sierra
#

you can't check for null for primitive values

slow dove
#

int -> 0

trail sand
#

if all your parameters are required, then no, a builder wouldnt be a good option

#

i have an SO answer about this somewhere, one sec

#

gives a bit more detail

minor sierra
trail sand
#

that can be done via the builder's constructor

minor sierra
#

yeah i fudged it up, but that's the idea i was converying

#

that's why i mentioned you can't check for null for primitive values. with builder it's easy to have a partially constructred object without proper validation

#

i need a user to provide a value even though 0 is an acceptable value

trail sand
#
var client = new Client.Builder("Host")
    .optionalArg1(..)
    .optionalArg3(..)
    .build();```
#

yup

#

you can check for invalid primitive values, for example -1 may be considered invalid. but yeah, cant check for "unassigned"

#

and thats not just primitives

minor sierra
#

"unassigned" is the proper word yes

trail sand
#

similar to how 0 can be seen as a valid value, so can null

minor sierra
#

your code may accept null, but you can't check whether they set it to null or it's null because it's unassigned

trail sand
#

(it shouldnt, but its still common)

trail sand
#

instead, decompose

#

i mean, its possible to track whether a required value has been set via a method, by tracking the method calls

#

you can use a builder, then throw an exception if they didnt call one of the methods

#

but now you're turning compilation errors into runtime errors, and no one wants that

minor sierra
#

tracking method calls would require assign field per method call or some other mechanism?

public void setA(int a) {
  setA = true;
  this.a = a;
}