Use continue or Checked Exceptions when checking and processing objects

I am processing, say, a list of Document objects. Before recording the processing of a document successfully, I first want to check a couple of things. Say a file referencing a document must be present and something in the document must be present. Just two simple checks for an example, but remember 8 more checks before I successfully process my document.

What will be 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");
}

Which is more readable. What's better? Is there even a better way to do this (possibly using some kind of design pattern)?

As for readability, my preference is currently the Exception variant ...

What's yours

+3
source share
5 answers

, .

for (Document document : List<Document> documents) {
    if(checkDocument(document)) {
        doSomethingWithTheSucces();
    } else {
        doSomethingWithTheError();
    }
}

// Later:
public boolean checkDocument(Document doc) { ... }

, , checkDocument() , , . , , - :

for (Document document : List<Document> documents) {
    try {
        checkDocument(document);
        doSomethingWithTheSucces();
    } catch(CheckDocumentException ex) {
        doSomethingWithTheError(ex);
    }
}

// Later:
public void checkDocument(Document doc) throws CheckDocumentException { ... }

checkDocument() - , , .

try {} , , . , .

+4

continue, . , . fillInStackTrace, .

, , , . , , , , . , , , , .

+1

, . , , , (, ).

, "if" - .

, , .

P.S. . , . Mine , - , , . .

+1

, , .

" " , , , , - .

" " , , , - , , , continue , , , .

0

, , .

, , , , . , , , .

, - , . , , , . , .

, , . , , " , ", , .

In short, I think it depends. In the specific example that you have above, I think that in the end I will use a combination of both styles.

0
source

Source: https://habr.com/ru/post/1697418/


All Articles