Assume there's a public void process
method on a Java class called A
that currently takes a single String
argument id
.
class A {
public void process(final String id) {
// Some implementation
}
}
The existing method's String
id
argument has a specific format: type#integer
where type
can be foo
or bar
(so foo#1
and bar#1
).
While the underlying implementation does not change based on the format of id, having the method take a String
seems less accurate than representing the argument as a concrete type, especially when unfamiliar readers examine the public interface of the class.
One approach is to represent the id
value as the Union
of two input types - a FooId
and a BarId
.
public void process(final Union2<FooId, BarId> id)
Another approach is to represent the id
value as a "generic" Id
class that wraps the two types and keeps track of the type based on an internal Type
enum
like
class Id {
private static final enum Type {
Foo,
Bar;
}
private final Type type;
private final int value;
private Id(final Type type, final int value) {
this.type = type;
this.value = value;
}
public static Id from(final String formattedId) {
// parse the type and value and return an Id instance
}
}
What are the tradeoffs between these two approaches?
Would you instead recommend using method overloading instead of a Union
?
public void process(final FooId id)
public void process(final BarId id)