When to use macros?

Is it correct to say:

Macros should only be used when we are branching over context - or establishing a context. When branching over values and conditions, only functions must be used.

In simple words If you have some function lets say index in 20 different controllers. Which receive same set of params .You can use macro . Write one generic macro and use it in 20 controllers.(In my opinion).

In my book there are two valid use cases for macros:

  1. You want to extend the functionality of your module (i. e. you want or need to require extra modules inside the calling module). For example you could use it to keep the amount of configuration small when writing a library.
  2. You have a problem domain that demands additional operators because it allows the problem to be formulated in a much more natural way. I actually think this is the main reason why you should utilize macros.

If I understand the first part of your own definition correctly it maps cleanly onto the first of the afforementioned points. The second allows for something like this: https://github.com/expede/witchcraft#haskell-translation-table although I will admit that the example might be a little artificial. :wink:

1 Like

Good usages of macros:

  1. As others have said: repeatable and generic copy-pastable snippets.
  2. Inject a lot of use, alias, import or requires with one line.
  3. Your own DSL – that is their main use in my eyes.
1 Like

My general statement of when to use macro-like things in languages is when you are needing to do something that is impossible to do efficiently in any other way.

3 Likes