My coworker was talking about enums a few weeks ago, and I blew him off, but then I cracked the Gang of Four book, and it is so dense I started to try to code the samples so I could understand things better. And right away they start with an enum:
enum Direction{North, South, East, West}
And so out of sheer ADD, I started puzzling over how to do something like this in Coldfusion. Basically, to be able to say this argument wants an integer limited to the following values, and those values will mean this. Obviously, merely using the generic "numeric" type and then validating inside the function is neither self-documenting nor reusable.
Best I've come up with so far is this:
Enums = CreateObject("component", "packages.utils.enums.EnumLibrary").Init();
Direction = Enums.Enum("packages.utils.enums.Direction");
Room = CreateObject("component", "packages.maze.Room").Init();
Permitted values for Direction: #Direction.PermittedValues#.
Room.SetSide(Direction.North, "Wall");
Room.SetSide(Direction.East, "Door");
Room.SetSide(Direction.South, "Wall");
Room.SetSide(Direction.West, "Door");
Side #Direction.North.Index# - #Direction.North.Value# #Room.GetSide(Direction.North)#;
Room.SetSide is defined:
function SetSide(packages.utils.enums.Direction, String);
Unfortunately, this requires a component for every single enum (packages.utils.enums.Direction). It also requires that the type/name for each enum item (North, South, East, West) is that cfc, which means instantiating 4 objects, as far as I can figure (reusing the object creates lots of reference problems).
When originally creating the packages.utils.enums.Direction cfc, you just have to provide a list (THIS.Definition = "North,East,South,West"). EnumLibrary::Enum transforms each of those list items into members containing the enum object (enum.North = CreateObject("component", "packages.utils.enums.Direction").Init()).
Obviously, the enums library can be stored in server scope. And the enums don't have to be created before they are needed, but will then persist in the library as well. But that could mean a lot of objects sitting in memory.
And for the week of work and effort exploring various dead-ends until arriving at this solution, I still can't think of a circumstance where my life would have been so much easier for having enums...
No comments:
Post a Comment