Question

For example, if I have two classes "Director" and "Follower". I want the Director to tell the follower where to go (ex: follower1.go(direction.LEFT)), and I want the Director to know what directions it can tell the Follower to go when coding in an IDE that gives completion suggestions.

I know I can already either do:

public void go(String direction);

or

public void goLeft();
public void goRight();
public void goUp();
public void goDown();

But the first won't give me options in an IDE (or at least, I don't know how to show the options), and the second could be hard to maintain for a less trivial function. Ideally, I would like something like,

public enum Direction{LEFT, RIGHT, UP, DOWN};
public void go(Direction direction);

But of course, that doesn't work (at least in Java, and Direction is part of the Follower class). Is there a roundabout way to use enums (or any other way) to get something like the 3rd effect, where I can both limit the parameters of a function, and make it easily visible in an IDE that gives completion suggestions?

Was it helpful?

Solution

I think if you remove public, it will work:

enum Direction{LEFT, RIGHT, UP, DOWN};

though I believe it that this enum will only be accessible to other classes that are in the same package as Follower.

Why does Direction need to be contained within the Follower class, when the Director (which I assume is a separate class) will also need to make use of it? If you want to limit the scope of this enum, you could declare it in the same package, but in a separate file. That way you can change it to having public scope when you need it to be accessed elsewhere, and the syntax for accessing it is neater and cleaner, too.

OTHER TIPS

There are two ways you can with this.

As FrustratedWithFormDesigner pointed out, you can make the enum a top level entity.

The other option is to leave it as a inner-member of one of you classes. To do this, you can either qualify the enum with the host class name:

go(Follower.Direction.LEFT);

Or you can import the enum and use as you would normally expect:

import somepackage.Follower.Direction
...
go(Direction.LEFT);

Now, in your case, I would probably suggest going with the top-level enum, as Direction doesn't strike me immediately as "belonging" to either Follower or Director.


For completeness, I should mention there's actually a third way to access the enum elements: static imports. This method should be used judiciously, if at all, but it is something to be aware of.

import static somepackage.Direction.*;
....
go(LEFT);
Licensed under: CC-BY-SA with attribution
scroll top