Receive Policies Instead of Data
Hi folks, today I wanna share something that drew my attention while reading Confident Ruby.
Avdi presents the following method:
And its invocation:
This code is not good at all.
- the method worries to much in handling edge cases (error, logs)
- The
true, true
in calls todelete_files
does not help. We have to refer to the method definition to remember what those flags mean. - What if we wanted to log using a special format? Or to somewhere other than STDOUT? There is no provision for customizing how errors are logged.
- What do we do if we ever decide to handle permissions errors differently from
no such file or directory
? Add yet another flag?
The book point us the fundamental problem: both ignore_errors
and log_errors
attempt to specify policies using data.
Let's fix this by passing a block as argument:
Look how flexible it is now. We define a default behavior for error handling but also let it open for customization by calling a given block.
What if we need more control over the behavior? Just pass more policies:
Conclusion
Block and proc as argument help callers to specify policies, freeing us from hard-coded decisions which someone else could make.
Written on October 11, 2018