Published by

on

My Love-Love Relationship with Metalama

In the world of software development, we often hear about “love-hate relationships” with tools and technologies, where developers grapple with frustrations and joys alike. But today, I want to share my experience with a tool that defies the typical narrative. I’m talking about my unequivocal love-love relationship with Metalama.

When it comes to coding, every developer has faced their fair share of challenges. The struggle to maintain clean and maintainable code, eliminate repetitive boilerplate, and enforce coding standards can often feel like an uphill battle. Enter Metalama, a modern Roslyn-based meta-programming framework designed to simplify the lives of C# developers. Metalama promised one thing upfront: the elimination of repetitive code. And let me tell you, it delivers on that promise in ways that exceeded my expectations.

Unlike its older sibling, PostSharp, Metalama took a unique approach that immediately won me over. It eliminated the need for recompilation, allowing me to sidestep a common pain point in the development process. As a Unity and C# developer, I was eager to streamline my workflow and enhance the quality of my projects. With Metalama, I found a tool that not only met my expectations but far exceeded them. This is my story of how Metalama transformed my coding experience into a true love affair.

Note: While my experience with Metalama has been nothing short of amazing, there’s a caveat that’s worth mentioning. Currently, using Metalama directly in Unity projects isn’t straightforward due to Unity’s reliance on an older Mono-based compiler. However, this limitation isn’t a fault of Metalama itself. The good news is that Unity is actively working on modernizing its platform, including upgrading to the modern .NET framework with the Roslyn compiler. Once this transition is complete, it holds the promise of enabling developers like me to use Metalama directly within Unity, eliminating the need for pre-compiled assembly projects and further enhancing our coding experience. It’s an exciting development that we’re eagerly anticipating on the horizon.

Why Metalama?

In the world of software development, few things are as frustrating as grappling with repetitive code, commonly known as boilerplate. It clutters codebases, complicates maintenance, and invites errors during updates. This is where Metalama shines, offering a compelling reason for its adoption.

Eliminating Repetitive Code with Precision: Let’s take a look at a common scenario where parameter validation is essential. Below, we have a method that processes data, and it’s crucial to ensure that the provided data is not null, that the number is greater than or equal to 0, and the second number falls within a specific range (between 10 and 100, inclusive).

Method example without Metalama Aspects:

public void ProcessData(string data, int number, int number2)
{
    // Parameter Validation: Check for null data
    if (data == null) throw new ArgumentNullException(nameof(data), "Data cannot be null.");

    // Parameter Validation: Check if number is less than 0
    if (number < 0) throw new ArgumentException("Number must be greater than or equal to 0.", nameof(number));

    // Parameter Validation: Check if number is within a range
    if (number2 < 10 || number2 > 100) throw new ArgumentOutOfRangeException(nameof(number2), "Number must be between 10 and 100 (inclusive).");

    // Main method logic here...
}

As can be seen in this example with the highlighted line on main logic comment, even before starting to implement the actual logic of this method, we have to do lots of parameter validations. Going with this way, we would have hundreds, thousands maybe ten thousands of validation checks like these in our codebase.

Enter Metalama: A Boon for Code Quality: Now, consider the same method with Metalama aspects.

Method example with Metalama Aspects:

public void ProcessData([NotNull] string data, [GreaterThan(0)] int number, [Range(10, 100)] int number2)
{
    // Main method logic here...
}

With the use of Metalama aspects, the parameter validation is simplified and streamlined. The [NotNull] aspect ensures that data is not null, the [GreaterThan(0)] aspect checks if number is greater than 0, and the [Range(10, 100)] aspect validates that number falls within the specified range. Metalama handles these validations during compilation, reducing the need for manual checks and boilerplate code.

So if the operation of throwing exception when the parameter validation fails isn’t included in the method, where and how does it happen? To answer this question, I’ll give you the implementation of one my custom Metalama aspects. You can find more custom aspects in my open-source project which is also available as a NuGet package: https://www.nuget.org/packages/Atesh.Metalama/#readme-body-tab

public class NotNullAttribute : InputValidationAspect
{
    // ReSharper disable once InconsistentNaming
    public override void Validate(dynamic? value)
    {
        if (value == null) throw new ArgumentNullException(((INamedDeclaration)meta.Target.Declaration).Name);
    }
} 

public abstract class InputValidationAspect : ContractAspect
{
    public override void BuildEligibility(IEligibilityBuilder<IParameter> Builder)
    {
        base.BuildEligibility(Builder);

        Builder.MustBeReadable();
    }
}

As can be seen on the highlighted line in NotNullAttribute implementation, we just need to implement the parameter validation and exception throwing operation only once in our entire code base. From now on, we can simply apply this simple [NotNull] aspect to any parameter we desire in our codebase instead of repeating the same null check parameter validation thousands of times.

Conclusion

In the ever-evolving landscape of software development, tools that streamline workflows and enhance code quality are like hidden gems waiting to be discovered. My journey with Metalama, which I’ve fondly referred to as my “love-love relationship,” has been nothing short of transformative.

A Love-Love Relationship with Code: We’ve explored how Metalama excels in eliminating the scourge of repetitive code with surgical precision. Gone are the days of manual validation checks and boilerplate that clutter codebases and complicate maintenance. With Metalama, code becomes cleaner, more concise, and easier to manage. It’s a tool that delivers on its promise with precision, enhancing code quality with every compilation.

Acknowledgments

I’d like to take a moment to extend my heartfelt appreciation to the incredible Metalama team. Their dedication to crafting this exceptional tool has been nothing short of remarkable. But what truly sets them apart is their unwavering commitment to the .NET and Metalama communities. On the Metalama Slack server, I’ve witnessed firsthand the tireless efforts of the team members as they help users navigate challenges, troubleshoot issues, and foster a sense of camaraderie among developers. Their responsiveness and willingness to go the extra mile have made the Metalama experience even more enriching. It’s not just a tool; it’s a community of passionate individuals who share a common goal: elevating the art of coding. My sincere thanks to the Metalama team for their outstanding support and for making this love-love relationship with code possible.

Blog at WordPress.com.