News for hackers. Stuff that matters.
Re:Ask HN: What are the best programming tricks you know? by throw1234651234 on Monday July 25, 2022 @09:34AM (#32224022)
What? How?
Re:Ask HN: What are the best programming tricks you know? by chriswarbo on Monday July 25, 2022 @10:20AM (#32224658)
Here's a "functionalised" API:

    GET https://example.com/users?postprocess=result.sort("signup-date").reverse
This is easy to implement: just send the 'postprocess' parameter through 'eval()'. It's completely general, allowing the data to be sorted, filtered, transformed, etc. in any way the caller likes.

It's also completely insecure, since it executes arbitrary code. It's also hard to refactor, since there's always a chance that some caller's postprocess parameter is relying on e.g. a particular variable name, etc.

Here's a "defunctionalised" alternative:

    GET https://example.com/users?sort=signup-date&order=descending
Instead of allowing arbitrary code, we only accept a description of what to do (sort by "signup-date" in descending order). This requires we implement all the logic ourselves, as well as parsing and branching-on the input to determine what was requested.

Defunctionalised APIs are the norm on the Web (except for those who accept raw SQL...); whilst functionalised APIs are the norm inside applications. For example, `myList.map(myArbitraryFunction)`. Defunctionalising is a good way to break systems into modules, with the descriptions acting as the interface.

Re:Ask HN: What are the best programming tricks you know? by flipflip on Monday July 25, 2022 @09:38AM (#32224077)
You write a simple interpreter basicly. Instead of directly manipulating the data , you build an ast of how to manipulate the data then you execute it. It also allows for nifty optimizations later on.