Vladimir Sedach

Have Emacs - Will Hack

June 8, 2009

Why your language needs macros

Topic: Software engineering

A couple of days ago someone started yet another "why do I need macros?" thread on Hacker News. Many of the usual arguments and examples arguing for macros were posted. Noted absence were the arguments against macros (all of which seem to be a variation on "programmers are too dumb to understand someone else's macros" - if you were at the Great Macro Debate at ILC 09 you would have heard it stated more eloquently).

I have been thinking about macros in terms of domain-driven design lately, kicking around my idea of "domain onions" (planning to write more about that later), so I decided to post my current thoughts about why every programming language that aspires to be general-purpose needs macros:

I used to like arguing over the Internet about this subject. There are many good technical and management/organizational arguments you can make for and against macros. What I have come to realize is they are all pretty much irrelevant.

The entire point of programming is automation. The question that immediately comes to mind after you learn this fact is - why not program a computer to program itself? Macros are a simple mechanism for generating code, in other words, automating programming. Unless your system includes a better mechanism for automating programming (so far, I have not seen any such mechanisms), _not_ having macros means that you basically do not understand _why_ you are writing code.

This is why it is not surprising that most software sucks - a lot of programmers only have a very shallow understanding of why they are programming. Even many hackers just hack because it is fun. So is masturbation.

This is also the reason why functional programming languages ignore macros. The people behind them are not interested in programming automation. Wadler created ML to help automate proofs. The Haskell gang is primarily interested in advancing applied type theory.

Which brings me to my last point: as you probably know, the reputation of the functional programming people as intelligent is not baseless. You do not need macros if you know what you are doing (your domain), and your system is already targeted at your domain. Adding macros to ML will have no impact on its usefulness for building theorem provers. You cannot make APL or Matlab better languages for working with arrays by adding macros. But as soon as you need to express new domain concepts in a language that does not natively support them, macros become essential to maintaining good, concise code. This IMO is the largest missing piece in most projects based around domain-driven design.