I’ve recently watched an interesting video about domain modeling in F#, and I wanted to apply some of the concepts to my C++ code.
For example, I currently have a class Window
that has a member function clear(int r, int g, int b, int b)
. The function is supposed to clear the window with the provided color values. I want to give a unique type name to the parameters, such as ColorComponent
so the function would become clear(ColorComponent r, ColorComponent g, ColorComponent b, ColorComponent b)
. I also want to create a validation function so that the input to the function would always be valid and I wouldn’t need to perform checks inside every function that takes this form of input. In this case, I want the values to be in the range 0-255
.
in my current code I have this:
int validateColor(int r) {
return (r >= 0 && r <= 255) ? r : 255; // 255 is the default value
}
I’ve seen different ways of doing it online like making template classes:
template <class Tag, typename T>
class StrongTypedef
{
private:
T value;
}
struct Color : StrongTypedef<Color, int> {};
Ideally, I’d be able to create unique types and then have different validations for each one. What would be the best way of going about this? Also, is this a good way to think about this in general or am I just over complicating things?
Thanks in advance.
Adam Shkolnik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.