return - Java : Proper way a method() should handle a bad call -


i confronted question. let's see quick example, got simple method : retrieves position of string in string[].

public int getstringposition(string s, string[] text) {     (int = 0; < text.length; i++) {         if (text[i].equals(s)) {             return i;         }     }     return text.length; } 

but if string isn't in array? here, returns size of array (an int couldn't come normal use of method). return -1. wish return null doesn't seem possible.

anyway, method used in same class other methods. question pretty general, how handle cases can't return expected?

if inability find string constitutes error, exceptional condition, should throw exception caller. e.g.,

throw new runtimeexception("string not found"); 

if inability find string normal situation caller want handle in normal flow of code, should use special return value. type of search method, no normal return value negative, , convention return -1, string.indexof , list.indexof do. if follow convention implement method body single line:

return java.util.arrays.aslist(text).indexof(s); 

note: change treats null bit differently. there 3 things null in method: search string, array, , elements of array. current code throws nullpointerexception if passed null array, or when encounters null element, silently ignores null search string. deferring list.indexof, array elements allowed null too, allowing searching null value within array. it's harmless difference here, well-designed method considers such questions. example, might prefer treat null search string invalid input , throw exception in case.

a documented public method consider case of multiple matching elements within array: should return lowest matching index, or matching index? if index acceptable, must consistently return same index repeat invocations same arguments? (a hypothetical multithreaded search implementation defeat "obvious" assumption of returning lowest index, because can't predict cpu core find match first.)

also consider method declared static.


Comments

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -