An Introduction to Metaprogramming

An Introduction to Metaprogramming 

In his article "An Introduction to Metaprogramming", master Ariel Ortiz explains the concept of metaprogramming, its several uses, and different ways to apply it depending the context of the problem to solve. 

As the prefix meta suggests, metaprogramming refers to the practice of writing code for a program that writes code for a program. Kind of confusing, but that's the essence of it. They are use to automatize code writing and agilizing software development, as they are faster than writing the code by hand. Most of them are found in Linux platforms, and are usually composed of compilers, interpreters, parser generators, assemblers and preprocessors.

After explaining this concepts, the author gives differents examples of metaprogramming by creating working code of C in Ruby, and viceversa, and proceeded to explain different elements that are very common in metaprogramming and easily implemented. First, he talks about eval, a function that is used in interpreting languages, like Lisp, Perl, Python, Ruby and JavaScript, where the programming language would evaluate the real values of the operation of a string. This is, you could declare an operation as a string and evaluate it to get the result:

eval("4 + 5")  ==>  returns 9 as result.

Another concept the author brings in are the quines, which is code that outputs its own text. The example seen in the lecture is the following:

f="f=%p;puts f%%f";puts f%f

Which prins itself when ran in the console.

To give an example of metaprogramming in the wild, we are given the accessors and initializers in Ruby. Instead of defining a variable, instancing it, and assigning its respective method to get its values or set them (Getters and setters), Ruby implements different accessors that internally create the getters and setters for the variables and initializers that substitute the code and writes in all what's needed for the object to be declared, reducing all the lines of code into 2 or 3 lines of code.

I think metaprogramming could be a good practice to simplify work when coding, but one must only implement it when it is a really complex code that requires it, or you could be complicating yourself too much. Plus one must be experienced with metaprogramming, as errors could lead to possible vulnerabilities to the code, like the probability of others making code injection or modifying values.

Comments

Popular posts from this blog

Moon Machines

Understanding the SOLID Principles

Hidden Figures