Reputation: 1159
I write a lot of methods looking a bit like this:
/* myVal must be between 10 and 90 */
int myVal = foo;
if(myVal < 10) { myVal = 10; }
else if (myVal > 90) { myVal = 90; }
Is there a more elegant way of doing it? Obviously you could easily write a method, but I wondered if any languages had a more natural way of setting a constraint, or whether there was something else I'm missing.
Language agnostic, because I'm interested in how different languages might deal with it.
Upvotes: 2
Views: 444
Reputation: 25042
I've made use of an interval data type from time to time. Most of the effort is in initializing the different cases, since you might want to handle either end being either open or closed. Testing for inclusion is easy for any given case.
Nothing earth-shaking here, but surprisingly convenient. Easy to do in object-oriented, functional, and procedural styles.
Upvotes: 0
Reputation: 601729
In most programming languages, you could use something like
myVal = min(max(foo, 10), 90);
or simply write a clip()
macro which does the same thing.
Upvotes: 3