Search code examples
javaoptimizationcode-readability

Code-readability of non-loopable initilazations


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...

Solution

  • 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 :

    DummyObject d = new DummyObject("qw", "k", 12);
    d.init("sdfs", true);
    otherObjectC.addDummy(d);
    

    and I would extract a new method like that :

      DummyContainer container = ...;
      DummyObject a = new DummyObject("qw", "k", 12);
      initAndAddDummyObject(a, container,"sdfs",true);
         ...
      DummyObject b = new DummyObject("qwe", "sd", 8);
      initAndAddDummyObject(b, container,"a4rhs", true);
    
         ...
    
     public void initAndAddDummyObject(DummyObject source, DummyContainer container,  String initString, boolean initBoolean){ 
            source.init(initString, initBoolean);
            container.addDummy(source);
        }