开发者

Java Cascading Enums?

开发者 https://www.devze.com 2022-12-27 15:16 出处:网络
In my project, I have such class : class Statut开发者_如何学编程 { String satDomain; String staCode;

In my project, I have such class :

class Statut开发者_如何学编程 {
    String satDomain;
    String staCode;
}

But working with Strings is not what I want. It is too permisive and using constants is not enough.

I wanted to use enums but find a problem :

class Statut {
    Domain satDomain;
    StatutCode staCode;
}
enum Domain { }
enum StatutCode { }

This solution is far better, but you can set a StatutCode that is not in the selected Domain.

Did you find a solution in your project to such problem ?

Thank for your help

Fluminis


Actually slight improvement on extraneon's answer.

Define StatutCode enum first, and then assign EnumSet< StatutCode > to each Domain enum value. Then the validation is pretty simple in Statut constructor

enum StatutCode
{
  ONE,
  TWO,
  THREE,
  FOUR
};

enum Domain
{
  DOMAIN_1( EnumSet.of( StatutCode.ONE, StatutCode.TWO ) ),
  ...
  DOMAIN_N( EnumSet.of( StatutCode.TWO, StatutCode.THREE ) );

  private final EnumSet< StatutCode> validStatCodes;

  Domain( EnumSet< StatutCode > validStatCodes )
  {
    this.validStatCodes = validStatCodes;
  }

  public boolean isValidCode ( final StatutCode code )
  {
    return validStatCodes.contains( code );
  }
}

class Statut {
    final Domain staDomain;
    final StatutCode staCode;

    Statut(
      final Domain staDomain,
      final StatutCode staCode
    )
    {
      if ( ! staDomain.isValidCode( staCode ) )
      {
        throw new IllegalArgumentException(
            "Invalid code " + staCode + " for domain " + staDomain
          );
      }

      this.staDomain = staDomain;
      this.staCode = staCode;
    }

}


I suggest making your fields private and final and adding a constructor the verifies that the constructed object is well-formed.


I don't usually find that a problem. I tend to use a unmodifiable validation Map<Domain,StatutCode>()` if run-time validation is sufficient, or the contents is pulled from a database.

You could add such a validator on Statut. Make the only setter like setDomainAndStatutCode(Domain domain, StatutCode statutCode) and check whether the input is valid.

Otherwise I'd use an enum DomainAndStatutCode. Lot's of work and maintenance of course, so really not a nice solution. Might be good if the dataset is limited and correctness is a must.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号