25 October 2018

Boosted Enum

Usage:

package org.catcher.example.boostedenum;

import org.catcher.example.boostedenum.some.SomeRepository;
import org.catcher.example.boostedenum.some.SomeService;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class Main {

    public static void main(String[] args) {

        SomeRepository repo = mock(SomeRepository.class);
        when(repo.getFactor()).thenReturn(5);

        SomeService service = new SomeService(repo);

        System.out.println(service.compute(SomeService.Type.REGULAR, 2));
        System.out.println(service.compute(SomeService.Type.SPECIAL, 2));
        System.out.println(service.compute(SomeService.Type.SOMETHING, 2));

    }
}

Example of SomeService class:

package org.catcher.example.boostedenum.some;

import java.util.function.BiFunction;

public class SomeService {

    public enum Type {

        REGULAR(SomeService::computeRegular),
        SPECIAL(SomeService::computeSpecial),
        SOMETHING(SomeService::computeSomething);

        private final BiFunction<SomeService, Integer, Integer> algorithm;

        public BiFunction<SomeService, Integer, Integer> getAlgorithm() {
            return this.algorithm;
        }

        Type(BiFunction<SomeService, Integer, Integer> algorithm) {
            this.algorithm = algorithm;
        }
    }

    private final SomeRepository repo;

    public SomeService(SomeRepository repo) {
        this.repo = repo;
    }

    public int compute(Type type, int data) {
        return type.getAlgorithm().apply(this, data);
    }

    int computeRegular(int data) {
        return data * repo.getFactor();
    }

    int computeSpecial(int data) {
        return data * 6;
    }

    int computeSomething(int data) {
        return data * 2;
    }
}

Repo:

package org.catcher.example.boostedenum.some;

public interface SomeRepository {
    int getFactor();
}