Functional Refactoring: Unleashing the Power of Pure Functions
In our article, we embark on a journey to enhance the quality of our code by incorporating helpful methods. Our existing codebase leverages the CSharpFunctionalExtensions package, crafted by Vladimir Khorikov. This package is a treasure trove of utility classes, including Result, Maybe, Entity, and ValueObject. Notably, Result and Maybe play pivotal roles in enabling us to craft honest (pure) functions — functions whose behavior is transparently conveyed by their return types. For a deeper understanding of the Result class, feel free to explore our dedicated article.
In this article, we’ll illuminate our concepts through a simple yet powerful example — a CRUD operation revolving around the Author entity. By employing Result and Maybe, we aim to articulate how these helper methods contribute to code clarity, readability, and maintainability. Our objective is to deliver a clear and concise understanding to our audience, making the adoption of these techniques an accessible and enlightening experience.
All the above codes are very old I tried refactoring it to be more functional way instead of a lot of branching {} and if statements.
1- Remove my helper package and add my Result and Entity … to control to add my own helper methods, will remove CSharpFunctionalExtensions.
2- Add my Result Class
3- MayBe class
4- add my helper methods
I explain this helper method, The Bind method takes input and returns the new result of the input not changing the result from the output of the function, The second helper method is a map that maps result of the function to the Result, The third method is Apply when you have a lot of methods that method all must be success to execute a statement that depend on the result of all these methods. this all methods that I need to refactory our code you can extend and add more overloading methods like apply which takes many arguments, and map method which map result of func to another result.
5- add some shared validation to reusing like checking string empty
Rewrite our code toward a more functional way
I use a mediator package to remove any logic from the controller and to make our controller thinner.
All code in this article will be found in our GitHub repo. also, you can see the more powerful package Language.Ext but encourage for using you custom helper must not depend to package.