3

I want to define own data type, say a Digit, which would have definite type of values ( 0 to 9 ) and I'm struggling with defining this in a way it's practical. What's the best way (design pattern) to do this?

I'm doing this in Scala, which might provide some advantages, but I'm also interested in general approach.

If instantiating Digit via Int constructor ( var d = new Digit(1) ), how to handle "out of bounds" safety in compile type? Is creating subclasses ( var d: Digit = new Digit1() ) a way?

Additional question: How to handle large sets of values - e.g. letters come to mind first?

1
  • imo "letters" is still a small enough set (in most Western languages) that an enum is fine. Perhaps an infinite yet well-defined set of values like the natural numbers would be a better example? Or are you only concerned with finite sets?
    – Ixrec
    Mar 27, 2016 at 1:33

1 Answer 1

3

This specific case is easy. You could use sum types or enumerations, since you have such a small number of possible values.

In scala (typing this on a tablet, so it might come out a bit mangled):

sealed abstract class Digit {
  def value: Int
}

case object One extends Digit { override val value = 1 }
case object Two extends Digit { override val value = 2 }

// ...

You might want to make this more pleasant with a proper unapply method in the companion object and other goodies.

As far as construction is concerned, no need: all values are already present, you don't need to create a new one.

This is only practical because you have ten values though. A larger number would require an entirely different answer.

4
  • Thanks @nicolas-rinaudo ! I'll try this approach and see how it works in my ecosystem. Very close larger case would be letters ... :-) Mar 26, 2016 at 18:44
  • @DavidLukac standard protocol here would be: upvote my answer (acknowledging that you found it useful), update your question with the alphabet bit, notify me in comments that the scope of your question has changed (or open an entirely new question). While 'thank you' comments feel polite, they add little value to a q&a site and in extreme cases might be deleted by mods. But you're welcome, of course :) Mar 26, 2016 at 18:51
  • Unfortunately I don't have enough reputation on 'Programmers' site to up-vote yet (it was the 1st thing I tried). I have updated the question with larger scale example. Mar 26, 2016 at 18:58
  • 1
    @DavidLukac You should be able to mark the answer as "accepted" by clicking the check mark even if you can't upvote yet.
    – Ixrec
    Mar 27, 2016 at 1:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.