metaprogramming with javascript
TRANSCRIPT
Jakarta
What is Metaprogramming
is the writing of computer programs that write or manipulate other program (or themselves) astheir data, or that do part of the work at compile time that otherwise be done at runtime
“writing code that writes code
Jakarta
The Purpose
To have super power!
• More elegant code
• Less boilerplate code • Hide the how, focus on what • Essential in framework building
Jakarta
Background
• My first encounter: Prototype.js, jQuery
• Experimenting with my own parsing (zparse) and angular like framework foo.js (2007)
• Then created chain.js batik etc. (2008-2010)
• Now maintaining Merapi and its plugins (for YesBoss / Kata.ai)
I love Metaprogramming
Jakarta
Uses in Real World
• Almost every framework uses Meta Programming in some way
• Domain Specific Languages
• Add functionalities without littering main logic (logging, measurement, etc.)
Jakarta
Two Flavours
Dynamic Language FeaturesProgram can inspect itself using built-in features of the language.
Code GenerationTranslate meta features into generated code in target language.
examples: jquery spring (java) rails (ruby) merapi ;)
examples: QT (C++) CoffeeScript React Babel / Typescript
Jakarta
Dynamic Language Features• Reflection
• Getter Setter
• Proxy
• Decorator
• Generator
• DOM Manipulation
• Eval
Jakarta
Reflection
• for (let i in object);
• .prototype, getPrototypeOf()
• getOwnPropertyNames(), defineProperties()
• typeof etc…
Jakarta
Getter Setter
• {set prop() {}, get prop() {}}
• Object.defineProperty()
• Object.defineProperties()
Jakarta
Proxy
• it’s a trap!
• replace object access by function invocation
• create truly dynamic object
• warning: slow performance
• handlers:
• get(), set(), has(), ownKeys(), …
Jakarta
Performance
• Code Generation (compile/transpile):
• No impact performance (however depends on implementation)
• Runtime (processed during initialization only)
• Could lead to slower initialization (still ok in most cases)
• Runtime (heavy use)
• Be careful!
Jakarta
Conclusion
• It is like doing black magic:
• know what you are doing
• can have side effects if not used properly
• Performance Trade-Off
• Unclear Program Flow
• Devs not familiar with the core can get confused