Advanced Topic 53 of 54 Programming Fundamentals
Metaprogramming
Code that inspects or generates other code at runtime or compile time.
How it works
Metaprogramming is writing code that manipulates other code: macros, decorators, templates, code generation, annotations or runtime modification of classes and functions. Programs treat code as data, inspecting or building it at compile time or run time. This allows libraries to remove boilerplate and offer very expressive APIs.
Step-by-step walkthrough
- Ordinary code is data that other code can read.
- Meta code such as macros, decorators or templates transforms it.
- New code is generated at compile time or runtime.
- The generated code runs like hand-written code.
- It removes boilerplate but is harder to debug.
Where it is used
ORMs that generate methods from database schemas, web frameworks using decorators to register routes, serialization libraries, test frameworks and domain-specific languages rely on metaprogramming. Lisp macros and Rust procedural macros are well-known examples.
Common pitfall
It is hard to debug and understand because the code that runs is not the code that was written. Error messages become confusing, tools struggle with it and behavior can change unexpectedly. Use it sparingly with clear conventions and documentation, and prefer plain functions when they are enough.
Where it fits in the course
Metaprogramming is topic 53 of 54 in Programming Fundamentals, rated Advanced. It follows Memoization. The next topic is Reflection.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Metaprogramming?
Where do people use Metaprogramming?
What is the most common mistake with Metaprogramming?
What should I learn before this topic?
How can I practice it?
Is Metaprogramming hard to learn?
How long does it take to learn Metaprogramming?
Which topics are related to Metaprogramming?
What should I study after Metaprogramming?
Related topics
- Memoization (Programming Fundamentals)
- Reflection (Programming Fundamentals)
- Monads (Programming Fundamentals)
- Currying and Partial Application (Programming Fundamentals)