- Mastering JavaScript Functional Programming
- Federico Kereki
- 308字
- 2021-07-02 22:41:15
Stubbing
This is a use case similar in some aspects to polyfill: having a function do different work depending on the environment. The idea is to do stubbing, an idea from testing, which means replacing a function with another that does a simpler job, instead of doing the actual work.
A common case is the usage of logging functions. You may want the application to do detailed logging when in development, but not to say a peep when in production. A common solution would be writing something along the lines of:
let myLog = someText => {
if (DEVELOPMENT) {
console.log(someText); // or some other way of logging
} else {
// do nothing
}
}
This works, but as in the example about Ajax detection, it does more work than it
about Ajax detection, it does more work than it needs since it checks every time if the application is in development. We could simplify the code (and get a really, really tiny performance gain!) if we stub out the logging function, so it won't actually log anything:
let myLog;
if (DEVELOPMENT) {
myLog = someText => console.log(someText);
} else {
myLog = someText => {};
}
We can even do better with the ternary operator:
const myLog = DEVELOPMENT
? someText => console.log(someText)
: someText => {};
This is a bit more cryptic, but I prefer it, because it uses a const, which cannot be modified.
Given that JS allows calling functions with more parameters than arguments, and that we aren't doing anything in myLog() when we are not in development, we could have also written () => {} and it would have worked fine. I do prefer, however, keeping the same signature, and that's why I specified the someText argument, even if it wouldn't be used; your call!
- Developing Mobile Web ArcGIS Applications
- Python自動(dòng)化運(yùn)維快速入門(第2版)
- React Native Cookbook
- Implementing Cisco Networking Solutions
- Python機(jī)器學(xué)習(xí)算法與實(shí)戰(zhàn)
- Scala程序員面試算法寶典
- Windows Phone 7.5:Building Location-aware Applications
- Fast Data Processing with Spark(Second Edition)
- C++語言程序設(shè)計(jì)
- Java編程從入門到精通
- 大學(xué)計(jì)算機(jī)應(yīng)用基礎(chǔ)(Windows 7+Office 2010)(IC3)
- Android開發(fā)進(jìn)階實(shí)戰(zhàn):拓展與提升
- Kotlin程序員面試算法寶典
- Office VBA開發(fā)經(jīng)典:中級(jí)進(jìn)階卷
- FORTRAN程序設(shè)計(jì)權(quán)威指南