Union of Modddels Overview

You know by now how to create a modddel. But what if you want to make a union of modddels ?

In freezed, you would do something like this :

@freezed
class Weather with _$Weather {
  const factory Weather.sunny({
    required int temperature,
  }) = _Sunny;

  const factory Weather.rainy({
    required int temperature,
    required double rainIntensity,
  }) = _Rainy;
}

Basically, you create one factory constructor per union-case. The same principle applies for making a union of modddels. In our example, we will consider Weather as a union of two MultiValueObjects : Sunny and Rainy.

@Modddel(
  validationSteps: [
    ValidationStep([
      Validation('habitable', FailureType<WeatherHabitableFailure>()),
    ]),
  ],
)
class Weather extends MultiValueObject<InvalidWeather, ValidWeather>
    with _$Weather {
  Weather._();

  factory Weather.sunny({
    required int temperature,
  }) {
    return _$Weather._createSunny(
      temperature: temperature,
    );
  }

  factory Weather.rainy({
    required int temperature,
    required double rainIntensity,
  }) {
    return _$Weather._createRainy(
      temperature: temperature,
      rainIntensity: rainIntensity,
    );
  }

  @override
  Option<WeatherHabitableFailure> validateHabitable(weather) {
    // TODO: implement validateHabitable
    return none();
  }
}

@freezed
class WeatherHabitableFailure extends ValueFailure with _$WeatherHabitableFailure {
  const factory WeatherHabitableFailure.tooHot() = _TooHot;
  const factory WeatherHabitableFailure.tooCold() = _TooCold;
  const factory WeatherHabitableFailure.flooding() = _Flooding;
}

As you can see, we have two factory constructors : Weather.sunny and Weather.rainy . This creates two MultiValueObjects Sunny and Rainy. Each one of these is a modddel with all of the functionality we've seen before :

On top of that, these classes are generated :

These classes are what we call "super-sealed classes". They are classes that have multiple modddels as union-cases (called "case-modddels"). This table shows the relationship between the super-sealed classes and the two modddels.

Super-sealed classCase-modddels

Weather

Sunny - Rainy

ValidWeather

ValidSunny - ValidRainy

InvalidWeather

InvalidSunny - InvalidRainy

InvalidWeatherValue

InvalidSunnyValue - InvalidRainyValue

In the example above, we've showcased how you can create a union of MultiValueObjects. However, the same approach applies to any modddel kind : SingleValueObject, SimpleEntity, etc. All you need to do is add multiple factory constructors to your class, each representing a different case-modddel.

It is enough to have a single named factory constructor to make a union of modddels. In that case, there would be one case-modddel only.