Created
July 20, 2018 02:01
-
-
Save fwfurtado/b4b229518b99f7dde7fd3e7c1ddd7647 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sample.rest.demo.either; | |
import org.junit.Test; | |
import sun.reflect.generics.reflectiveObjects.NotImplementedException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import static org.junit.Assert.assertEquals; | |
import static org.junit.Assert.assertTrue; | |
interface Either<L,R> { | |
default boolean isLeft() { | |
return false; | |
} | |
default boolean isRight() { | |
return false; | |
} | |
default R get() { | |
throw new NotImplementedException(); | |
} | |
default L getLeft() { | |
throw new NotImplementedException(); | |
} | |
static <L,R> Either<L, R> left(L content){ | |
return new Left<>(content); | |
} | |
static <L,R> Either<L, R> right(R content){ | |
return new Right<>(content); | |
} | |
} | |
class Left<L, R> implements Either<L, R> { | |
private final L content; | |
@Override | |
public boolean isLeft() { | |
return true; | |
} | |
Left(L content) { | |
this.content = content; | |
} | |
@Override | |
public L getLeft() { | |
return content; | |
} | |
} | |
class Right<L,R> implements Either<L, R> { | |
private final R content; | |
@Override | |
public boolean isLeft() { | |
return false; | |
} | |
@Override | |
public boolean isRight() { | |
return true; | |
} | |
Right(R content){ | |
this.content = content; | |
} | |
@Override | |
public R get() { | |
return content; | |
} | |
} | |
public class EitherTest { | |
@Test | |
public void shouldHaveOnlyOneValeInEither(){ | |
double number = Math.random() * 10.0; | |
int value = Double.valueOf(number).intValue(); | |
Either<List<Exception>, String> content = random(value); | |
assertTrue(content.isLeft()); | |
assertEquals(1, content.getLeft().size()); | |
assertEquals(IllegalArgumentException.class, content.getLeft().get(0).getClass()); | |
} | |
public Either<List<Exception>, String> random(int value){ | |
if (value % 2 == 0) { | |
List<Exception> errors = new ArrayList<>(); | |
errors.add(new IllegalArgumentException()); | |
return Either.left(errors); | |
} | |
return Either.right(String.valueOf(value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment