by Zak · 4y ago · 0 comments
(first-working
(get-it-from-the-cache)
(get-it-from-the-database)
(get-it-from-an-external-api)
(compute-it-the-slow-way)
default-value)
Note each of those functions could throw an exception. You want to ignore it (or you could log it) and move on to the next. for f in GetFromCache, GetFromDatabase, GetFromAPI, Compute:
try:
return f()
except Exception as ex:
log(ex)
return default_value
(You'd probably define a custom exception class for your application that represents the kinds of errors you can tolerate, so you don't end up swallowing programming errors, but you get the idea.)In Common Lisp:
(defmacro return-first-working (&body body)
"Expects a sequence of expressions as body.
Returns the value of the first expression of body
which returns without error."
(when body
`(handler-case ,(first body)
(error ()
(return-first-working ,@(rest body))))))
(return-first-working
(error "hi")
(error "there")
(error "!")
"hello-world"
(error "wtf?"))
That way I can easily implement primitive control structures, without resorting to add to my code visibly complex things (like making expressions into functions).Above is a recursive macro, which takes its subexpressions and returns a simplified expression, reusing itself. That way code transformation itself is described as a recursive process. One can learn how to apply such transformation patterns to the code itself and then it gets relatively easy to write.
(first-working
(get-it-from-the-cache (or local-cache default-cache))
(get-it-from-the-database current-database-connection)
(get-it-from-an-external-api (ask-user-for-api-credentials))
(compute-it-the-slow-way foo bar baz)
default-value)
Each expression can be arbitrary code where to do something similar in Python you'd need to compute a thunk in advance.There's also an advantage in clarity because an abstraction can be defined. Once you know what first-working is for, the purpose of this block of code is clear as soon as you read the first token. Using a pattern instead of an abstraction, it's necessary to read the whole loop to make sure it's really the pattern you think it is.
def atdt_exception_suppression(*list_of_fns):
...
What you've done is leverage the fact that functions are first class objects in Python (ie, can be passed as arguments) to achieve the same result as a macro. Which is cool, it works. Probably slightly better than a macro for this use case because we get a neat function boundary.But macros are a powerful option because it doesn't matter if functions are first class or not. If you are using a language where functions aren't first class objects, a macro system would let Zak implement anyway.
So you are correctly identifying that Python can implement this in an alternate way as a function, but a macro system is sufficient to do this and a whole batch of other tricks even if first class functions aren't available as a feature.
def get_from_cache
get_from_cache!
rescue NoRecord
nil
end
Then you just do this to not only do it all but only do it once lazily on access: def record
@record ||= get_from_cache || get_from_database || get_from_api || compute || default_value
end
Be slightly better if ruby supported a proper null coalescing operator like C# ?? and ??= or Perl // and //= but as long as you stay way from "false" as a valid value it works fine.Assume, for purposes of the exercise that someone else wrote some of the methods you're calling and they do not behave this way. You could write your own wrappers, but that's a lot more code to write and maintain than a simple control structure that doesn't care what's inside it.
firstWorking() ?? getItFromTheCache() ?? getItFromTheDataBase() ?? getItFromAnExternalApi() ?? computeItTheSlowWay() ?? defaultValue;
Perl OR short-circuit:
firstWorking() or getItFromTheCache() or getItFromTheDataBase() or getItFromAnExternalApi() or computeItTheSlowWay() or defaultValue;
const firstSuccessfulOptionValue = fnReturnsOption
.orElse(fn2ReturnsOption())
.orElse(fn3ReturnsOption())
.orElse(fn4ReturnsOption())
.getOrElse("val");
[0]https://github.com/sbernheim4/excoptional/blob/main/src/inde... cache.get
.orElse(db.get)
.orElse(api.get)
...