Refactoring: Functional Decorators
John Peters
Posted on October 24, 2020
Image of decorating the sidewalk with Chalk Art
Staying in tune with Polymorphic Composition where the majority of our code parts are Javascript or Typescript functions, we will begin to see a pattern whereby base functions can easily have more functionality simply using another function. This other function uses what is known as decorator pattern. The base function never changes.
By "never changing working code" we simply add a function which calls an existing function but returns a different result.
Consider this Angular route function:
/** Using the route, parse the id param
* @returns id e.g. route/id
*/
export function funcGetRouteId(
ar: ActivatedRoute
) {
let currentRoute = ar.snapshot;
let id = currentRoute.paramMap.get("id");
let person id = Number.parseInt(id);
return personId;
}
In the code above the id of the route is returned using angular's route snapshot. e.g. /person/id where id is the number.
The Decorator
/**Parses the route id
* @returns True if id is greater than zero
* (meaning existing person)
* False if person id is not greater than zero
*/
export function funcIsExistingPerson(ar:ActivatedRoute) {
// we reuse the existing code but
// provide a different result
let id = funcGetRouteId(ar);
if (id > 0) return true;
return false;
}
The caller's code looks like this:
if (funcIsExistingPerson(this.ar)){
// don't show icon until change;
this.SaveIconAction
.saveIconVisibility = "none";
}
None of the internals of how it was done are exposed, however, the naming of the function makes it clear what it's doing.
The caller merely needs to hover over the function to pick up the API comments.
A New Way of Thinking
When we start dialing-into what decorators do for us, we spend more time thinking about the base-function. Each base-function can have a minimum of 2n-1 decorators based on the number of parameters it requires.
When we start seeing code possibilities based on the Permutations of the parameters used, we are thinking outside of all specific solutions, and more into reusable parts.
Warning: It's pretty easy to get carried away with decorators, once we dial into thinking of Permutations. It's better; however, not to just write code because "someday" we may need it. Unless of course, we are writing utility programs.<\sub>
JWP2020 Functional Decorators
Posted on October 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
November 27, 2024