Multiple Returns Pattern Builder

Asked

Viewed 45 times

1

I have a class Builder who is responsible for returning an object he builds:

public class ObjetoBuilder {

    private Objeto objeto; 

    public ObjetoBuilder() {
        objeto = new Objeto();
    }

    public ObjetoBuilder adicionarId(Long id) {
        if (id != null) objeto.setId(id);
        return this;
    }

    public Objeto constroi() {
        return objeto;
    }
}

Doubt

It is good practice to have more than one method builds into one Builder? For example:

public class ObjetoBuilder {
    ...
    public Objeto controi() {
        return objeto;
    }

    public List<Objeto> constroiLista(){
        return Arrays.asList(objeto);
    }

    public String constroiJson() {
        return new Gson().toJson(objeto);
    }

    public String controiXml() {
        return new XStream().toXML(objeto);
    }
}

1 answer

1


The methods constroiJson, constroiLista and constroiXml of your class ObjetoBuilder do not build class objects Objeto, logo are not part of the Design Pattern. They could be part of the class Objeto, because they only convert the object into String in different formats (or in a list, in the case of constroiLista).

You can also use a helper class, which deals with converting not only to class objects Objeto, but something genetic for any class (avoiding code duplication). I particularly like this option better.

  • In case what would this class "helper" be? Is there a pattern where I can find these references?

  • In my view besides the object being built it is being serialized, in case receiving a plus, my question is whether this plus goes out of the standard or whether it can be done.

  • Yes, it comes out of the pattern. And yes, it can be done - each case is a case, patterns are guides to help, not to plaster the project. It is better to evaluate case by case.

  • Let’s say you have 3 classes that you want to serialize in Json format. It is not good that you implement 3 equal (or almost equal) methods for the same function. Then, you can create an auxiliary class (helper) that contains a method toJson that takes any of the objects as a parameter and converts them to Json. So you don’t replicate bugs, simplify testing, decrease chances of failure...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.