I am reading data from a file, one line at a time. The number of elements in the line can vary. I am using Java 8.
public boolean display (Integer code, String line) {
String[] strArray = line.split(Constant.sep);
String name = strArray[0];
String address = strArray[1];
String country = strArray[2];
//Do Something Scenario (if only name is Not Null, OR if name & address are not null or ....
}
In the above case, not all the fields are necessary for the follow up execution.
However, strArray goes out of bound in the above case, say, when e.g. only field "name" is present. I understand, why this happens. Is there a solution to get around this?
I would prefer to simplify the code and not have to create separate code for each situation or build a complex If/else logic for each combination. The value "code" is a helper that tells the method that what fields are present in the "String line".
Use if statements.
This works because the code “falls through” to each if statement. If the length is 2, then the third if statement is not executed but the first two are. This allows for you to avoid repeating yourself and using a long if statement structure.