Use continue or Checked Exceptions when checking and processing objects
Posted
by Johan Pelgrim
on Stack Overflow
See other posts from Stack Overflow
or by Johan Pelgrim
Published on 2008-09-23T20:37:37Z
Indexed on
2010/04/04
5:03 UTC
Read the original article
Hit count: 360
I'm processing, let's say a list of "Document" objects. Before I record the processing of the document successful I first want to check a couple of things. Let's say, the file referring to the document should be present and something in the document should be present. Just two simple checks for the example but think about 8 more checks before I have successfully processed my document.
What would have your preference?
for (Document document : List<Document> documents) {
if (!fileIsPresent(document)) {
doSomethingWithThisResult("File is not present");
continue;
}
if (!isSomethingInTheDocumentPresent(document)) {
doSomethingWithThisResult("Something is not in the document");
continue;
}
doSomethingWithTheSucces();
}
Or
for (Document document : List<Document> documents) {
try {
fileIsPresent(document);
isSomethingInTheDocumentPresent(document);
doSomethingWithTheSucces();
} catch (ProcessingException e) {
doSomethingWithTheExceptionalCase(e.getMessage());
}
}
public boolean fileIsPresent(Document document) throws ProcessingException {
... throw new ProcessingException("File is not present");
}
public boolean isSomethingInTheDocumentPresent(Document document) throws ProcessingException {
... throw new ProcessingException("Something is not in the document");
}
What is more readable. What is best? Is there even a better approach of doing this (maybe using a design pattern of some sort)?
As far as readability goes my preference currently is the Exception variant...
What is yours?
© Stack Overflow or respective owner