A Function’s Interface Is It’s Bond

TL;DR: A function must respect all arguments or return an error

The Arguments #

The only realistic way a function can fail its interface is how it treats arguments as mis-typed arguments or return values are usually caught by a framework

All The Arguments #

Be they required or optional arguments that are present, functions must respect all the arguments; they cannot ignore some because they are inconvenient or contradictory

“I’d like a number four with no cheese” #

One cannot stop paying attention just because we know what a #4 is. Functions and especially REST endpoints often accept resource ids or primary key values, which implicitly identify specific resources. Tempting as this easy lookup is, the function must apply all the arguments even if they are additional criteria. With a key value in hand, the function does not need additional criteria, but it cannot ignore them

A function could optimize1 by having a dedicated code path retrieving data via the key and testing that data against any additional criteria while having another code path to query by criteria without a key value, but that is unlikely to be a good decision. Datastores usually2 are perfectly capable of making this sort of optimization

No One Would Ask For That #

The function cannot make assumptions about what the caller wants; it must provide what the caller actually asked for, even if that seems nonsensical

While a USA address’ state is implicit in its zip code3, if a function accepts both state and zip code, it must ensure that its results meet both requirements: if the supplied state does not match the implicit state from the zip code, then it must return no addresses

And Nothing But the Arguments #

If a function abides by all the arguments it receives, then receiving an unknown argument must be an error condition. For compiled languages, spurious arguments are impossible. For other languages, they might be allowed. Take the time to detect and report them

HTTP is a line format: a text message where the contents have semantic meaning depending on what part of the message one looks at. One can often translate the HTTP method (verb) and path into a function call and required parameter (with the query-string acting as additional, usually optional, parameters). While HTTP frameworks can often detect extra and missing parameters an error (404 or 422), it is usually an option


  1. “…; premature optimization is the root of all evil (or at least most of it) in programming.” - Donald Knuth 

  2. always? 

  3. a business rule of the USPS 

 
0
Kudos
 
0
Kudos

Now read this

The Futures of Python

Futures defer execution of code. They can allow code to wait for external resources like file reads, network calls, and database access, and then automatically continue without stopping every other operation. They allow the definition... Continue →