Asserting your method get valid arguments can’t be easier than using …

Just wanted to help myself and anyone interested in topic simplify asserting my methods receive valid arguments before ever executing main logic.
One easy way to do so is using Java’s assert keyword.

So, say you have method:

     private static int populateMatrixSortedAscending() {
        int counter = 0;
        final int totalRows = matrix.length;
        for (int i = 0; i < totalRows; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                int newEntry = newEntry();
                while (!isValidNewEntry(newEntry, i, j)) {
                    newEntry = newEntry();
                }
                matrix[i][j] = newEntry;
            }
        }
        return counter;
    }

We want very easy way to assert matrix our code runs agains has at least one row and one column. In order to skip if … throw construct we can just use assert, like this:

     private static int populateMatrixSortedAscending() {
        int counter = 0;
        final int totalRows = matrix.length;
        assert (totalRows > 0) : "Matrix must have at least one row";
        assert (matrix[0].length > 0) : "Matrix must have at least one column";
        for (int i = 0; i < totalRows; i++) {
        ...

If condition given to assert keyword, (totalRows > 0) evaluates to false message given after semicolon will be used to construct instance of AssertionError which will be thrown eventually.

One additional thing to be done is that, in order for JVM to even execute assertions – you need to pass -ea argument when running our application. After running your application – you might get this message printed in console output once your method receives bad input:

Exception in thread "main" java.lang.AssertionError: Matrix must have at least one row
	at com.example.coding_exercises.SortedMatrixNumberCounter.populateMatrixSortedAscending(SortedMatrixNumberCounter.java:28)
	at com.example.coding_exercises.SortedMatrixNumberCounter.main(SortedMatrixNumberCounter.java:14)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...

It’s very easy to troubleshoot any issue and on the other hand – it’s very compact language construct to achieve it.
Stay tuned and – don’t forget to subscribe!

Advertisements

One thought on “Asserting your method get valid arguments can’t be easier than using …

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s