Re: How to specify a parameter
Luca D. wrote:
Hello!
When I create an instance of a class, I have to specify a direction,
which can be "Left" or "Right".
I thought about:
public class Object {
Perhaps you should name your class "String" or "System"
to avoid confusion. ;-)
private String direction;
public Object(String direction) {
this.direction = direction;
}
}
Object o = new Object("Left"/"Right");
Otherwise:
public class Object {
private final int left = 0;
private final int right = 1;
private int direction;
public Object(int direction) {
this.direction = direction;
}
}
Object o = new Object(0/1);
In this case everyone must know that left = 0 and right = 1.
Is there a common way/design pattern to solve this kind of problem?
Several, with various advantages and disadvantages.
public class Obtuse {
public static final int LEFT = 0;
public static final int RIGHT = 1;
private int direction;
public Obtuse(int direction) {
this.direction = direction;
}
}
...
Obtuse o = new Obtuse(Obtuse.LEFT);
Advantage: Simplicity. Disadvantage: Allows `new Obtuse(-42)'.
public class Obnoxious {
private static class Direction {
private Direction() { }
}
public static final Direction LEFT = new Direction();
public static final Direction RIGHT = new Direction();
private Direction direction;
public Obnoxious(Direction direction) {
this.direction = direction;
}
}
...
Obnoxious o = new Obnoxious(Obnoxious.LEFT);
Advantage: Built-in type safety. Disadvantage: Clutter.
public class Obese {
public enum Direction { LEFT, RIGHT }
private Direction direction;
public Obese(Direction direction) {
this.direction = direction;
}
}
...
Obese o = new Obese(Obese.LEFT);
Advantage: It's all the rage. Disadvantage: More clutter.
--
Eric Sosman
esosman@ieee-dot-org.invalid