A no-op is a function that does nothing. No-op is short for no operation.
We commonly use no-ops to avoid writing if
statements. There's an example of this in the Identity Function glossary entry.
We're interested in the if
statements that are used to work out if a function should be called or not:
function myFunction(funcA: SomeFunctionType) {
if (some expression) {
funcA();
} else {
// do something else, because it isn't safe
// to call funcA()
}
}
We don't need the if
statement if it's always safe to call funcA()
. That's where the no-op comes in.
- We design
funcA()
so that it's possible to create a no-op for it. - Then it's up to the caller to pass in either a function that does something, or the no-op.
Our function don't care either way. It doesn't need to care.
function myFunction(funcA: SomeFunctionType) {
funcA();
}
We've eliminated the if
statement. That makes the code smaller, and makes our unit tests smaller, because we've eliminated complexity.