1

Lets say I've this code:

public class MyClass { public final static int valueA = 0; public final static int valueB = 1; private int parameter = -1; public MyClass(int parameter) { if(parameter != valueA && parameter != valueB) { throw new IllegalArgumentException("Exception description here"); } this.parameter = parameter; } } 

Is this a best practice? Or is there a better way to grantee that whatever the value passed on the constructor it has the same value as one of those variables?

2
  • There's nothing wrong with checking parameters and throwing an IAE in the constructor. If we're talking about best practices, there is something that should be noted here: when the parameter to the constructor is mutable, always make a defensive copy first and check the constraints on the copy. (And then of course use the copy.) Commented Aug 15, 2014 at 19:13
  • fail early, they say Commented Aug 15, 2014 at 19:26

2 Answers 2

6

The Java API contains many classes that throw exceptions in their constructors, so there's nothing wrong with that.

Example :

In java.net.URI class :

public URI(String str) throws URISyntaxException { new Parser(str).parse(false); } 

In java.util.ArrayList class :

public ArrayList(int initialCapacity) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Accepted your answer because it answers my main question and straight to the point. Thanks.
6

Maybe you should look into Enums.

public enum MyEnum { A(0), B(1); private int parameter; public MyEnum(int parameter) { this.parameter = parameter; } } 

Basically, this forces that you can only have the object with the parameter = 0,or parameter = 1. However, this also only allows ONE instance of each type (0, 1, etc...), so this may not work depending on your use case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.