Java Enum question

sorry guys, this is IDEA unrelated but I hope this can be useful to
someone else.

Can someone explain me why is the test below not working?

@Test(groups = "util")
public class EnumTest {
    private static final String RECORD = "RECORD";
    private static final String PAY = "PAY";

    public void testStatusEnum() {
        assertEquals(RECORD, this.switchTest(Status.RECORD));
        assertEquals(PAY, this.switchTest(Status.PAY));
    }

    private String switchTest(Status status) {
        String ret = null;
        switch (status) {
            case RECORD:
                ret = RECORD;
            case PAY:
                ret = PAY;
        }
        return ret;
    }

    enum Status {
        PAY, RECORD;
    }
}

I'm new to Enums as you may have guessed, and it seems the natural way
to use a switch.

rgds
-nodje

15 comments
Comment actions Permalink

Can someone explain me why is the test below not working?

@Test(groups = "util")
public class EnumTest {
   private static final String RECORD = "RECORD";
   private static final String PAY = "PAY";

   private String switchTest(Status status) {
       String ret = null;
       switch (status) {
           case RECORD:
               ret = RECORD;
           case PAY:
               ret = PAY;


You are not testing for the string constants!

Should be

   switch (status) {
     case Status.RECORD:
       ...
     case Status.PAY:
       ...
   }

0
Comment actions Permalink

Can someone explain me why is the test below not working?

@Test(groups = "util")
public class EnumTest {
   private static final String RECORD = "RECORD";
   private static final String PAY = "PAY";

   private String switchTest(Status status) {
       String ret = null;
       switch (status) {
           case RECORD:
               ret = RECORD;
           case PAY:
               ret = PAY;


You are not testing for the string constants!

Should be

   switch (status) {
     case Status.RECORD:
       ...
     case Status.PAY:
       ...
   }

0
Comment actions Permalink

didn't you forget to insert break; into switch cases?

0
Comment actions Permalink

Using multiple return points in a method often leads to clearer and less deeply indented code, plus in this case might have prevented a bug. I do not understand why some coding standards forbid them.
Also the @Test annotation is missing from your code, but I assume this is just test code, and your actual code includes it. And finally the semicolon in the enum class is redundant. I end up with:

import org.junit.Test;

import static org.junit.Assert.*;

public class EnumTest {
    private static final String RECORD = "RECORD";
    private static final String PAY = "PAY";

    @Test
    public void testStatusEnum() {
        assertEquals(RECORD, this.switchTest(Status.RECORD));
        assertEquals(PAY, this.switchTest(Status.PAY));
    }

    private String switchTest(Status status) {
        switch (status) {
            case RECORD:
                return RECORD;
            case PAY:
                return PAY;
            default:
                throw new AssertionError();
        }
    }

    enum Status {
        PAY, RECORD
    }
}



Bas
0
Comment actions Permalink

I forgot to mention, you should enable the "fallthrough in 'switch' statement" inspection, to help you detect such switch statement problems earlier.

Bas

0
Comment actions Permalink

nodje wrote:

sorry guys, this is IDEA unrelated but I hope this can be useful to
someone else.

Can someone explain me why is the test below not working?

@Test(groups = "util")
public class EnumTest {
   private static final String RECORD = "RECORD";
   private static final String PAY = "PAY";

   public void testStatusEnum() {
       assertEquals(RECORD, this.switchTest(Status.RECORD));
       assertEquals(PAY, this.switchTest(Status.PAY));
   }

   private String switchTest(Status status) {
       String ret = null;
       switch (status) {
           case RECORD:
               ret = RECORD;
           case PAY:
               ret = PAY;
       }
       return ret;
   }

   enum Status {
       PAY, RECORD;
   }
}

I'm new to Enums as you may have guessed, and it seems the natural way
to use a switch.

Most of the time, you don't want to use a switch.

Sometimes its unavoidable, but usually its not.

Instead, make the behavior part of your enum:

enum Status {
     PAY {
        public String describe() {
           return "PAY";
        }
     },
     RECORD {
        public String describe() {
           return "RECORD";
        }
     }
     ;
     public abstract String describe();
}

Remember, each enum value has its own class, so you can take full
advantage of polymorphism. Also, each enum value has its own instance,
so you can use constructors and member variables as well.

Most of the time, you should only use a switch statement if you are
converting from a legacy code base. Even then, you should see if it
improves the design to move the cases into polymorphic methods.

In other words, if you are writing a new switch statement, you are
likely to be doing it wrong.

Of course, there are exceptions to this rule. Its not dogma, but close
too it ;)

0
Comment actions Permalink

right Wi Wi, I forgot it
The test behaves as expected with break;.

Looking at the syntax, it didn't strike me that it was necessary.
As Daniel said it's probably a structure to avoid.

0
Comment actions Permalink

Hi Daniel, thanks for your reply.

I fell for a switch statement as I was try to replace String constants.
Enums does a good job at that, but then I faced the point where I had to find a way to do different things according to the Enum value used.
Switch appeared as an obvious way to do that.

Now that you mention it, and after having made that fall-through mistake, it seems pretty clear that it's better to avoid it.

But how do you implement condition on enum values? If condition?

if (status == Status.PAY)
//do sthig
else if (status == Status.RECORD)
//do else
else throw new AssertionException()

Switch syntax is pretty neat compare to that!

rgds
-nodje

0
Comment actions Permalink

thanks, very useful inspection!
I wish I had it enabled already, would have saved me precious time...

-nodje

0
Comment actions Permalink

nodje wrote:

Hi Daniel, thanks for your reply.

I fell for a switch statement as I was try to replace String constants.
Enums does a good job at that, but then I faced the point where I had to find a way to do different things according to the Enum value used.
Switch appeared as an obvious way to do that.

Now that you mention it, and after having made that fall-through mistake, it seems pretty clear that it's better to avoid it.

But how do you implement condition on enum values? If condition?

if (status == Status.PAY)
//do sthig
else if (status == Status.RECORD)
//do else
else throw new AssertionException()

Switch syntax is pretty neat compare to that!

Yes, switch is better than if/else/else, but polymorphism is even better ;)

0
Comment actions Permalink

In this specfic case "return status.name();" would have the same effect
as the switch.
In general to get enum-value-specific behavior you can also have an enum
implement an interface and supply an implementation for each value.
From Effective Java (highly recommended):

// Emulated extensible enum using an interface
public interface Operation {
     double apply(double x, double y);
}

public enum BasicOperation implements Operation {
     PLUS("+")
             {
                 public double apply(double x, double y) {
                     return x + y;
                 }
             },
     MINUS("-")
             {
                 public double apply(double x, double y) {
                     return x - y;
                 }
             },
     TIMES("*")
             {
                 public double apply(double x, double y) {
                     return x * y;
                 }
             },
     DIVIDE("/")
             {
                 public double apply(double x, double y) {
                     return x / y;
                 }
             };
     private final String symbol;

     BasicOperation(String symbol) {
         this.symbol = symbol;
     }

     @Override
     public String toString() {
         return symbol;
     }
}




nodje wrote:

Hi Daniel, thanks for your reply.

I fell for a switch statement as I was try to replace String constants.
Enums does a good job at that, but then I faced the point where I had to find a way to do different things according to the Enum value used.
Switch appeared as an obvious way to do that.

Now that you mention it, and after having made that fall-through mistake, it seems pretty clear that it's better to avoid it.

But how do you implement condition on enum values? If condition?

if (status == Status.PAY)
//do sthig
else if (status == Status.RECORD)
//do else
else throw new AssertionException()

Switch syntax is pretty neat compare to that!

rgds
-nodje

---
Original message URL: http://www.jetbrains.net/devnet/message/5252697#5252697

0
Comment actions Permalink

What you share is all my need and we all hope you can share us more info further time. And I like shopping online, for the coming Christmas Day ( http://www.overgift.com/ ) want to prepare beauty http://www.overgift.com** in that day, and search online, and find some info. More, used to buying kinds shoes online shop and yesterday I found unusual shoes called http://www.vibrambazaar.com/** which really tract my eyes. Then no words to say I bought a pair http://www.vibrambazaar.com/** not for myself, sent this as a gift for my father who love sport. So if you want to live a happy life you should concern more things around you, buy Christmas tree on http://www.overgift.com/** and http://www.vibrambazaar.com/** online shop. Come and more choices.

---
Original message URL: http://devnet.jetbrains.net/message/5278482#5278482

0
Comment actions Permalink

A round http://www.pandora-bracelets-australia.com/ cut has the http://www.pandora-bracelets-australia.com/ greatest http://www.pandora-bracelets-australia.com/pandora-charms/pandora-bangles/ number of facets, http://www.pandora-bracelets-australia.com/ and if properly proportioned, will appear http://www.pandora-bracelets-australia.com/ the most brilliant. An emerald http://www.pandora-bracelets-australia.com/pandora-earrings/ cut diamond has the fewest facets, http://www.pandora-bracelets-australia.com/pandora-beads/ so larger stones are need to make an impressive  display.Clarity: All diamonds, except the most rare, http://www.pandora-bracelets-australia.com/pandora-necklaces/ has some kind of mark,nick, or cloudiness to them http://www.pandora-bracelets-australia.com/ caused by flaws. http://www.pandora-bracelets-australia.com/ The clarity of the diamond is measured by an alphabetical and  numerical scale with the diamonds in the “F” category http://www.pandora-bracelets-australia.com/pandora-beads/ being completely http://www.pandora-bracelets-australia.com/pandora-beads/ flawless.

---
Original message URL: http://devnet.jetbrains.net/message/5279130#5279130

0
Comment actions Permalink

Inexpensive price tags of
http://www.tagreplicawatches.com/ give you a nice possibility to own a few pairs of best http://www.tagreplicawatches.com/ or even an impressive collection. Exquisite Watches site presents the best http://www.tagreplicawatches.com/Rolex.html offered by online vendors. Buy best quality replica watches from our http://www.tagreplicawatches.com/ store. Here you can find interesting information about Breitling Company and http://www.tagreplicawatches.com/Breitling.html . On our site ,you can find replica breitling watches,http://www.tagreplicawatches.com/Tag-Heuer.html ,replica hublot watches and more.

---
Original message URL: http://devnet.jetbrains.net/message/5282884#5282884

0

Please sign in to leave a comment.