An Introduction to Metaprogramming

After reading the article "An Introduction to Metaprogramming", there are a few things that I would like to discuss through this blog entry, I would like to start by explaining what is a metaprogram. A metaprogram is a program that generates other programs or parts of a program. So, when we talk about metaprogramming we are talking about writing metaprograms. This kind of programs is useful to eliminate or reduce a tedious or error-prone programming task. 

There is a special kind of source generator named quines. A quine is a program that generates a copy of its own source text as its complete output. While other programs (dynamic programs) have the feature to modify some parts of the code during runtime without the need to generate a source code. For our course of Software Design and Architecture, we are using Ruby, which employs the feature to automate common programming task, a clear example is on classes, where you use an attr_accessor method to produce the read/write access methods automatically for a given attribute name. 

If we want to implement metaprogramming in our Ruby programs, we need to implement the following methods: 

- cls.define_method(name){body}
This adds a new instance method to the receiving class and takes as input the method's name (as a symbol or string) and its body (as a code block).

- cls.instance_variable_set(name,value)
This binds an instance variable to the specified value. The name of the instance variable should be a symbol or string, and it also should be included the @ prefix. 

I can conclude the there are a lot of techniques in programming and as a programmer, you should be able to know and apply many of them. Even though the name metaprogramming might sound a little scary it is not that difficult. With metaprogramming, we can automate our codes and be more efficient and I'm sure that we can apply this to all or to most of our projects. 

- References: 

Ortiz, A. (2007, June). An Introduction to Metaprogramming. Retrieved from http://34.212.143.74/apps/s201911/tc3049/activity_metaprogramming/

Comentarios

Entradas más populares de este blog

Microservices

Understanding the SOLID Principles

Ethical Reflection on Ready Player One