bartlomey
bartlomey

Reputation: 39

Java Enum methods - switch vs Overriding for each object

Let's consider an enum.

What's the difference between creating one method with "switch(this)" for each object and creating one abstract method and overriding it for each object in enum?

Upvotes: 2

Views: 1012

Answers (3)

Cyril S
Cyril S

Reputation: 51

There isn't necessarily a difference while you don't change the enum. However, let's look at an example:

enum MyEnum {
    FIRST
    {
        @Override
        void foo() {
            //Do something
        }
    },
    SECOND
    {
        @Override
        void foo() {
            //Do something else
        }
    };

    abstract void foo();
}

Now, if we were to add a new element THIRD to this enum, then the compiler would ensure that we actually implement this method.

Let's look at the switch case instead:

enum MyEnum {
    FIRST,
    SECOND;

    void foo() {
        switch (this) {
        case FIRST:
            //Do something
            break;
        case SECOND:
            //Do something else
            break;
        default:
            break;
        }
    }
}

If we were to add a new element THIRD, then we would be able to forget adding an additional case to the switch statement, meaning we need to be more careful.

One more difference is then simply that switch can be used for external functionality with these enum objects, while we can't add additional methods to the enum itself.

Upvotes: 2

SJuan76
SJuan76

Reputation: 24845

The enum method has the advantage of following the Open/Closed principle. If you need to expand the enum, all you have to do is to implement the method for the new enum member and you are good; otherwise you have to go finding through your codes where your enum is used to cover all the possibilities.

The disavantage is that, if you are too strict about it, you may putting way too much things in your code. Imagine that you have an enum covering age ranges in your business level and you wish, at the UI level, to present a different layout based on the age of the user... obviously, adding a method to the enum specifying HTML details would break many abstraction levels.

I tend to use enum methods for issues that are related to the "core" functions of the enum, and using switches elsewhere.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533492

with a switch you can share code, many combinations of case labels for the same code.

If every enum is different (or mostly they are), I would use an override.

Note: you can have a default implementation and override the ones which are different.

Upvotes: 1

Related Questions