CollinAlpert / Lombok.NET

.NET adaptation for Java's Lombok using Source Generators.
MIT License
309 stars 16 forks source link

Generator For freezable Pattern #33

Closed furesoft closed 1 year ago

furesoft commented 1 year ago

Hi,

it would be really useful to have an attribute that marks an object as freezable, so there is a freeze method. if the object is frozen properties cant be changed anymore

CollinAlpert commented 1 year ago

That's a good idea. How does this API sound to you?

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field)]
public sealed class FreezableAttribute : Attribute { }

[Freezable]
public partial class Person
{
    [Freezable]
    private string _name;

    private int _age;
}

// This part is generated
public partial class Person
{
    private bool _isFrozen;

    public string Name
    {
        get => _name;
        set
        {
            if (_isFrozen)
            {
                throw new InvalidOperationException("Person is frozen and cannot be modified.");
            }

            _name = value;
        }
    }

    public void Freeze()
    {
        if (_isFrozen)
        {
            throw new InvalidOperationException("Person is already frozen.");
        }

        _isFrozen = true;
    }

    public bool TryFreeze()
    {
        if (_isFrozen)
        {
            return false;
        }

        return _isFrozen = true;
    }

    public void Unfreeze()
    {
        if (!_isFrozen)
        {
            throw new InvalidOperationException("Person is not frozen.");
        }

        _isFrozen = false;
    }

    public bool TryUnfreeze()
    {
        if (!_isFrozen)
        {
            return false;
        }

        return !(_isFrozen = false);
    }
}
furesoft commented 1 year ago

that looks good

CollinAlpert commented 1 year ago

I'll keep this open until I have implemented it.

CollinAlpert commented 1 year ago

This is available in v2.2.0.

furesoft commented 1 year ago

Maybe add an option to not generate unfreeze functions?

CollinAlpert commented 1 year ago

Available in v2.2.1.