Java constructor (anti-pattern) super-classing String -
the intention of following design allow string values (in effect) subclassed enable number of conflicting constructor methods established (e.g. method signatures same though parameter names different).
kindly consider following (non-functional) design:
id interface (an empty - marker interface)
public interface id {}
classes interface (an empty - marker interface)
public interface classes {}
title interface (an empty - marker interface)
public interface title {}
tool class
public tool(id id) throws exception { this.span = new span(); this.span.addattribute(new attribute(attribute.id, (string)((object) id))); } public tool(classes classes) throws exception { this.span = new span(); this.span.addattribute(new attribute(attribute.class, (string)((object) classes))); } public tool(title title) throws exception { this.span = new span(); this.span.addattribute(new attribute(attribute.title, (string)((object) title))); } public tool(id id, classes classes, title title) throws exception { this.span = new span(); this.span.addattribute(new attribute(attribute.id, (string)((object) id))); this.span.addattribute(new attribute(attribute.class, (string)((object) classes))); this.span.addattribute(new attribute(attribute.title, (string)((object) title))); } public void test() throws exception { tool hammer = new tool((id)((object)"hammer")); tool poweredtool = new tool((classes)((object)"tool powered")); tool tool = new tool((id)((object)"invention"), (classes)((object)"tool powered"), (title)((object)"define new tool")); }
the approach requires interface per parameter "type" , down cast / cast specific interface "type" object , string...
i uncomfortable approach , i'm hoping there's design pattern out there alleviate desire subclass string (solely purpose of constructor method differentiation)...
i have variadic method takes arbitrary collection of name value pairs provide alternative fixed parameter constructors, constructors shown above common combinations , therefore convenience programmer presently being contemplated being provided...
thanks!
considering how constructors suggest rid of them , use builder pattern instead:
class tool { private tool() { // preventing direct instantiation private constructor this.span = new span(); } ... // tool class code public static builder builder() { return new builder(); } public static class builder { private final tool tool = new tool(); public builder withid(string id) { tool.span.addattribute(new attribute(attribute.id, id)); return this; } ... // other methods in same manner public tool build() { // add validation if necessary return tool; } } }
usage:
tool tool = tool.builder() .withid("id") .withclasses("classa, classb") .build();
Comments
Post a Comment