With macros + primary constructors @dart_lang becomes insane ๐
Example: from a 50+ lines of code to just 1
Stay tuned, because this is going to be game-changing ๐คฏ
Let's see what is the problem, why it matters, how it works, and how your dart code will change (forever ๐ฅ) ๐
The problem with dart code
How is it possible that some code can be reduced from 70 lines of code to just 2?
Today to write a data class with equality (==), serialization/deserialization (toJson, fromJson), immutability (@immutable, copyWith) you need the following in dart:
Notice ๐: These are 70 lines for a single class
Two new features are coming to dart that will cause a revolution:
How so? Well, the above 70 lines will be shortened to just 2:
Macros and Primary Constructors in dart
Take a look at the highlighted snippet below, see if you notice the problem (and the solution):
See how many times we need to repeat firstName, lastName, and age?
This is what in programming is called Boilerplate Code ๐
If you take a second look now it's easy to notice: the only "relevant" information in the class are the parameters and their types, everything else is repeated ๐คฏ:
Ideally we can reduce the code to just the following:
Guess what, we are not even satisfied with that ๐ โโ๏ธ
What matter at the end are the parameters:
Primary constructors come to the rescue to solve this issue as well:
Finally, we need to actually apply the macro to this code, so we end up with the initial 2 lines:
There is more.
Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 600+ readers.
How macros (will) work in dart
macro allows to write code that takes code as parameters.
Metaprogramming refers to code that can operate on other code as if it were data: take code in as parameters, reflect over it, inspect it, create it, modify it, and return it.
Static metaprogramming means doing that work at compile-time.
These 2 new features together have the potential to skyrocket dart to another dimension ๐
I plan to explore the progress and experiment with alpha and beta releases in the upcoming months. I will share more content and snippets as new details become available ๐
If you are interested to learn more, every week I publish a new open source project and share notes and lessons learned in my newsletter. You can subscribe here below ๐
Every week I build a new open source project, with a new language or library, and teach you how I did it, what I learned, and how you can do the same. Join me and other 600+ readers.