-1

This isn't a difficult question. I simply want to know which of these two C++ code snippets you think is better (readability vs. length vs. boiler-platery):

Option #1

Entity* square = Entity::Builder().positionX(0.0).positionY(0.0).
    controller(ctrl).representation(rep).build();

Option #2

Entity::Builder bld;
bld.positionX(0.0).positionY(0.0).controller(ctrl).representation(rep);
Entity* square = bld.build();

I personally prefer the first option, but that may be because I am the author of the code and already know what the code does (it may be confusing for someone who doesn't know the code). I like it better because it shows the focus on the Entity object rather than on the Entity::Builder object (and because it's shorter).

Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • 5
    Why not `Entity* square = new Square(0.0, 0.0, ctrl, rep);`? – James Mar 16 '11 at 21:06
  • 2
    It's not a *difficult* question, but it doesn't have a "right" answer, either, which goes against StackOverflow's guidelines. – StriplingWarrior Mar 16 '11 at 21:07
  • @James: This is method chaining. It's less restrictive than e.g. a constructor call, where you might not want to provide all the arguments. – Oliver Charlesworth Mar 16 '11 at 21:07
  • I don't know about readability - they both look the same to me - but the second one is creating a superfluous "bld" which may or may not be an issue. – Peter M Mar 16 '11 at 21:07
  • @Oli: I know, was just curious as to why you would need it for something with (seemingly) so few parameters. Maybe there is more to the `Square` than meets the eye here. Objection withdrawn. – James Mar 16 '11 at 21:08
  • @James I expect the Entity class to grow quite big, so I'll require some sort of mechanism to better handle the large amount of parameters I would have to pass in the constructor. I chose the builder pattern. There's few parameters now, but their number will grow. – Paul Manta Mar 16 '11 at 21:09
  • @Paul: Makes sense. For what it is worth, option 1 seems fine so long as you don't need the builder after you call `build`. – James Mar 16 '11 at 21:10

1 Answers1

5

Option #3

Entity* square = Entity::Builder()
                     .positionX(0.0)
                     .positionY(0.0)
                     .controller(ctrl)
                     .representation(rep)
                     .build();
James
  • 24,676
  • 13
  • 84
  • 130
  • That's also an option, but I have an irrational dislike for that kind of alignment. :P I use it sometimes, but most of the time it makes me think of old C code. :)) – Paul Manta Mar 16 '11 at 21:13
  • In such case, it is best to provide a proper constructor method. It improves readability and is less error-prone. – Maciej Ziarko Mar 16 '11 at 21:14
  • `boost::python` uses this design extensively, and it works quite neatly. – James Mar 16 '11 at 21:20