I have put validations on the Data class that prevent users from putting invalid data in the database file.
My problem is that putting validations is not a must requirement, so I want to remove them.
Is it safe to assume that people who use the Data class will always pass valid information to the methods of the Data class?
I mean is it safe to assume that users who call read(recNo) will pass a recNo >= 0 always ?
Is it safe to assume that when users call create(String record) record will not be null ?
Is it safe to assume that the elements of String record will not be null ?
Is it afe to assume that the size of String record is 7 ?
If I remove the validations, then the Data class will fall over if users pass invalid data to the methods of the Data class.
They will get NullpointerExceptions and ArrayIndexOutOfBoundException.
I think your Data class should be as robust as possible, so in my Data class every parameter is validated. When a recNo lower than 0 is passed to the read method, nothing more than a RNFE will be thrown. But if you pass a null-array to the create-method you will get an IllegalArgumentException. If the array does not match the size of the number of fields in a record also an IllegalArgumentException will be thrown. Each exception will have a meaningful message, so a developer using my code will know what he did wrong.
And from the point of view you are developing a kind of API, which could be used by other developers throwing an IllegalArgumentException is much better than a NullPointerException or ArrayIndexOutOfBoundsException. You could also improve your code to handle all these situations, but that will clutter up your code, so throwing the IllegalArgumentException is the best option in my opinion.
Applications should throw instances of this class to indicate other illegal uses of the null object.
So this is more suited to cases where a caller has passed in a null argument.
Joined: Jan 14, 2010
I threw IllegalArgumentException when users of the Data class provided invalid arguments such as null because such an argument is illegal.
If you want to throw NullPointerException when users provide a null argument to your methods, I assume that is okay since you will provide a description of what is wrong when throwing the exception.
The issue of using IllegalArgumentException or NullPointerException is a subjective one in this case of recieving a null as an argument.
As long as your Data class does not fall over, it is okay to use what you feel is better or will be understood by people who will maintain your code.