Random enum

As a software engineers or software developers we need to test what we are implementing (you have a description of types of tests here). When implementing these tests, we can hardcode the data we are using or, we can randomly generate it what, despite we can think it is going to make our life more difficult when debugging errors, it is going to make it easier in the long run. Our code should not be linked to the data it is processing, it should be generic for the type of data it is expecting.

To do this, the easiest way is to implement or use libraries that implement random generators. One of the most interesting and one it is always forgotten is the random generator for our enums.

In Java, there is an easy way to implement it.

It can be just for one enum class:

private static CarBrand randomCarBrand() {
    return CarBrand.class.getEnumConstants()[new Random().nextInt(CarBrand.class.getEnumConstants().length)];
}

Or, even more interesting, it can be a generic random generator that it receives as a parameter an enum class and return the random value:

public static <T extends Enum<?&gt;&gt; T randomEnum(Class<T&gt; clazz) {
    int x = random.nextInt(clazz.getEnumConstants().length);
    return clazz.getEnumConstants()[x];
}

We can see an example here:

import java.util.Random;

public class RandomEnum {

    public static void main(String[] args) {

        for (int i = 0; i < 10; i++) {
            System.out.println(randomCarBrand());
        }
    }

    private static CarBrand randomCarBrand() {
        return CarBrand.class.getEnumConstants()[new   Random().nextInt(CarBrand.class.getEnumConstants().length)];
    }

    enum CarBrand {
        ARUTI_SUZUKI,
        TATA,
        HONDA,
        HYUNDAI,
        FORD,
        MAHINDRA,
        SKODA,
        ARIEL,
        ASHOK_LEYLAND,
        ASTON_MARTIN,
        AUDI,
        BAJAJ,
        BENTLEY,
        BMW,
    }
}

Do not forget, from know on, if you are not doing it, try to make all your tests, except if you want to test an edge case, random and see how it goes.

Random enum

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.