2

I want to know the the best programming practice in the following use-case for a method say myMethod--

1) myMethod has some numerical purpose - say modify the contents of an array which is a private variable of the class

2) Before it does so, i need to run some critical checks on the numbers,say check1, check2, check3, any of which if fail, there is no point in going ahead. for eg. check might be to check for any negative numbers in array.

So this brings the question, what should myMethod return, how should the calling function be told that checkX has failed.

Hobby_Web_programmer
  • 775
  • 2
  • 10
  • 18
  • If these checks are critical, you can throw an exception if they are not met. – luanjot Jun 26 '14 at 15:05
  • try to segragate checker methods separate from your array modifying method. from your main method, call checker methods first and if they pass then only call for modifying method – Adi Jun 26 '14 at 15:07
  • Exception handling would work. Or return an invalid number. Say your method would always give a positive value, just return -1 and check for that in your calling method. An exception is probably your best bet though as it's safer. – Mike Boch Jun 26 '14 at 15:07
  • If you make a method that does the critical checks say, `checkArray(myArray)`, that method could return an array of integers containing the positions in `myArray` that contain bad numbers. If all numbers are good, have `checkArray` return -1, meaning the array is 'OK' and you can then proceed to call `myMethod`. – em_ Jun 26 '14 at 15:08

8 Answers8

3

You should throw Exceptions if any of these checks fail.

Now the question is what kind of Exception to throw. Checked or unchecked? Checked Exceptions must be caught by the calling code where as unchecked do not (but that means they might bubble up to the top of the call stack all the way up to your main method). There is vigorous debate which is better. Either way, make sure to document which Exceptions are thrown.

In general, you should use checked exceptions for recoverable conditions and unchecked exceptions for programming errors (Effective Java 2nd ed Item 58)

there are many built in unchecked Exceptions in Java that you should use in preference to writing your own including but not limited to.

IllegalArgumentException IllegalStateException IndexOutOfBoundsException NullPointerException

Take a look at the core Java methods to see what they throw.

Exceptions are better than return values because:

  1. You must rely on users to check the return value and do something about it.
  2. You are stuck with a method signature that returns a boolean or return code which might not be what you want.
  3. The Exception can have a very descriptive error message explaining why it was thrown.
dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • I do know the exception handling thing, but i feel it is too code cluttering to keep adding try..catch.. blocks everywhere and looking for bubbled up exceptions. – Hobby_Web_programmer Jun 27 '14 at 16:05
1

You can create a custom checked exception as follows:

   class ArrayModificationException extends Exception{

          public ArrayModificationException(String message){
                super(message);
          }
   }

now in your "myMethod" add following:

  void myMethod() throws ArrayModificationException{


             //code to check conditions before modifications
             //code to modify an array
             if(check fails){
                 throw new ArrayModificationException("cusom message");
             }   
  } 

where custom message would be specific message conveying the exact reason of failure.

Of course the called will decide if to handle it or re-throw it. If this is one of conditions where your code should not try to recover itself you can design this as run-time exception and just throw it without throws clause for your method

Shailesh Vaishampayan
  • 1,766
  • 5
  • 24
  • 52
  • I wanted something lightweight, than full try..catch blocks. What you have written works without those? – Hobby_Web_programmer Jun 27 '14 at 16:03
  • Marked as the answer as i wanted a minimal exception handling, which is shown here, assuming it is correct. – Hobby_Web_programmer Jun 27 '14 at 16:06
  • @new_web_programmer Yes it will work without try catch. but ideally if you want to take some action when exception occurs,one of the callers better handle it gracefully with try{}catch{} block. If it is not recoverable then no need at allow and you can all it to reach at top where JVM shows you the trace – Shailesh Vaishampayan Jun 28 '14 at 00:24
0

There is no "best practice" here. It depends entirely on what your code does, where it's being executed, what the caller of the method expects, what should happen in erroneous cases, etc. Context is key here.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107
0

One possibility would be to throw an exception from the failing check, which would then be caught in the calling method.

Another option would to have myMethod return a boolean of true if all of the checks pass and the modification/calculation is done, and false otherwise.

As new_web_programmer said, though, it completely depends on what you are trying to do.

Patrick
  • 31
  • 4
0

In general after a failed validation I do

throw new IllegalArgumentException("... Clue to the error and its repair...");

IllegalStateException is an alternative here.

This enables the function to continue as desired on success.

If the exception must be catched, not propagated, use your own Exception.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
0
try{
    check1
}catch(Exception e){
    throw new CustomException("failed due to check1");
}

Some thing like this may be a better practice.

Francois Bourgeois
  • 3,650
  • 5
  • 30
  • 41
ranj
  • 33
  • 5
0

If the check failure is expected to be an exceptional circumstance, then throw an exception. Good examples are if a parameter is null but null is disallowed, or if a array index is out of range.

If your functio is supposed to return a reasonable value based on the inputs, such as returning the Point clisest to 0,0 then you could return a reasonable value based upo the check failures. For example, retur null if the array of Points is empty, or if the array itself is null.

In any case, be sure to clearly document (in the method's javadoc) what inputs result in the failure and what the expected behavior is, so that your callers are not surprised.

atk
  • 9,244
  • 3
  • 32
  • 32
0

This brings up a very old debate whether to use exceptions or error codes. You can read more about it here:

Exceptions or error codes

Community
  • 1
  • 1
Urbanleg
  • 6,252
  • 16
  • 76
  • 139