0

What is the best practice to limit a functions inputs to specific integers in java?

lets say

public Car(CarColor carcolor, (Range limited integer value) carnum) {
    // Rest of the code
}

For strings the best way is to use enumeration like

enum CarColor{
    Blue, Black, Red, Green
}

But it wont work for integers

enum CarNumber{
    1,2,3,4,5
}

What i came up with is this:

enum CarNumber{
    c1, c2, c3, c4, c5;

    @Override
    public String toString() {
            return this.name().substring(1);
    }
}

But I'm pretty sure this is not a good practice. I also don't want to let the function be called by any integer and check with a if inside the function like below. The function should not be able to be called and limited with a enum like style.

public Car(CarColor carcolor, int carnum) {
    if (carnum < 0 || carnum > 5)
        return ;
    // Rest of the code
}
KaO
  • 313
  • 1
  • 3
  • 13
  • Why do you think using `enum` isn't a good practice? – Chris Martin Feb 17 '18 at 20:14
  • @ChrisMartin using enum is what I want, just enum does not enumerate integers. like i cannot have a enum of values "1,2,3,4,5". – KaO Feb 17 '18 at 20:38
  • Right, you'd can an enum of the values "c1, c2, c3, c4, c5", which is isomorphic to the set "1, 2, 3, 4, 5". What's wrong with that? – Chris Martin Feb 17 '18 at 20:39
  • @ChrisMartin "c1, c2, c3, c4, c5" was something I came up with and therefore wanted to valide if it is the best practice. If everyone uses it the same way for enumerating integers than everything is fine. – KaO Feb 17 '18 at 20:42
  • I think we need some more context regarding what these types are being used for. Are the colors and car numbers significant to the program? That is, are you going to write code that behaves specially for particular values? Or do you just have a validation requirement that says "the color/number must be one of these values?" In the former case, I would use enums for both types, and in the latter case, I wouldn't use enums for either type. You shouldn't think of an enum as a subset of the strings, think of it as a totally new type. Enums aren't strings. – Chris Martin Feb 17 '18 at 20:49

1 Answers1

1

Maybe your best bet is to make a class that only takes in a variable that is between a certain range and then only accept an instance of that class as a parameter in your function. This way, your function won't have to check anything because it already knows that it won't be outside of a range.

Jackson Tarisa
  • 298
  • 2
  • 9