Skip to content

Latest commit

 

History

History
81 lines (56 loc) · 2.11 KB

File metadata and controls

81 lines (56 loc) · 2.11 KB

Patternify.NullObject

This source generator simplifies the implementation of the Null Object design pattern in C#. It automatically generates a default, "do nothing" implementation of an interface, helping you avoid null reference exceptions and redundant null checks in your code.

Features

  • Automatically generates a Null Object implementation for interfaces.
  • Reduces the need for null checks, promoting cleaner, safer code.
  • Simple and easy-to-use with a single attribute.

How to Use

Step 1: Apply the [NullObject] Attribute

To generate a Null Object for an interface, apply the [NullObject] attribute to the interface.

Example:

[NullObject]
public interface ILog
{
    public int Id { get; }
    public string Login(string username, string password);
    public void Info(string message);
    public void Warn(string message);
}

Step 2: Let the Generator Do the Work

The generator will automatically create a class that implements the ILog interface with default "do nothing" behavior.

Generated code:

// <auto-generated/>
using DesignPatternCodeGenerator.Attributes.NullObject;

namespace Samples.NullObject
{
    public class LogNullObject : ILog
    {
        public int Id { get; }

        public void Info(string message) { }

        public void Warn(string message) { }

        public string Login(string username, string password) 
        {
            return default(string);
        }
    }
}

Step 3: Use the Null Object

You can now safely use the generated LogNullObject class as a default implementation when an instance of ILog is expected, without the need for null checks.

Generated code:

ILog logger = new LogNullObject();
logger.Info("This will do nothing safely.");

Installation

To use this source generator in your project, add the NuGet package to your project:

dotnet add package Patternify.NullObject

Contributing

Contributions are welcome! If you encounter any issues or have ideas for improvements, feel free to open an issue or submit a pull request.

License

This project is licensed under the MIT License.