Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Best way to choose different child class to create new instance based on a boolean

Hi my question is simple.
I have 3 classes, BaseObject, and GoodObject + BadObject that extends it:


public class BaseObject {
  // some properties
}

public class GoodObject extends BaseObject {
  // good properties
}

public class BadObject extends BaseObject {
  // bad properties
}

And in the code, I’ll need to choose to create GoodObject or BadObject, depending on boolean value isGood:

public BaseObject businessLogic(){
  // ...
  return isGood ? new GoodObject(...) : new BadObject(...);
}

I don’t like the idea for businessLogic to worry about which BaseObject instance to create, so plan to extract the return isGood ? new GoodObject(...) : new BadObject(...); into a factory class, so businessLogic will call something like Factory.createObject(isGood, ...).
But not sure if there’s a better or more elegant way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


An additional question, if I’m to use Factory class, what is the good way for me to pass in different properties? What I can think of is something similar to Builder pattern.

public class ObjectFactory {
  // all properties...

  public BaseObject withGoodProperties(good properties)   {
    // set good properties
    return this;
  }

  public BaseObject withBadProperties(bad properties)   {
    // set bad properties
    return this;
  }

  public BaseObject create(boolean isGood, base properties){
    return isGood ? new GoodObject(...) : new BadObject(...);
  }
}

Then in order to create a GoodObject i.e.: I need to call ObjectFactory.withGoodProperties(...).create(true, ...).
The problem is that it doesn’t seem much simpler than the original
return isGood ? new GoodObject(...) : new BadObject(...);

>Solution :

I’d recommend going with the Factory approach, such as:

public class BaseObjectFactory {
    public static BaseObject create(boolean isGood) {
         return isGood ? new GoodObject(...) : new BadObject(...);
    }
}

If you want a Design Pattern approach. In my actual code, I’d probably have an if statement somewhere, and not be too concerned with this.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading