In the previous part I introduced the Result class as a means of control flow and error handling. Now I will focus on when to use the Result class to return an Error, and when to throw instead.

Part of Functional Programming: Clean architecture and DDD series

There appears to be quite some different opinions on the subject:

  1. Always throw an Error
  2. Always throw errors and then only wrap them when you want to handle them
  3. Only return recoverable errors, throw the rest
  4. Return expectable errors, throw (or pass through) the rest.
  5. Return every error, never throw. …

When we add more functional composition tools to our belt, we can start composing usecase pipelines that are both terse and descriptive.

Part of Functional Programming: Clean architecture and DDD series

Operators

  • From previous article: map: (value => newValue) => Result<newValue, ...>
  • flatMap: (value => newResult) => newResult
  • toTup: (value => newValue) => readonly [newValue, value]
  • tee: (value => any) => Result<value, ...>
  • resultTuple: (...[Result<..., ...>]) => Result<readonly [value, value2, ...], error[]>

Sample

type CreateError = CombinedValidationError | InvalidStateError | ValidationError | ApiError | DbError // ({ templateId: string, pax: Pax, startDate: string }) => Result<TrainTripId, CreateError> pipe( flatMap(validateCreateTrainTripInfo), // R<{ pax…

We can improve our error handling and composition by leveraging a Result class and several other tools from the functional programming world.

Part of Functional Programming: Clean architecture and DDD series

Instead of throwing errors, we wrap our results. Either the Result is an Error value, or a Success value, in the process documenting the possible errors. Callers must first examine and unwrap the Result, handling either the Success or Failure case. Paving the way for more functional programming and composition.

For a more complete introduction to the Result class and Railway Oriented Programming:

For implementations check…


Recently, often the question is asked if Hooks and Context replaces Redux. It is more a question of do you need Redux, and perhaps how Hooks and Context can help you write cleaner, more functional, more composable code.

Part of Of Hooks and Screens series

Hooks by themselves are an alternative way to write and reuse logic between components. So they’re not any more “alternative” to Redux than classes. They’re just a way to write and compose code.

The question of whether you need Redux seems unrelated to Hooks to me.

- Dan Abramov (@dan_abramov) April 16, 2019

I stumbled…

Patrick Roza

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store