Imagine you have to initialize some objects that you can't really handle in a loop. On top of calling the constructor, you'll have to init the object somehow with supplied data. Finally you want to also use that object in a different method. For the sake of readability and maybe even computing, would method A or B be recommended?
Method A
DummyObject a = new DummyObject("fs", "y", 4);
a.init("aseas", true);
otherObjectA.addDummy(a);
DummyObject b = new DummyObject("qwe", "sd", 8);
b.init("a4rhs", true);
otherObjectA.addDummy(b);
DummyObject c = new DummyObject("j", "xe", 39);
c.init("as", false);
otherObjectB.addDummy(c);
DummyObject d = new DummyObject("qw", "k", 12);
d.init("sdfs", true);
otherObjectC.addDummy(d);
// and so on...
Method B
DummyObject a = new DummyObject("fs", "y", 4);
DummyObject b = new DummyObject("qwe", "sd", 8);
DummyObject c = new DummyObject("j", "xe", 39);
DummyObject d = new DummyObject("qw", "k", 12);
a.init("aseas", true);
b.init("a4rhs", true);
c.init("as", false);
d.init("sdfs", true);
otherObjectA.addDummy(b);
otherObjectB.addDummy(c);
otherObjectA.addDummy(a);
otherObjectC.addDummy(d);
// and so on...
1) Why not include the content of init() method in the constructor of DummyObject ? The aim of a constructor is also initialization of the object.
2) If you have good reasons to keep this way and you have many DummyObjects to configure in this way, a more readable solution would be to extract a method to perform initialization and add steps for each DummyObject :
I would use the method A :
and I would extract a new method like that :