Skip to main content

How to model a Struct with a limited set of values that behaves like an enum? [Resolved]

I have a general organization problem with my code. I'm modeling DNA, and I've created a Nucleobase struct to store the "letter" of the DNA. For ease of use, I would prefer the following functionality for fluent creation of objects, equality checking, and testing purposes:

Nucleobase newInstance = Nucleobase.A;

and

if (someNucleobase == Nucleobase.C) {
    //do something...
}

Basically I want them to behave like an enum, but with functionality and behavior of a struct with methods, other fields etc.

Nucleobases can only be one of 4 letters. So I've implemented the following:

public struct Nucleobase : IEquatable {

    readonly Letter letter;

    Nucleobase(Letter letter) {
        this.letter = letter;
    }

    enum Letter {
        A,
        T,
        C,
        G
    }

    public static Nucleobase A => new Nucleobase(Letter.A);
    public static Nucleobase T => new Nucleobase(Letter.T);
    public static Nucleobase C => new Nucleobase(Letter.C);
    public static Nucleobase G => new Nucleobase(Letter.G);

    //More things... e.g. converting to and from string, IEquatable implementation etc
}

This works great. But seems to have repetition, and makes it difficult to add new values since I'd have to change code in two places, the enum, and the list of static Nucleobase properties.

Now, this is fine for Nucleobases since there will only ever be 4 values. However, Now I want to model Codons in a similar fashion. Codons are a collection of 3 Nucleobases. But codons have many more possible values (e.g. AAT, ATA, TAA, GCT, GTC etc.).

Is there a way to better construct the static members so I can do something like: Codon newCodon = Codon.AAT; without having to type out all the possible values for both the enum and the static fields? I'm not married to it being a struct. If there's a better way to model this I'm open to shifting it.

Ideally it would be automatic by looking at a list or enum of all possible values of Codons, and automatically create the fields somehow. I also would like a similar model for Amino acids, etc.

I suspect that there's a more elegant way than using static properties, but I have been pondering it for quite some time with no solutions.

This seems like a pattern that is repeating a lot, when I have a struct with a limited set of valid values.

Note: My code is in C#, but the question is relatable to any OO language imo.


Question Credit: Adam B
Question Reference
Asked September 14, 2019
Posted Under: Programming
43 views
1 Answers

Your Answer