barbara
barbara

Reputation: 3201

Need advice in enum design structure in Java

I have an enum which is quite weird for me.

enum PoolType {

    FIXED(4),
    CACHED,
    SINGLE;

    private int threadsAmount;

    private PoolType(int threadsAmount) {
        this.threadsAmount = threadsAmount;
    }

    private PoolType() {
    }

    public int getThreadsAmount() {
        return threadsAmount;
    }

    public PoolType withThreads(int threadsAmount) {
        this.threadsAmount = threadsAmount;
        return this;                    
    }
}

Actually I want to know is it OK by design or maybe there are some errors?

PS

I cau use it in a way like this

new ExecutionStarter(PoolType.CACHED.withThreads(5));

Upvotes: 0

Views: 88

Answers (3)

Jama Djafarov
Jama Djafarov

Reputation: 358

Enum type is: "An enum type is a special data type that enables for a variable to be a set of predefined constants..."

your approach seems unconventional.

I would use a factory/façade to pass the type/size parameters which will create a pool for me. The enum type seems redundant in this case.

Upvotes: 0

icza
icza

Reputation: 417642

Enums should be immutable. Yours isn't:

PoolType.CACHED.withThreads(5);
System.out.println(PoolType.CACHED.getThreadsAmount()); // Prints 5

PoolType.CACHED.withThreads(4);
System.out.println(PoolType.CACHED.getThreadsAmount()); // Prints 4

I would advise against it.

If you pass PoolType.CACHED.withThreads(5) to an ExecutionStarter and then PoolType.CACHED.withThreads(4) to another ExecutionStarter, if the first one gets threads amount via getThreadsAmount() later in time than the creation of the other, the first ExecutionStarter might also see a value of 4 instead of 5!

Upvotes: 4

Edwin Buck
Edwin Buck

Reputation: 70909

If you need to modify the number of threads, you'll need two classes.

A Pool which can have it's threads configured, and a PoolType which can be an enum.

Since the enum only provides type handling, you are much better off ditching the type delegation via an enum pattern. Instead use the Java type system directly

public interface Pool ...
public class FixedPool implements Pool ...
... etc ...

This way you can have two fixed pools of different thread sizes.

Upvotes: 3

Related Questions