Skip to content

Commit

Permalink
Move handling of missing file to normal code path
Browse files Browse the repository at this point in the history
As stated in the comments of the original code, handling the missing
file using an exception is not appropriate, because it is a normal
situation (e.g. when starting the program for the very first time).

Therefore, handle the logic outside the exception code path to aid
readability.
  • Loading branch information
yamgent committed Feb 4, 2017
1 parent 5810f7c commit 2ef44b2
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/seedu/addressbook/storage/StorageFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Expand Down Expand Up @@ -117,6 +118,13 @@ public void save(AddressBook addressBook) throws StorageOperationException {
* @throws StorageOperationException if there were errors reading and/or converting data from file.
*/
public AddressBook load() throws StorageOperationException {
// create empty file if not found
if (!Files.exists(path) || !Files.isRegularFile(path)) {
final AddressBook empty = new AddressBook();
save(empty);
return empty;
}

try (final Reader fileReader =
new BufferedReader(new FileReader(path.toFile()))) {

Expand All @@ -128,17 +136,8 @@ public AddressBook load() throws StorageOperationException {
}
return loaded.toModelType();

/* Note: Here, we are using an exception to create the file if it is missing. However, we should minimize
* using exceptions to facilitate normal paths of execution. If we consider the missing file as a 'normal'
* situation (i.e. not truly exceptional) we should not use an exception to handle it.
*/

// create empty file if not found
} catch (FileNotFoundException fnfe) {
final AddressBook empty = new AddressBook();
save(empty);
return empty;

throw new AssertionError("A non-existent file scenario is already handled earlier.");
// other errors
} catch (IOException ioe) {
throw new StorageOperationException("Error writing to file: " + path);
Expand Down

0 comments on commit 2ef44b2

Please sign in to comment.