What is metaprogramming?

Metaprogramming

Simple code generation means a program that takes input and produces an output.

But can we write a program that can read, change, or even create other programs?

Yes. We can do this through metaprogramming, which is essentially “Code that writes code.”

Code that writes code

Consider a baker who bakes cakes. One day they realize that they’re just repeating the same steps again and again to do the same thing. They create a machine that bakes cakes. They create a factory that makes machines that bake cakes with more demand. This concept is called metaprogramming.

The concept of metaprogramming

Metaprogramming enables us to write self-changingCode that can change its instructions during execution. code. It gives us the ability to control when and what is compiled.

Example

An example of metaprogramming is the Logger module in applications containing references or function calls to logging.

In Elixir metaprogramming, we can use macros to skip the overhead of function calls to logging. We can recreate the Logger macro and give it the ability to be enabled or disabled easily. We can then use our own created macro and enable it accordingly.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved