On Github benhyland / validation-workshop-intro
As a definition:
What do we mean to do in our system? Stuff like:
We will implement the Validation concept.
This term can be used for different things, even within functional programming. Let's find out what it means for us.
SomeThing result = repository.getById(42); if(result != null) { doSomeThing(result); }
Slightly nicer:
Optional<SomeThing> result = repository.findById(42); result.ifPresent(this::doSomeThing);
Why might it be null? Perhaps something can break.
try { SomeThing result = service.performDangerousActionForId(42); doSomeThing(result); } catch (ServiceException e) { handleError(e); }
Slightly nicer:
Either<ServiceException, SomeThing> result = service.tryDangerousActionForId(42); result.ifLeft(this::handleError); result.ifRight(this::doSomeThing);
The remote agent or the service might throw an exception, for several hosts.
List<String> hosts = Arrays.asList("host1", "host2", "host3"); List<SomeOtherThing> results = new ArrayList<>(); List<Exception> errors = new ArrayList<>(); for (String host : hosts) { try { SomeThing firstResult = remoteAgent.lookupSomeThingOnHost(host); SomeOtherThing secondResult = service.useSomeThing(firstResult); results.add(secondResult); } catch (RemoteException | ServiceException e) { errors.add(e); } } if(errors.isEmpty()) { doSomeOtherThings(results); }
It might look something like this:
List<String> hosts = Arrays.asList("host1", "host2", "host3"); List<Validation<Exception, SomeThing>> firstResults = Validation.mapInputs(hosts, remoteAgent::tryLookupSomeThingOnHost); List<Validation<Exception, SomeOtherThing>> secondResults = Validation.flatMapInputs(firstResults, service::tryUseSomeThing); Validation<Exception, List<SomeOtherThing>> result = Validation.sequence(secondResults); result.ifSuccess(this::doSomeOtherThings); result.ifFailure(this::handleAllErrors);
Optional, Either and Validation are all examples of sum types.
A sum type is a data type with several mutually exclusive representations:
http://github.com/benhyland/validation-workshop