Skip to content
This repository has been archived by the owner on Mar 5, 2023. It is now read-only.

Commit

Permalink
Replace asserts with proper exceptions for parameter validation
Browse files Browse the repository at this point in the history
Parameter validation is done by using asserts, and throws AssertionError
when validation fails.

Asserts may not always be enabled. Furthermore, specific exceptions
such as NullPointerException should be thrown to make the error more
explicit.

Let's replace the asserts with checkNotNull() and checkArgument(),
which throws an appropriate exception when validation fails.
  • Loading branch information
Zhiyuan-Amos committed May 16, 2017
1 parent 0f2cb22 commit 4f67e03
Show file tree
Hide file tree
Showing 34 changed files with 168 additions and 112 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.commons.core;

import static com.google.common.base.Preconditions.checkNotNull;

import java.text.Collator;
import java.util.Collection;
import java.util.Collections;
Expand Down Expand Up @@ -28,7 +30,7 @@ public class UnmodifiableObservableList<E> implements ObservableList<E> {
private final ObservableList<? extends E> backingList;

public UnmodifiableObservableList(ObservableList<? extends E> backingList) {
assert backingList != null;
checkNotNull(backingList);
this.backingList = backingList;
}

Expand Down
4 changes: 3 additions & 1 deletion src/main/java/seedu/address/commons/util/AppUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.commons.util;

import static com.google.common.base.Preconditions.checkNotNull;

import javafx.scene.image.Image;
import seedu.address.MainApp;

Expand All @@ -9,7 +11,7 @@
public class AppUtil {

public static Image getImage(String imagePath) {
assert imagePath != null;
checkNotNull(imagePath);
return new Image(MainApp.class.getResourceAsStream(imagePath));
}

Expand Down
7 changes: 5 additions & 2 deletions src/main/java/seedu/address/commons/util/FileUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package seedu.address.commons.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
Expand Down Expand Up @@ -80,8 +83,8 @@ public static void writeToFile(File file, String content) throws IOException {
* @return {@code pathWithForwardSlash} but '/' replaced with {@code File.separator}
*/
public static String getPath(String pathWithForwardSlash) {
assert pathWithForwardSlash != null;
assert pathWithForwardSlash.contains("/");
checkNotNull(pathWithForwardSlash);
checkArgument(pathWithForwardSlash.contains("/"));
return pathWithForwardSlash.replace("/", File.separator);
}

Expand Down
8 changes: 5 additions & 3 deletions src/main/java/seedu/address/commons/util/JsonUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.commons.util;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.IOException;
import java.util.Optional;
Expand Down Expand Up @@ -55,7 +57,7 @@ static <T> T deserializeObjectFromJsonFile(File jsonFile, Class<T> classOfObject
public static <T> Optional<T> readJsonFile(
String filePath, Class<T> classOfObjectToDeserialize) throws DataConversionException {

assert filePath != null;
checkNotNull(filePath);

File file = new File(filePath);

Expand Down Expand Up @@ -84,8 +86,8 @@ public static <T> Optional<T> readJsonFile(
* @throws IOException if there was an error during writing to the file
*/
public static <T> void saveJsonFile(T jsonFile, String filePath) throws IOException {
assert jsonFile != null;
assert filePath != null;
checkNotNull(jsonFile);
checkNotNull(filePath);

serializeObjectToJsonFile(new File(filePath), jsonFile);
}
Expand Down
13 changes: 8 additions & 5 deletions src/main/java/seedu/address/commons/util/StringUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package seedu.address.commons.util;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.io.PrintWriter;
import java.io.StringWriter;

Expand All @@ -20,12 +23,12 @@ public class StringUtil {
* @param word cannot be null, cannot be empty, must be a single word
*/
public static boolean containsWordIgnoreCase(String sentence, String word) {
assert word != null : "Word parameter cannot be null";
assert sentence != null : "Sentence parameter cannot be null";
checkNotNull(sentence);
checkNotNull(word);

String preppedWord = word.trim();
assert !preppedWord.isEmpty() : "Word parameter cannot be empty";
assert preppedWord.split("\\s+").length == 1 : "Word parameter should be a single word";
checkArgument(!preppedWord.isEmpty(), "Word parameter cannot be empty");
checkArgument(preppedWord.split("\\s+").length == 1, "Word parameter should be a single word");

String preppedSentence = sentence;
String[] wordsInPreppedSentence = preppedSentence.split("\\s+");
Expand All @@ -42,7 +45,7 @@ public static boolean containsWordIgnoreCase(String sentence, String word) {
* Returns a detailed message of the t, including the stack trace.
*/
public static String getDetails(Throwable t) {
assert t != null;
checkNotNull(t);
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
return t.getMessage() + "\n" + sw.toString();
Expand Down
10 changes: 6 additions & 4 deletions src/main/java/seedu/address/commons/util/XmlUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.commons.util;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.File;
import java.io.FileNotFoundException;

Expand Down Expand Up @@ -27,8 +29,8 @@ public class XmlUtil {
public static <T> T getDataFromFile(File file, Class<T> classToConvert)
throws FileNotFoundException, JAXBException {

assert file != null;
assert classToConvert != null;
checkNotNull(file);
checkNotNull(classToConvert);

if (!FileUtil.isFileExists(file)) {
throw new FileNotFoundException("File not found : " + file.getAbsolutePath());
Expand All @@ -51,8 +53,8 @@ public static <T> T getDataFromFile(File file, Class<T> classToConvert)
*/
public static <T> void saveDataToFile(File file, T data) throws FileNotFoundException, JAXBException {

assert file != null;
assert data != null;
checkNotNull(file);
checkNotNull(data);

if (!file.exists()) {
throw new FileNotFoundException("File not found : " + file.getAbsolutePath());
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/seedu/address/logic/commands/AddCommand.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package seedu.address.logic.commands;

import static com.google.common.base.Preconditions.checkNotNull;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE;
Expand Down Expand Up @@ -44,7 +45,7 @@ public AddCommand(ReadOnlyPerson person) {

@Override
public CommandResult execute() throws CommandException {
assert model != null;
checkNotNull(model);
try {
model.addPerson(toAdd);
return new CommandResult(String.format(MESSAGE_SUCCESS, toAdd));
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/seedu/address/logic/commands/ClearCommand.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.logic.commands;

import static com.google.common.base.Preconditions.checkNotNull;

import seedu.address.model.AddressBook;

/**
Expand All @@ -13,7 +15,7 @@ public class ClearCommand extends Command {

@Override
public CommandResult execute() {
assert model != null;
checkNotNull(model);
model.resetData(new AddressBook());
return new CommandResult(MESSAGE_SUCCESS);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.logic.commands;

import static com.google.common.base.Preconditions.checkNotNull;

/**
* Represents the result of a command execution.
*/
Expand All @@ -8,7 +10,7 @@ public class CommandResult {
public final String feedbackToUser;

public CommandResult(String feedbackToUser) {
assert feedbackToUser != null;
checkNotNull(feedbackToUser);
this.feedbackToUser = feedbackToUser;
}

Expand Down
16 changes: 9 additions & 7 deletions src/main/java/seedu/address/logic/commands/EditCommand.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.logic.commands;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL;
import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE;
Expand Down Expand Up @@ -53,8 +55,8 @@ public class EditCommand extends Command {
* @param editPersonDescriptor details to edit the person with
*/
public EditCommand(int filteredPersonListIndex, EditPersonDescriptor editPersonDescriptor) {
assert filteredPersonListIndex > 0;
assert editPersonDescriptor != null;
checkArgument(filteredPersonListIndex > 0);
checkNotNull(editPersonDescriptor);

this.filteredPersonListIndex = IndexUtil.oneToZeroIndex(filteredPersonListIndex);
this.editPersonDescriptor = new EditPersonDescriptor(editPersonDescriptor);
Expand Down Expand Up @@ -126,7 +128,7 @@ public boolean isAnyFieldEdited() {
}

public void setName(Optional<Name> name) {
assert name != null;
checkNotNull(name);
this.name = name;
}

Expand All @@ -135,7 +137,7 @@ public Optional<Name> getName() {
}

public void setPhone(Optional<Phone> phone) {
assert phone != null;
checkNotNull(phone);
this.phone = phone;
}

Expand All @@ -144,7 +146,7 @@ public Optional<Phone> getPhone() {
}

public void setEmail(Optional<Email> email) {
assert email != null;
checkNotNull(email);
this.email = email;
}

Expand All @@ -153,7 +155,7 @@ public Optional<Email> getEmail() {
}

public void setAddress(Optional<Address> address) {
assert address != null;
checkNotNull(address);
this.address = address;
}

Expand All @@ -162,7 +164,7 @@ public Optional<Address> getAddress() {
}

public void setTags(Optional<Set<Tag>> tags) {
assert tags != null;
checkNotNull(tags);
this.tags = tags;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package seedu.address.logic.parser;

import static com.google.common.base.Preconditions.checkNotNull;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_ADDRESS;
import static seedu.address.logic.parser.CliSyntax.PREFIX_EMAIL;
Expand Down Expand Up @@ -29,7 +30,7 @@ public class EditCommandParser {
* and returns an EditCommand object for execution.
*/
public Command parse(String args) {
assert args != null;
checkNotNull(args);
ArgumentMultimap argMultimap =
ArgumentTokenizer.tokenize(args, PREFIX_PHONE, PREFIX_EMAIL, PREFIX_ADDRESS, PREFIX_TAG);
List<Optional<String>> preambleFields = ParserUtil.splitPreamble(argMultimap.getPreamble(), 2);
Expand Down
12 changes: 7 additions & 5 deletions src/main/java/seedu/address/logic/parser/ParserUtil.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.logic.parser;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
Expand Down Expand Up @@ -49,39 +51,39 @@ public static List<Optional<String>> splitPreamble(String preamble, int numField
* Parses a {@code Optional<String> name} into an {@code Optional<Name>} if {@code name} is present.
*/
public static Optional<Name> parseName(Optional<String> name) throws IllegalValueException {
assert name != null;
checkNotNull(name);
return name.isPresent() ? Optional.of(new Name(name.get())) : Optional.empty();
}

/**
* Parses a {@code Optional<String> phone} into an {@code Optional<Phone>} if {@code phone} is present.
*/
public static Optional<Phone> parsePhone(Optional<String> phone) throws IllegalValueException {
assert phone != null;
checkNotNull(phone);
return phone.isPresent() ? Optional.of(new Phone(phone.get())) : Optional.empty();
}

/**
* Parses a {@code Optional<String> address} into an {@code Optional<Address>} if {@code address} is present.
*/
public static Optional<Address> parseAddress(Optional<String> address) throws IllegalValueException {
assert address != null;
checkNotNull(address);
return address.isPresent() ? Optional.of(new Address(address.get())) : Optional.empty();
}

/**
* Parses a {@code Optional<String> email} into an {@code Optional<Email>} if {@code email} is present.
*/
public static Optional<Email> parseEmail(Optional<String> email) throws IllegalValueException {
assert email != null;
checkNotNull(email);
return email.isPresent() ? Optional.of(new Email(email.get())) : Optional.empty();
}

/**
* Parses {@code Collection<String> tags} into a {@code Set<Tag>}.
*/
public static Set<Tag> parseTags(Collection<String> tags) throws IllegalValueException {
assert tags != null;
checkNotNull(tags);
final Set<Tag> tagSet = new HashSet<>();
for (String tagName : tags) {
tagSet.add(new Tag(tagName));
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/seedu/address/model/AddressBook.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package seedu.address.model;

import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
Expand Down Expand Up @@ -60,7 +62,7 @@ public void setTags(Collection<Tag> tags) throws UniqueTagList.DuplicateTagExcep
}

public void resetData(ReadOnlyAddressBook newData) {
assert newData != null;
checkNotNull(newData);
try {
setPersons(newData.getPersonList());
} catch (UniquePersonList.DuplicatePersonException e) {
Expand Down Expand Up @@ -100,7 +102,7 @@ public void addPerson(Person p) throws UniquePersonList.DuplicatePersonException
*/
public void updatePerson(int index, ReadOnlyPerson editedReadOnlyPerson)
throws UniquePersonList.DuplicatePersonException {
assert editedReadOnlyPerson != null;
checkNotNull(editedReadOnlyPerson);

Person editedPerson = new Person(editedReadOnlyPerson);
syncMasterTagListWith(editedPerson);
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/seedu/address/model/ModelManager.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package seedu.address.model;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

import java.util.Set;
import java.util.logging.Logger;

Expand Down Expand Up @@ -30,7 +33,7 @@ public class ModelManager extends ComponentManager implements Model {
*/
public ModelManager(ReadOnlyAddressBook addressBook, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(addressBook, userPrefs);
checkArgument(!CollectionUtil.isAnyNull(addressBook, userPrefs));

logger.fine("Initializing with address book: " + addressBook + " and user prefs " + userPrefs);

Expand Down Expand Up @@ -74,7 +77,7 @@ public synchronized void addPerson(Person person) throws UniquePersonList.Duplic
@Override
public void updatePerson(int filteredPersonListIndex, ReadOnlyPerson editedPerson)
throws UniquePersonList.DuplicatePersonException {
assert editedPerson != null;
checkNotNull(editedPerson);

int addressBookIndex = filteredPersons.getSourceIndex(filteredPersonListIndex);
addressBook.updatePerson(addressBookIndex, editedPerson);
Expand Down
Loading

0 comments on commit 4f67e03

Please sign in to comment.