Last active
February 27, 2018 11:42
-
-
Save nhojpatrick/d2d27b64a72e4a985511bef11f717927 to your computer and use it in GitHub Desktop.
Method Chaining Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tld.examples; | |
public class Example { | |
protected String mandatory; | |
protected String optional; | |
protected String mandatoryIfOptionalExists; | |
private Example() { | |
} | |
public Example(final Example.Builder builder) { | |
this.mandatory = builder.entity.mandatory; | |
this.optional = builder.entity.optional; | |
this.mandatoryIfOptionalExists = builder.entity.mandatoryIfOptionalExists; | |
} | |
public String getMandatory() { | |
return this.mandatory; | |
} | |
public String getOptional() { | |
return this.optional; | |
} | |
public String getMandatoryIfOptionalExists() { | |
return this.mandatoryIfOptionalExists; | |
} | |
public static class Builder<T extends Example> { | |
protected final T entity; | |
public Builder() { | |
this((T) new Example()); | |
} | |
public Builder(final T abstractEntity) { | |
this.entity = abstractEntity; | |
} | |
public Builder withMandatory(final String mandatory) { | |
this.entity.mandatory = mandatory; | |
return this; | |
} | |
public Builder withOptional(final String optional) { | |
this.entity.optional = optional; | |
return this; | |
} | |
public Builder withMandatoryIfOptionalExists(final String mandatoryIfOptionalExists) { | |
this.entity.mandatoryIfOptionalExists = mandatoryIfOptionalExists; | |
return this; | |
} | |
public Example build() { | |
if (this.entity.optional != null | |
&& !"".equals(this.entity.optional.trim())) { | |
if (this.entity.mandatoryIfOptionalExists == null | |
|| "".equals(this.entity.mandatoryIfOptionalExists.trim())) { | |
throw new IllegalArgumentException(); | |
} | |
} | |
return new Example(this); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment