Effective Java check validity for parameters

Content Protection by DMCA.com

Before read the main content about Java check validity, I want to suggest a book write about this problem. It’s Effective Java 3rd Edition, you should read it if you want to become Java Senior Software Engineer.

Best book for who want become Senior Software Engineer.


1. Java check validity

Java check validity is a common problem we need to solve. If the input parameters wrong and can’t stop by validity, we will get a big problem.

Furthermore, If an invalid parameter value is passed to a method and the method checks its parameters before execution, it will fail quickly and cleanly with an appropriate exception.

Most methods and constructors have some restrictions on what values may be passed into their parameters.

There is two things we need to remember when write a Java check validity for the methods.

2. Handle Exception

We write the Java check validity methods, but what happened when we got the error?.

The method could fail with a confusing exception in the midst of processing. For public and protected methods, use the Javadoc @throws tag to document the exception that will be thrown if a restriction on parameter values is violated.

There is many Exception type we need to handle when validation. IllegalArgumentException, IndexOutOfBoundsException, NullPointerException. If we throw it in the code, we need to write a document for them.

It make another guys when read the validation code, they can easy and quick to handle.

/*** Returns a BigInteger whose value is (this mod m).  This method* differs from the remainder method in that it always returns a* non-negative BigInteger.** @param  m the modulus, which must be positive* @return this mod m* @throws ArithmeticException if m is less than or equal to 0*/
public BigInteger mod(BigInteger m) {
  if (m.signum() <= 0)throw new ArithmeticException("Modulus <= 0: " + m);
  ... // Do the computation

Note that the doc comment does not say “mod throws NullPointerException if m is null,” even though the method does exactly that, as a by product of invoking m.signum().

3. Some notes

3.1 Objects.requireNonNull

Please take note that we can also ignore the return value and use Objects.requireNonNull as a freestanding null check where that suits your needs.

// Inline use of Java's null-checking facilitythis.strategy
Objects.requireNonNull(strategy, "strategy");

With Objects.requireNonNull, now we can remove the code to check null like that

// Inline use of Java's null-checkin strategy
if (strategy != null) {

The requireNonNull is very helpful in case we want to use Java check validity. If we write the API, the input parameter with get from the user, if they input null value, we can handle it. Otherwise, if the previous method get the parameter return a wrong value -> we also can stop a process.

3.2 Function do only one thing

If the Java check validity has many field to check, like request of API. We can move it to another method.

I think it’s NOT a bad choice because the function validation can return only true or false. It’s easy to understand and maintenance later.

// Function do only one thing
// We can do all validation field in here
private boolean validationRequestParams(Request request) {
  if (request.getFieldA() == null) return false;
  if (request.getFieldB() == WRONG) return false;
  return true

Functional Programming is a nice concept we should know. If you don’t know what’s FP, please feel free to read the post about Functional Programming in Kieblog.

3.3 Java 9 check from to index

In Java 9, a range-checking facility was added to java.util.Objects. This facility consists of three methods: checkFromIndexSize, checkFromToIndex, and checkIndex. This facility is not as flexible as the null-checking method.

  • checkFromIndexSize: Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
  • checkFromToIndex: Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
  • checkIndex: Checks if the index is within the bounds of the range from 0 (inclusive) to length (exclusive).
Java Check validity

4. Reference

There’s many we can talk about Java check validity like:

  • How to handle in case many item?
  • Can we apply the Factory Pattern for this?
  • If don’t use Objects, can we use Java Optional?

You can read more with link below:

Thank for your attension. Please like the page if you think the article helpful. Happy coding!

Anh em nếu muốn tìm hiểu sâu hơn có thể vào ghé Udefree để lựa cho mình các khoa học miễn phí cũng như trả phí

Có gì thắc mắc cứ comment đây nha! - Please feel free to comment here!

Kiên Nguyễn

👋 HEY THERE! 👋. My pleasure when you're here to read the article. Please feel free to comment, send a message or just want to say HELLO. Thank you, from bottom of my heart ❤️❤️❤️. Visit my portfolio: https://kieblog.com

Mời tui ly cà phê

Like page để không bỏ lỡ bài viết mới
Facebook Pagelike Widget
Bài viết mới
Lưu trữ