Developus
Developus

Reputation: 1462

How to substitute switch statement with better solution - clean code hints

I created a code, which have to convert ContentDataType into MIME types. For example - ContentDataType is a simple String like ImageJPEG and now I use MediaType.IMAGE_JPEG_VALUE to convert it into image/jpeg. But I use switch to do this. This is a code:

 public static String createContentType(ContentDataType contentDataType) {
        String contentType;

        switch (contentDataType) {          
            case IMAGE_JPG:
                contentType = MediaType.IMAGE_JPEG_VALUE;
                break;
            //next media types
        }
    return contentType;
 }

What is a better and elegant way to do this? I do not want to use if, but maybe some polymorphism? Can you give me any hints?

Upvotes: 2

Views: 737

Answers (2)

Anil Agrawal
Anil Agrawal

Reputation: 3026

This type of operation should be used Enum.

If you have all the known possible options for your ContentDataType, then create a enum for the same.

Then you can store string as well as MIME type. like below,

enum ContentDataType{
    IMAGE_JPG("ImageJPG", "image/jpg"),
    IMAGE_GIF("ImageGIF", "image/gif");
    String contentType;
    String mimeType;
    ContentDataType(String contentType, String mimeType){
        this.contentType = contentType;
        this.mimeType = mimeType;
    }
}

Or you can use MimeType object as well as below

import com.google.common.net.MediaType;
enum ContentDataType{
    IMAGE_JPG("ImageJPG", MediaType.JPEG),
    IMAGE_GIF("ImageGIF", MediaType.GIF);
    public String contentType;
    public MediaType mimeType;
    ContentDataType(String contentType, MediaType mimeType){
        this.contentType = contentType;
        this.mimeType = mimeType;
    }
}

Upvotes: 1

Guillaume Barré
Guillaume Barré

Reputation: 4218

If you are ready to use just one if/elseYou can do something like this :

private static Hashtable<String, String> types = new Hashtable<>();

static{
    types.put(IMAGE_JPG, MediaType.IMAGE_JPEG_VALUE);
    types.put(IMAGE_PNG, MediaType.IMAGE_PNG_VALUE);
    types.put(IMAGE_XXX, MediaType.IMAGE_XXX_VALUE);
}

public static String createContentType(ContentDataType contentDataType) {
    if types.containsKey(contentDataType) 
        return types.get(contentDataType);
    else
        throw new RuntimeException("contentDataType not supported");
    }
}

This allows you to add new supported types into the Hashtable whitout having to deal with a long sequence of if/else if/else.

Upvotes: 3

Related Questions