-5

What is the right way in java to limit constructor values?

I want to make sure that its NOT possible to create objects using MyConstructor with the parameter int value > 5

example: (pseudo code)

public MyConstructor(value){
   if(value < 5){
       this.value = value;
   } 
}
nanobot
  • 108
  • 5
  • 18
  • 5
    1: that code won't compile 2: use an enum for compile-time safety – Hovercraft Full Of Eels Nov 11 '18 at 13:51
  • 1
    Although the code is not valid Java code, I understand your question. An enum or a specialized type may help. Also, do you want the limitation at compile time or run time? – Sid Nov 11 '18 at 13:52
  • 3
    Explain precisely what you actually want to achieve. What is the actual class, what is the actual parameter for, what does it represent, and why it must be less than 5. At the moment, your question is much too vague to provide good advice. – JB Nizet Nov 11 '18 at 13:54
  • 2
    we normally throw an `IllegalArgumentException` if `value >= 5` – Andrew Tobilko Nov 11 '18 at 14:05
  • You could [throw](https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html) [IllegalArgumentException](https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/IllegalArgumentException.html) when an invalid value is passed. – D.B. Nov 11 '18 at 14:06
  • I want to create objects using a constructor and pass a parameter BUT I want that its not possible to pass a parameter which is >5 as this would not make any sence in my program. So I'm looking for a proper way to do this. I mean I can do this in diffrent ways but I want to know the "best" one. – nanobot Nov 15 '18 at 10:04
  • duplicate of: https://stackoverflow.com/questions/13443406/how-do-i-insert-a-precondition-in-a-java-class-method-or-constructor – Guillaume Nov 15 '18 at 15:50

1 Answers1

2

You can use JSR-303 Bean Validation API:

@Max(4)
int value

JSR-303 allows you to define declarative validation constraints against such properties:

public class PersonForm {

@NotNull
@Size(max=64)
private String name;

@Min(0)
private int age;

Specifically @Max

The value of the field or property must be an integer value lower than or equal to the number in the value element.

@Max(10)
int quantity;
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
  • 1
    That does not prevent you from constructing such objects though, I don't think that's what OP means. (plus it's a bit convoluted for doing such a basic thing) – Joeri Hendrickx Nov 15 '18 at 15:27