What's the use of metaprogramming?

后端 未结 11 688
清酒与你
清酒与你 2020-12-12 11:12

I\'ve read:

  • Wikipedia
  • Code Generation vs. Metaprogramming
  • The art of Metaprogramming
  • Metaprogramming at c2.com

and I

11条回答
  •  攒了一身酷
    2020-12-12 11:36

    We use meta-programming a lot to create properties in VBA. We have various Excel spreadsheets with many headers on them and we want to define getter/setter properties for each header, allowing us to manipulate cells under that header. Manually doing this would be a nightmare.

    The meta programming framework of choice for us was Notepad++ and its find/replace regular expressions capabilities. Here is how we meta-programmed our properties:

    • Copy a list of headers from Excel to Notepad++
    • Record a Notepad++ macro to clean up the data (remove whitespaces and special characters). At the end of this we have a list of newline separated strings.
    • Manually copy the list to another .CSV file and use Excel to generate a list of line numbers. Then copy back to Notepad++.
    • Write a regex to convert a property name into a property definition, adding all the whitespace, keywords etc. Use the line number as the column number in our property definition.

    At the end of this we have a process that's a mixture of manual steps, recorded macros and a regex that we can re-apply every time we want properties for a sheet. And we did! To great effect.

    That's the power of meta-programming. When to use it is a matter of experience/intuition. But I recommend answering this question:

    Will if be quicker for me to just code this directly, or can I automate some/all of the process, and speed up my process?

    That gives you a line to draw beyond which meta-programming is no longer useful. If you can just code it quicker, even if it's 10 repetitions, just do it! Only if it's hundreds of repetitions, or it's something you expect to reuse many times in future then meta program it.

    Another point is that there are degrees here. I once wrote a Java program to create a bunch of files for adding a new IntelliJ inspection to an inspections coding project. That was a fair bit of overhead: creating the Java project and compiling it etc. On the other hand, Notepad++ find/replace is just a tiny step above manually typing stuff yourself. The advice here is to start doing things manually and then automate as you see a need, only up to the point where it makes sense. No need for a Java program when Notepad++ will do. No need for Notepad++ when manually typing it will do.

提交回复
热议问题