mercredi 1 juillet 2015

Java constructor (anti-pattern) super-classing String

The intention of the following design is to allow String values to be (in effect) subclassed to enable a number of what would be conflicting constructor methods to be established (e.g. the method signatures would be the same even though the parameter names would be different).

Kindly consider the following 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.ID, (String)((Object) id)));
}

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 a new tool"));
}

The approach requires an interface per parameter "type" and the down cast / up cast from the specific interface "type" to Object and then to String...

I am uncomfortable with the approach and I'm hoping that there's a design pattern out there that would alleviate my desire to subclass String (solely for the purpose of constructor method differentiation)...

I have a variadic method that takes an arbitrary collection of name value pairs to provide an alternative to the fixed parameter constructors, but the constructors shown above are the most common combinations and therefore as a convenience to the programmer they are presently being contemplated as being provided...

Thanks!

Aucun commentaire:

Enregistrer un commentaire