Home > other >  Is there any better way to make a constructor that fills in for all the possible variables rather th
Is there any better way to make a constructor that fills in for all the possible variables rather th

Time:11-05

Is there any less time consuming method of creating a program that can take all of my given parameters and regardless of what they are simply fill in for those values? For example given optional 4 parameters that I want to fill will I have to write a constructor for each possible combination?

I'm new to Java but I've already written one class where I did this, and it took me quite some time and was a somewhat monotonous, I was just wondering if there was a faster method of doing it.

CodePudding user response:

Constructors are not the only way to construct objects. There are a few (creational) design patterns that accomplish the same goal that you should consider. In fact, it could be argued that constructors should be considered your last resort to build objects. I strongly recommend you do some research into Creational Design Patterns

For this problem, I think you can take advantage of The Builder Pattern.

Builder Pattern Explained

The builder pattern allows clients to build an object in stages. This is possible because instantiation of the required object is deferred to the builder until all needed attributes are obtained.

Consider the process of building a "widget". Assume this "widget" has two components, of which only one is required. You can either A) build the "widget" without the optional component, or B) you can assemble the "widget" with the required part, pause the build process and resume at a later time when the optional component is available. When using a conventional constructor, this is not possible.

Another advantage of the Builder pattern is that you don't need to create a constructor with a lot of parameters that are not required. And it eliminates the need to have multiple permutations of the constructor with different parameters. In fact, sometimes this is not even possible. For example, if the class in question has eight String parameters, you cannot have two constructors with four Strings each.

When implementing this pattern, the "widget" being built has only one constructor, and it is private. The constructor of the class is only accessible to the builder.

Lastly, unlike conventional "setter" methods, the "setter" methods of a builder return an instance of the builder itself. This allows chaining method calls to set multiple (optional) parameters. For example; builder.setOptionalParm1(val1).setOptionalParm2(val2)... etc.

Builder Pattern Code Example

public class ImmutableWidget {
    
    private final String required;
    private final String optional;
    
    private ImmutableWidget (Builder builder) {
        this.required = builder.required;
        this.optional = builder.optional;
    }
    
    @Override
    public String toString () {
        return "Required: "   required   "; Optional: "   optional;
    }
    
    public String getRequired () {
        return required;
    }
    
    public String getOptional () {
        return optional;
    }
    
    public static class Builder {
        
        private final String required;
        private String optional;
        
        public Builder (String required) {
            this.required = required;
        }
        
        public Builder setOptional (String optional) {
            this.optional = optional;
            return this;
        }
        
        public ImmutableWidget build () {
            return new ImmutableWidget (this);
        }
    }
    
    public static void main (String... strings) {
        Builder builder = new ImmutableWidget.Builder ("required");
        builder.setOptional("optional"); // This step is not required
        ImmutableWidget widget = builder.build();
        System.out.println(widget);
    }
}

Additional information

  1. Basic Builder Pattern topic: Immutable Widget YouTube video
  2. Advanced Builder Pattern topic: Using Builder Pattern with Class Hierarchies

CodePudding user response:

This post by Vitalii Fedorenko explains what to do: https://stackoverflow.com/a/12994104/20421925

Vitallii's post is a lot to take in (I'm still trying to understand it myself). Let me know if you need any assistance understanding it.

  • Related