简体   繁体   中英

Checking for validity in Java

I have heard that it is good practice to check public method arguments for validity and throw exceptions in the case that they are not valid. I have also heard that you should check the arguments of private methods using assertions.

A couple questions I have are:

Should you ever pass objects with multiple fields into private methods?

If you do, should you check the validity of all fields in the public method before doing so or check at time of use?

Should asserts in private methods be used just to check arguments or also in the case where you have object as null and it tries to call a method as shown below?

A.doSomething()

Should you ever pass objects with multiple fields into private methods?

There's nothing inherently wrong, bad, or special in doing so. You'll find yourself very restricted if you try to avoid passing complex objects to private methods.

If you do, should you check the validity of all fields in the public method before doing so or check at time of use?

This is entirely up to you.

If checking ahead of time will avoid doing a lot of unnecessary work, then it's probably a good idea to check earlier rather than later. (No point doing a lot of CPU work or some long network calls if you know that you've been given invalid input in the first place!)

However, you don't always know that what you've been given is invalid so there are cases where it might be impossible to check right away.

Should asserts in private methods be used just to check arguments or also in the case where you have object as null and it tries to call a method as shown below?

Asserts are typically used to make sure that your logic is right, not that inputs are right. Suppose that you're certain that the logic in some method is such that it will never return a negative number, you could put in an assert that will alert you if it does which indicates either a mistake in the implementation or in your design. You should use Exceptions to catch invalid inputs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM