What's the deal with enums?

Hello,
I'm trying to familiarise myself with the new Java features that project Tiger (Java 1.5) will introduce. I come from a C++ programming background. I very briefly studied enums whilst I learned C++ and never used them in my programs, so I was, quite frankly, relieved when I learned that Java didn't support them.
But now it does.
I'm wondering, from a software design and engineering perspective, what benefit enums will add to the Java language and software engineering in general. I have read some pleas and arguments for enums. As I understand those arguments, proponents feel that minor ledgibility improvements to switch statements (which some OO programmers don't use on the basis that it weakens the object-orientedness through its goto-esque break statements) necessitate the addition of a whole other structure.
Out of curiosity, wouldn't it be more advantageous for Sun to put their efforts into supporting constant strings in switches in addition to primitive data types if people are so concerned with clarity?
I fail to understand what enums will do that constant string arrays or constant values cannot. I would like to think that Sun wouldn't add C++ features unless if there was a reason to do so, so I believe that there are good reasons to introduce this feature.
Please help clarify this confusion.
Thank you!

Comments on the previous posting inline. Note: I'll go off on a few tangents, but try to always return to the issue of enums. The fact that I go off on tangents (related initially to an enum type example) should show that enums help eliminate numerous problems.
Fair enough, but wouldn't this accomplish the same thing in
a slightly wordier wayPretty much. But you still have the validation code in there yourself:
currentDirection = ( direction > 0 && direction < 5 ? direction : 0 );People can still accidentally enter an invalid value, and it won't get caught by the compiler. So, I could call set(Compass.WEST) and hope/expect that is equivalent to set(Direction.LEFT). This will only occur if both Compass.WEST and Direction.LEFT are the same int value. If they are not, then we are in trouble. Worse, still if Compass.WEST and Direction.RIGHT are the same value, the code will compile, and run without any illegal value flagging, but our traveller will go off in the wrong direction.
Error handling tangent: Given the implementation, the error handling is not performed in set, rather the illegal value is captured as a zero, which must be dealt with at a later time - say in a switch statement that calls get. This is not a good idea - it increases the "distance" between the error occuring (bad call to set) and the error being detected (if xInt != 0). The larger the distance, the harder debugging is. If you throw an exception in set the bug is immediately flagged. With enums, none of this should be necessary.
Implementation tangent: set, get and currentDirection are static. This is not a good idea - it only allows one direction. If you have multiple travellers, each would have a Direction object, but (sticking with constants) UP, etc. would still be static.
I keep the switch statement in my enum workaround, but I believe that
the second reply suggested that enum could altogether eliminate the
use for switch statements. How exactly would it do that?enum in its simplest form would not remove switch. However, using an extension of the type-safe enum idiom (i.e. the current Java approach to enums), you can embed direction specific logic in each of the "enum" members. If I understand the enum-spec correcly, this will also be possible with the Java 1.5 enum language facility.
So, for an example, sticking with the domain: Consider a class Location, with x and y elements, and a Direction. The non-OO, non-enum approach would be as follows:
class Location {
    int x,y;
    void move (final int direction) {
        switch (direction) {
            case UP:
                --y;
                break;
            case DOWN:
                ++y;
                break;
            case LEFT;
                --x;
                break;
            case RIGHT:
                ++x;
                break;
            default;
                throw new RuntimeException("Invalid direction " + direction);
class Direction {
    public static final int UP = 1;
    public static final int DOWN = 2;
    public static final int LEFT = 3;
    public static final int RIGHT = 4;
}Note that I've deliberately been loose with my visibility. All logic is in Location, and Direction is dumb. If we go with a type safe-enum idiom, we get:
class Location {
    int x,y;
    void move (final Direction direction) {
        if (direction == Direction.UP) {
            --y;
        } else if (direction == Direction.DOWN) {
            ++y;
        } else if (direction == Direction.LEFT) {
            --x;
        } else if (direction == Direction.RIGHT) {
            ++x;
        } else { // direction is null
            throw new NullPointerException("null direction");
class Direction {
    public static final Direction UP = new Direction();
    public static final Direction DOWN = new Direction();
    public static final Direction LEFT = new Direction();
    public static final Direction RIGHT = new Direction();
    private Direction () {} // the ctor is private to limit instances
}This code is a rewrite of the int approach, but is "type-safe". We've moved from switch to if as we can't switch on object references. Note: there is still error handling code, as you're not "null-safe" (I don't know what the Java 1.5 spec says about this)
Little else has changed - the responsibilities are still the same. We can address this by going OO, which removes the if (formerly a switch) statement, but does couple the classes.
class Location {
    int x,y;
    void move (final Direction direction) {
        direction.move(this);
class Direction {
    private final int xOffset, yOffset;
    private Direction (final int xOffset, final int yOffset) {
        this.xOffset = xOffset;
        this.yOffset = yOffset;
    public static final Direction UP = new Direction(0,1);
    public static final Direction DOWN = new Direction(0,-1);
    public static final Direction LEFT = new Direction(-1,0);
    public static final Direction RIGHT = new Direction(1,0);
    void move(final Location location) {
        location.x += xOffset;
        location.y += yOffset;
}This removes any conditional logic, embedding (constructor parameterised) logic within Direction. It also eliminates the "null-safe" check, as direction.move(this) will throw an NPE if a null is passed.
Also, I've read some things saying that enum reduces 'boilerplate'
code. What exactly does that and 'boilerplate' mean?The Direction class is an example of the type-safe enum approach currently used in Java. It has been enhanced with logic for movement. Even if I dropped this logic, there is still functionality worth adding to the Direction class - a toString method that returns one of "UP", "DOWN", etc (shown next); a way to serialize the object and retain reference equality - you have to write a readResolve method (not shown).
class Direction {
    private final String name;
    private Direction (final String name) {
        this.name = name;
    public static final Direction UP = new Direction("UP");
    public static final Direction DOWN = new Direction("DOWN");
    public static final Direction LEFT = new Direction("LEFT");
    public static final Direction RIGHT = new Direction("RIGHT");
    public String toString() {
        return name;
}Once you've written this code for one type-safe enum, you've written them for them all. You copy-cut-paste, and rename the class/elements. All this code is predictable. It is "boiler plate". Now, if you gave me a compiler that generated all this code for me, when I present it with
enum Direction {UP, DOWN, LEFT, RIGHT}; then I've got something that reduces my boiler plate code to zip.... Enter the Java 1.5 compiler.

Similar Messages

  • I opened a file on my desktop that I don't remember putting there.  It turned out to be a keychain certificate from a client of ours.  Does this mean that they were spying on me?  What is the deal with that?  Any ideas?

    I opened a file on my desktop that I don't remember putting there. We use many photos and I thought it was a photo file I was looking for. It turned out to be a keychain certificate from a client of ours.  Does this mean that they were spying on me?  What is the deal with that?  Any ideas?

    Interesting tid bit.  I created an AAC of the original file, deleted the original MP3 from my library and also deleted the Clean matched track from the icloud.
    Result is that it matched with the explicit version of Mrs. Officer this time.
    What I am curious about is which songs this is happening for. I've went thru a few batched of about 500 songs at a time and redownloaded in 256k for many tracks. Sadly we don't have people to bring this to our attention and I have so much music that it's impossible to go thru every song to make sure I am getting the right version.

  • What's the deal with dual processors???

    The whole dual processor thing has been bugging me for some time now. If I have a dual 500mhz processor, is it the same as a 1.0ghz processor, worse than one, better than one?! Are there other factors at play? In my limited scope, if you had a dual 500, 533, whatever, it would be the same as a single 1.0ghz - and yet these dual processors are priced much cheaper. I really am at a loss as to how computers do their processing, and how to compare single processor G4's and dual processor G4's when making a purchase.
    Insight would be greatly appreciated!

    And you shouldn't forget, the future is multiprocessors. There is a limit to miniturization, and the solution seems to be multiplication. So operating systems and applications are increasingly going to be multiprocessor-aware. Maybe a perfect example is the upcoming MacOS release, Snowleopard. Apparently, there will be almost no cosmetic changes. The changes will essentially be 'under-the-hood'. And you can bet, that some of those changes will be increased efficiency with respect to multiple processors.
    So what's the deal with airplane peanu...err, dual processors?
    The advantage, theoretically is, having more workers to do the work. Your 1ghz processor is like a worker who can lift 100kg, and your 500mhz are like workers who can lift 50kg each.
    So where's the advantage? If you have a farm with 40 kg hay bales in the field that you need to pick up, your better off with two workers than one right? Or 8 workers in the case of a 8-core MacPro. So an multiprocessor-aware operating system, doles out the work much more efficiently, spreading the tasks around, or spreading a single task around in pieces (if the app is so written).
    You've heard of render farms? The multiple computers used to render the frames of animated movies? Its the same principle. Having computer 1 render the first 1000 frames and computer 2 the next, the project gets done within a lifetime. If they had had only one computer, ToyStory would still not be finished.
    Its the future. Just wait till the end of this year for example. Nehalem chips will be sporting even more processors.
    Try these;
    http://discussions.apple.com/thread.jspa?threadID=1619399&tstart=0
    http://arstechnica.com/news.ars/post/20070605-intel-updates-compilers-for-multic ore-era.html
    Nehalem; http://techreport.com/discussions.x/12130

  • What's the deal with the video format?

    Hello! What is the deal with the video format? Does it mean I have to code the videos for 640*480 ? It won't accept any other size? What size do I need to select for widescreen format?
    With Quicktime pro I've been able to encode videos with a very nice resolution and small size, then try to synch them to the ipod touch and then the error, it can't be played. I use the .mov format, I like it more but if I have to use .mp4 then I'll use it.
    Thanks for the help!

    According to Apple's Specification, these are your video choices
    H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats.
    H.264 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Baseline Profile up to Level 3.0 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats.
    MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats.
    http://support.apple.com/kb/SP496

  • What's the deal with the CC menubar panel?

    What's the deal with the CC menubar panel? The tab to the apps are gone -- looks like it wants me to update the panel itself rather than list my installed apps. I've been on CC for about a month, is this common? Thankfully I can still open all apps normally, but the internet seems to think the "CC Way" is a horror show.
    Do you guys have trouble after updating the updater? All this talk of running "the cleaner" (a mafia term?) and reinstalling everything with each version bump is kinda scary. It could be that people only post online when things go wrong, and 95% of people update just fine. But since I'm new I guess I'd want some reassurance before committing to a night of Cleaning and Reinstalling...
    I'm one of those people who think app updates very 12 to 18 months was just fine (and stable). Would it be harmful to ignore updates for a few months? Lets see, I have a healing brush, smart objects, a blob tool, pretty good 3D in AE, ID seems to handle type pretty well… there's really no reason to update every month is there?
    -- Jim

    Has anyone had a normal non-cleaning install of this week's update?

  • What's the deal with Quicktime?

    What's the deal with Quicktime? In the past, there was just plain Quicktime. Then it was separated into two different versions: Standard and Pro. I bought the Pro version for my eMac. Then, when I moved to my 24" iMac, Quicktime was made into just one version again, and the features were rolled into it. Now that I have my 27" iMac running Lion, I find that a bunch of the menu items are greyed out and have the word "Pro" next to them. Also, I'm finding that it can't open many standard files, such as .MOV files that run fine on my older Mac, because "a required codec is not available." What's going on?

    There are two versions of QuickTime Player available for Snow Leopard and Lion systems. The QuickTime Player X included with those versions of Mac OS X have some of the features previously only available with a Pro key to unlock QuickTime Player 7.
    QuickTime Player 7 is an optional installation on SL and Lion, and apparently you installed it or it carried over across an update. If you wish the Pro features activated, you need to enter in your Pro key just as you did previously (you will need a key for QuickTime 7; an older key will not work). Then the Pro features will be available again, though support for some old codecs is no longer available. For more information, see:
    http://support.apple.com/kb/HT3678
    Regards.

  • What's the deal with the swoosh sound when sending texts? IOS 5.1 needs to have an option to turn it off., What's the deal with the swoosh sound when sending texts? IOS 5.1 needs to have an option to turn it off.

    What's the deal with the swoosh sound when sending texts? IOS 5.1 needs to have an option to turn it off., What's the deal with the swoosh sound when sending texts? IOS 5.1 needs to have an option to turn it off.

    Trax and kirt are correct. I'm pretty good with technology, being an engineer and all, and I can tell you for a fact that this 'swoosh' sound (triggered by a successfully sent SMS) can NOT be disabled from ANY menu in iOS 5. The ONLY way to disable it is to flip the silent switch on the left hand side of the phone. This is extremely annoying for some people (like trax, kirt, and myself). For what we pay for Apple products and, in particular, this phone, we simply didn't expect to have to deal with such annoyances. That's why we're Mac users. Please fix this bug.
    I feel like I shouldn't have to say this but it bears repeating: turning off message sounds from the 'sounds' menu does not fix his problem. It still emits the swoosh noise. Whoever suggested this clearly didn't try it because it obviously doesn't work. Who posts a solution to a problem without knowing for a fact that their solution is correct? I find that response condescending because he writer is assuming we're not smart enough to have tried it. In reality, it's vice versa.

  • What's the deal with bluetooth mice ?

    What's the deal with bluetooth mice ? I've never heard of any model yet that didn't come with loads of complain... (I've done my research) ... isn't there one that just works fine and that will for a few years like a standard mouse ?
    I would really like one with my macbook, any recommendation, something portable, that matches well my hardware would be nice.
    Or should I just wait until bluetooth mice technology works flawlessly ? What about you ?
    Francis.

    I've had a Macally BtMouseJr for a couple of years now, it's fairly basic but every time I've tried to replace it with a "better' one I've had to come back because of lock ups, losing the mouse altogether, slow response, random movements et al.
    Therefore the BtMouseJr is the ONLY one I can actually recommend (I retract my prvious recommendation of the Sony vaio mouse - it's nice but it doesn't always work and eats batteries) wholeheartedly.
    see it here.

  • My computer died and I had to buy another one.  Now I can't sync my ipod classic.  What is the deal with this?  I added songs about three months ago and it was fine.  Now it won't sync.  It says it has a duplicate file.

    My computer died and I had to buy another one.  Now I can't sync my ipod classic.  What is the deal with this?  I added songs about three months ago and it was fine.  Now it won't sync.  It says it can't sync because there is a duplicate file.

    There are server problems right now with iMessage effecting some users.  See http://www.apple.com/support/icloud/systemstatus/.

  • HT202213 My apple TV no longer finding my movies and photos. What's the deal with this?

    My apple TV no longer finding my movies and photos. What's the deal with this?

    That would be awesome, if the nearest service area wasn't 4 hours away.... It would cost me just as much in gas to drive down there as it would just to buy a cheap replacement off of ebay...

  • I am getting my third battery and charger! What's the deal with poor quality?

    My macbook is a late 2009 model.  It's always been running great, but I have some key issues that are making me question ever buying a mac again... For starters, I am purchasing my third battery and charger since owning this computer.  I am not very happy with the quality of these devices...  The battery is buldged out, and looks like it's ready to explode any day! The power supply is frayed, and exposing bare wires!  What is the deal with such poor quality products? I always thought Apple was top notch in high quality, but lately, I've been proven wrong...
    Power cord:
    Battery:
    Seems to me that these issues REALLY need to be addressed by Apple.  The reviews on the power supplies are ridiculous!  Numorous complaints, yet Apple has YET to do anything about it!  So my question is, what is Apple going to do about these issues?  These need to be addressed, and fixed, ASAP!  I owned a Dell laptop for 6 years, and never had an issue with the batteries I had, OR the power supply, and it cost me half the price of this macbook.

    That would be awesome, if the nearest service area wasn't 4 hours away.... It would cost me just as much in gas to drive down there as it would just to buy a cheap replacement off of ebay...

  • What is the deal with this thing?

    My computer no longer recognizes my ipod mini, won't charge it, or anything. It isn't responding to anything. I have tried resetting it so many times. All it does is show the "Do not disconnect." screen, and the backlight turns on when I press a button on the click wheel. My computer does not acknowledge that the ipod is connected to it at all, so I just diconnected it. However, the screen still says the same thing! I cannot find anyway to get some help off the Apple site. There are e-mail addresses or anything, which is completely annoying. My ipod mini is 13 months old and cost way too much money for this to be happening. Is it lost for good? What is the deal with this thing? Seriously, please help.

    First of all, try another port on your computer. Some ports are not connected direct to the motherboard and do not recognize the iPod as well as those that are. Reset the iPod each time you connect it to another port.
    Still no joy, see these.
    Your Windows PC doesn't recognize iPod.
    iPod appears in Windows Explorer but does not appear in iTunes.
    iPod does not appear in iTunes.
    Fast user switching in Windows XP is not supported.
    Strange iPod behavior.
    When restoring the iPod, put it into disk mode first.
    Putting iPod into disk mode.

  • What is the Deal with US Bank?

    Hey Guys/Gals,        What is the Deal with US Bank? I applied and barely qualified for VISA Signature for a CL of 5K. Are they generally conservative? Fee

    Congratulations on your approval! It's good to have your foot in the door with U.S. Bank; especially on the Visa Signature level. As others have mentioned, they are pretty conservative. I have had some hiccups with them in the past, but once you establish a rapport with them, they tend to loosen up.  Good luck in building up your relationship. I have had decent auto CLIs once in a blue moon and the last HP CLI increased my limits by 15K+ across two cards. 

  • What is the deal with the iOS 7.1? I downloaded it yesterday. This am my phone was at 100%. 4 hours later it was 14%---and I didn't do anything I don't usually do, and my battery will last all day!

    What is the deal with the iOS 7.1? I downloaded it yesterday. This am my phone was at 100%. 4 hours later it was 14%---and I didn't do anything I don't usually do, and my battery will last all day!

    Have a look here >  How to trouble-shoot iOS 7.1 battery problems

  • What is the deal with facetime

    what is the deal with facetime for iphone 4s

    Wow.  That could not be more vague.
    There is no "deal".
    What are you talking about?

Maybe you are looking for