Skip to content

Latest commit

 

History

History
1642 lines (1176 loc) · 69.3 KB

DeveloperGuide.adoc

File metadata and controls

1642 lines (1176 loc) · 69.3 KB

UniFy - Developer Guide

1. Introduction

Welcome to UniFy !

UniFy is a command-line application which provides a convenient way to store students' contact information. It is customised for NUS students, allowing them to efficiently manage their contact lists. This developer guide provides information that helps you to get started as a UniFy contributor, and aids you even if you are an experienced contributor. The developer guide consists of the following sections.

2. Setting up

2.1. Prerequisites

  1. JDK 1.8.0_60 or later

    ℹ️
    This app will only work with later versions of Java 8.
  2. IntelliJ IDE

    ℹ️
    IntelliJ has Gradle and JavaFx plugins installed by default.
    Please do not disable them. If you have disabled them, go to File > Settings > Plugins to re-enable them.

2.2. Setting up UniFy in your computer

  1. Fork this repo, and clone the fork to your computer

  2. Open IntelliJ (if you are not in the welcome screen, click File > Close Project to close the existing project dialog first)

  3. Set up the correct JDK version for Gradle

    1. Click Configure > Project Defaults > Project Structure

    2. Click New…​ and find the directory of the JDK

  4. Click Import Project

  5. Locate the build.gradle file and select it. Click OK

  6. Click Open as Project

  7. Click OK to accept the default settings

  8. Open your console and run the command gradlew processResources (Mac/Linux: ./gradlew processResources). It should finish with the BUILD SUCCESSFUL message.
    This will generate all resources required by the application and tests.

2.3. Verifying the setup

  1. Run the seedu.address.MainApp

  2. Try out a few commands

  3. Run the tests to ensure they all pass.

2.4. Doing configurations before writing code

2.4.1. Configuring the coding style

Our UniFy project follows oss-generic coding standards. IntelliJ’s default style is mostly compliant with ours but it uses a different import order from ours. To rectify,

  1. Go to File > Settings…​ (Windows/Linux), or IntelliJ IDEA > Preferences…​ (macOS)

  2. Select Editor > Code Style > Java

  3. Click on the Imports tab to set the order

    • For Class count to use import with '*' and Names count to use static import with '*': Set to 999 to prevent IntelliJ from contracting the import statements

    • For Import Layout: The order is import static all other imports, import java.*, import javax.*, import org.*, import com.*, then import all other imports. Add a <blank line> between each import

Optionally, you can follow the UsingCheckstyle.adoc document to configure Intellij to check style-compliance automatically as you write code.

2.4.2. Setting up Continuous Integration (CI)

You would have to set up Travis to perform CI for your fork. You can check UsingTravis.adoc to learn how to set it up.

Optionally, you can set up AppVeyor as a second CI (check UsingAppVeyor.adoc).

ℹ️
Having both Travis and AppVeyor ensures your App works on both Unix-based platforms and Windows-based platforms (Travis is Unix-based and AppVeyor is Windows-based)

2.4.3. Getting started with coding

When you are ready to start coding, you can get some sense of the overall design by reading the Architecture section.

3. Design

3.1. Architecture

Architecture

Figure 3.1.1 : Architecture Diagram

The Architecture Diagram given above explains the high-level design of the App. A quick overview of each component is given below.

💡
You can find the .pptx files used to create diagrams in this developer guide in the diagrams folder. To update a diagram, modify the diagram in the pptx file, select the objects of the diagram, and choose Save as picture.

3.1.1. Main

Main has only one class called MainApp. It is responsible for,

  • Launching app: Initializes the components in the correct sequence, and connects them up with each other.

  • Shutting down: Shuts down the components and invokes cleanup method where necessary.

3.1.2. Commons

Commons represents a collection of classes used by multiple other components. These classes can be found in the seedu.addressbook.commons package. The following two classes play important roles at the architecture level.

  • EventsCenter : This class (written using Google’s Event Bus library) is used by components to communicate with other components using events.

  • LogsCenter : This class is used by many classes to write log messages to the App’s log file.

3.1.3. Four main components

The rest of the App consists of four components.

  • UI : The User Interface (UI) of the App.

  • Logic : The execution of command.

  • Model : The storage of the data of the App in-memory.

  • Storage : The saving and retrieving of data from the hard disk.

Each of the four components

  • Defines its API in an interface with the same name as the Component.

  • Exposes its functionality using a {Component Name}Manager class.

For example, the Logic component (Fig 3.1.2) defines it’s API in the Logic.java interface and exposes its functionality using the LogicManager.java class.

LogicClassDiagram

Figure 3.1.2 : Class Diagram of the Logic Component

Events-Driven nature of the design

The Sequence Diagram below shows how the components interact for the scenario where the user issues the command delete 1.

SDforDeletePerson

Figure 3.1.3a : Component interactions for delete 1 command (part 1)

ℹ️
Note how the Model simply raises a AddressBookChangedEvent when the Address Book data are changed, instead of asking the Storage to save the updates to the hard disk.

The diagram below shows how the EventsCenter reacts to that event, which eventually results in the updates being saved to the hard disk and the status bar of the UI being updated to reflect the 'Last Updated' time.

SDforDeletePersonEventHandling

Figure 3.1.3b : Component interactions for delete 1 command (part 2)

ℹ️
Note how the event is propagated through the EventsCenter to the Storage and UI without Model having to be coupled to either of them. This shows you how this Event Driven approach helps us reduce direct coupling between components.

The sections below give more details of each component.

3.2. UI component

UiClassDiagram

Figure 3.2.1 : Structure of the UI Component

API : Ui.java

The UI consists of a MainWindow that is made up of several parts such as CommandBox, ResultDisplay, PersonListPanel, StatusBarFooter, and BrowserPanel. All these, including the MainWindow, inherit from the abstract UiPart class.

The UI component uses JavaFx UI framework. The layout of these UI parts are defined in matching .fxml files that are in the src/main/resources/view folder. For example, the layout of the MainWindow is specified in MainWindow.fxml.

The UI component,

  • Executes user commands using the Logic component.

  • Binds itself to some data in the Model so that the UI can auto-update when data in the Model change.

  • Responds to events raised from various parts of the App and updates the UI accordingly.

3.3. Logic component

LogicClassDiagram

Figure 3.3.1 : Structure of the Logic Component

LogicCommandClassDiagram

Figure 3.3.2 : Structure of Commands in the Logic Component. This diagram shows finer details concerning XYZCommand and Command in Figure 3.3.1

API : Logic.java

  1. Logic uses the AddressBookParser class to parse the user command.

  2. This results in a Command object which is executed by the LogicManager.

  3. The command execution can affect the Model (e.g. adding a person) and/or raise events.

  4. The result of the command execution is encapsulated as a CommandResult object which is passed back to the UI.

Given below is the Sequence Diagram for interactions within the Logic component for the execute("delete 1") API call.

DeletePersonSdForLogic

Figure 3.3.3 : Interactions Inside the Logic Component for the delete 1 Command

3.4. Model component

ModelClassDiagram

Figure 3.4.1 : Structure of the Model Component

API : Model.java

The Model,

  • stores a UserPref object that represents the user’s preferences.

  • stores the Address Book data.

  • exposes an unmodifiable ObservableList<ReadOnlyPerson> that can be 'observed' e.g. the UI can be bound to this list so that the UI automatically updates when the data in the list change.

  • does not depend on any of the other three components.

3.5. Storage component

StorageClassDiagram

Figure 3.5.1 : Structure of the Storage Component

API : Storage.java

The Storage component,

  • can save UserPref objects in json format and read it back.

  • can save the Address Book data in xml format and read it back.

4. Implementation

This section describes some noteworthy details on how certain features are implemented.

4.1. Undo/Redo Command mechanism

The undo/redo mechanism is designed to suit the needs of students who might accidentally execute a undesired command. It is facilitated by an UndoRedoStack, which resides inside LogicManager. It supports undoing and redoing of commands that modifies the state of the address book (e.g. add, edit). Such commands will inherit from UndoableCommand.

UndoRedoStack only deals with UndoableCommands. Commands that cannot be undone will inherit from Command instead. You will be able to see the inheritance diagram for commands below (Fig 4.1.1).

LogicCommandClassDiagram

Figure 4.1.1 : Structure of Commands in the Logic Component. This diagram shows finer details concerning XYZCommand and Command in Figure 3.3.1

As you can see from the diagram, UndoableCommand adds an extra layer between the abstract Command class and concrete commands that can be undone, such as the DeleteCommand. Note that extra tasks need to be done when executing a command in an undoable way, such as saving the state of the address book before execution. UndoableCommand contains the high-level algorithm for those extra tasks while the child classes implements the details of how to execute the specific command. The technique of putting the high-level algorithm in the parent class and lower-level steps of the algorithm in child classes is also known as the template pattern.

Commands that are not undoable are implemented this way:

public class ListCommand extends Command {
    @Override
    public CommandResult execute() {
        // ... list logic ...
    }
}

With the extra layer, the commands that are undoable are implemented this way:

public abstract class UndoableCommand extends Command {
    @Override
    public CommandResult execute() {
        // ... undo logic ...

        executeUndoableCommand();
    }
}

public class DeleteCommand extends UndoableCommand {
    @Override
    public CommandResult executeUndoableCommand() {
        // ... delete logic ...
    }
}

When the user has just launched the application. The UndoRedoStack will be empty at the beginning.

The user executes a new UndoableCommand, delete 5, to delete the 5th person in the address book. You can find that he current state of the address book is saved before the delete 5 command executes. The delete 5 command will then be pushed onto the undoStack (the current state is saved together with the command).

UndoRedoStartingStackDiagram

Figure 4.1.2a : The most recent undoable command is pushed into the undoStack

As the user continues to use the program, more commands are added into the undoStack. For example, the user may execute add n/David …​ to add a new person.

UndoRedoNewCommand1StackDiagram

Figure 4.1.2b : More commands are added into the undoStack

ℹ️
If a command fails its execution, it will not be pushed to the UndoRedoStack at all.

The user now decides that adding the person was a mistake, and decides to undo that action using undo.

We will pop the most recent command out of the undoStack and push it back to the redoStack. We will restore the address book to the state before the add command executed.

UndoRedoExecuteUndoStackDiagram

Figure 4.1.2c : The command on the top will be popped and pushed into the redoStack

ℹ️
If the undoStack is empty, then there are no other commands left to be undone, and an Exception will be thrown when popping the undoStack.

The following sequence diagram shows how the undo operation works:

UndoRedoSequenceDiagram

Figure 4.1.3 : The sequence diagram for the undo function

The redo does the exact opposite (pops from redoStack, push to undoStack, and restores the address book to the state after the command is executed).

ℹ️
If the redoStack is empty, then there are no other commands left to be redone, and an Exception will be thrown when popping the redoStack.

The user now decides to execute a new command, clear. As before, clear will be pushed into the undoStack. This time the redoStack is no longer empty. It will be purged as it no longer make sense to redo the add n/David command (this is the behavior that most modern desktop applications follow).

UndoRedoNewCommand2StackDiagram

Figure 4.1.2d : When a new command is pushed into undoStack, the redoStack is purged

Commands that are not undoable are not added into the undoStack. For example, list, which inherits from Command rather than UndoableCommand, will not be added after execution:

UndoRedoNewCommand3StackDiagram

Figure 4.1.2e : The list command is not added to the undoStack

The following activity diagram summarize what happens inside the UndoRedoStack when a user executes a new command:

UndoRedoActivityDiagram

Figure 4.1.4 : Activity diagram when a new command is executed

4.1.1. Design Considerations

Aspect: Implementation of UndoableCommand
Alternative 1 (current choice): A new abstract method executeUndoableCommand() is added.
Pros: This does not lose any undone/redone functionality as it is now part of the default behaviour. Classes that deal with Command will not know that executeUndoableCommand() exist.
Cons: It would be hard for new developers to understand the template pattern.
Alternative 2: An override execute() method is added.
Pros: This does not involve the template pattern, so it is easier for new developers to understand.
Cons: Classes that inherit from UndoableCommand must remember to call super.execute() to gain the ability to undo/redo.


Aspect: Execution of undo & redo commands
Alternative 1 (current choice): The entire address book is saved.
Pros: It is easy to implement.
Cons: This may have performance issues in terms of memory usage.
Alternative 2: Individual command knows how to undo/redo by itself.
Pros: This uses less memory (e.g. for delete, just save the person being deleted).
Cons: Each individual command might be hard to implemented correctly.


Aspect: Type of commands that can be undone/redone
Alternative 1 (current choice): Only commands that modifies the address book (add, clear, edit) is included.
Pros: The view can easily be re-modified as no data are lost (We only revert changes that are hard to change back).
Cons: User might think that undo also applies when the list is modified (undoing filtering for example), only to realize that it does not do that, after executing undo.
Alternative 2: All the commands are included.
Pros: The view might be more intuitive for the user.
Cons: User has no way of skipping such commands if he or she just wants to reset the state of the address book and not the view.


Aspect: Data structure to support the undo/redo commands
Alternative 1 (current choice): Separate stack for undo and redo are used.
Pros: This is easy to understand for new Computer Science undergraduates, who are likely to be the new incoming developers of our project.
Cons: Logic is duplicated twice. For example, when a new command is executed, we must remember to update both HistoryManager and UndoRedoStack.
Alternative 2: HistoryManager is used for undo/redo.
Pros: We do not need to maintain a separate stack, and just reuse what is already in the codebase.
Cons: This would require dealing with commands that have already been undone: We must remember to skip these commands. Violates Single Responsibility Principle and Separation of Concerns as HistoryManager now needs to do two different things.

4.2. Timetables Attribute

Users are able to store timetables by supplying a shortened NUSMods URL when adding a person. You will be able to understand how NUSMods URLs are being parsed and how the timetable information is being extracted. This need is especially crucial for NUS students who require friends' timetables in order to find out a time to meet up. ==== Retrieval of Lesson Information

NUSMods URLs are in the format of …​/timetable/ACAD_YEAR/SEM?MODULE_CODE[LESSON_TYPE]=LESSON_NO&…​ We use TimetableParserUtil:expandUrl() to get an expanded URL from shortened URL provided, then parse the expanded URL accordingly to obtain lesson data. Lessons for each module are stored in ModuleInfoFromUrl, which is then represented in TimetableInfoFromUrl.

NUSMods API is used to retrieve data related to lessons parsed from URLs. JSON objects representing each module is retrieved and cast to a Map using Jackson library. Lesson data is then retrieved as a list of Lesson objects.

// read JSON as map
Map<String, Object> mappedJson = mapper.readValue(url, HashMap.class);
// retrieve lesson data
ArrayList<HashMap<String, String>> lessonInfo = mappedJson.get("Timetable");

ArrayList<Lesson> lessons = new ArrayList<>();
for (HashMap<String, String> lesson : lessonInfo) {
    Lesson lessonToAdd = new Lesson(...);
    lessons.add(lessonToAdd);
}

TimetableParserUtil in commons.util.timetable contains all utility methods for parsing of NUSMods URLs and conversion between terms parsed from URLs and terms used in NUSMods API.

4.2.1. Representation of Timetables

Storing of timetables is facilitated by an immutable Timetable object, which is a component of Person. The information regarding the timings of each lesson is stored in a single TimetableInfo object within Timetable. More specific information for a person’s lessons is abstracted further as follows:

  • Information for odd/even weeks are stored by two TimetableWeek objects within TimetableInfo

  • Each day of the timetable (Monday to Friday) is represented by five TimetableDay objects in TimetableWeek

  • To represent each timeslot in TimetableDay, a TimetableSlot class is used to represent a 30 minute interval. 32 instances of TimetableSlot are used to represent a full day from 0800 to 0000

The following UML diagram represents the implementation of the classes.

TimetableClassDiagram

Figure 4.2.2.1 : Timetable class diagram (XYZComponent refers to all other components that Person is composed of, the class diagram is not complete)

4.2.2. Displaying of Timetables

Displaying of timetables is facilitated using a single TimetableDisplay component, which resides above BrowserPanel. Both these components are contained within InfoPanel, which handles specific events to bring either panel to the front.

Upon execution of a whenfree command, the following happens:

  1. TimetableCommandParser parses the input to determine which timetables to display.

    1. If no arguments are passed, empty ArrayList<Index> is used.

    2. Otherwise, arguments are parsed into their respective Index and stored in an ArrayList<Index>.

  2. A new TimetableCommand is constructed, using the list created by the parser.

  3. When TimetableCommand:execute() is called, the list of Index, is used to obtain the ReadOnlyPerson to display, and stores it in a List<ReadOnlyPerson>.

  4. A TimetableDisplayEvent is then posted with the list of people to be displayed.

  5. The event is then handled by the InfoPanel, which creates a new TimetableDisplay component and brings it to the front.

    1. Each Timetable to be displayed is obtained from the list of people from the TimetableDisplayEvent handled.

    2. When TimetableDisplay component is created, fillInitialGrid() first populates the timetable with empty slots.

    3. After which, each Timetable is added to the grid by fillSingleTimetable().

Execution of a select command is similar, except that a PersonSelectedEvent is handled instead of a TimetableDisplayEvent

4.2.3. Design Considerations

Aspect: Representation of timetables
Alternative 1 (current choice): Abstraction of timetable grid using classes for weeks/days/slots is used.
Pros: This is easily extendable to include new functionality e.g. lessons that occur in each slot.
Cons: This requires many method call chains to update and query timetable, might not be intuitive for new programmers. It is hard to iterate through entire timetable.
Alternative 2: A 3D array to represent the entire timetable is used.
Pros: It is simple and easy to understand, easy to iterate through.
Cons: This does not follow OOP concepts, and cannot be extended to implement new functionalities.
Alternative 3: Individual lesson timings and information are stored.
Pros: Building the timetable is not required.
Cons: Queries are inefficient if a timing has a lesson, needs to iterate through every lesson stored.


Aspect: The use of Shortened URLs versus full-length URLs
Alternative 1 (current choice): Only short URLs are accepted.
Pros: There is no need to deal with multiple types of URL.
Cons: This is less user friendly as users need to supply specific type of URL.
Alternative 2: Both shortened and full-length NUSMods URLs are accepted.
Pros: This is more user friendly as any type of NUSMods URL is accepted.
Cons: This is much harder to detect malformed URL as parsing data does not detect errors in lesson tokens in URL. Shortened URL gives 403 response on bad URL.


Aspect: Behaviour of app when there is no internet connection
Alternative 1(current choice): Only store timetable URLs, and query each time app is launched. If no internet, start with empty timetable.
Pros: Storage needed is minimal, as only a single string is stored for each person.
Cons: Startup of app can be slow if there is a large number of persons.
Alternative 2: Store timetable information after retrieval from NUSMods once.
Pros: We only need to retrieve lesson information once per person.
Cons: Storage of entire timetables can be very costly, and storage can be expensive with a large number of contacts.

4.3. Delete Command [Tag] Mechanism

Deleting a tag means deleting a specified tag in all persons who contain that tag, as well as deleting the tag from the master list of tags in the Address Book. This is significantly different from deleting a tag for a person via the edit command. There is a need for this because a user would like to delete a tag that is no longer relevant or is outdated. To delete a particular tag across multiple contacts, by editing each contact, would be a tedious process, hence, the addition of this feature.

In this section, you will be able to understand how tags are deleted from all persons tagged with that tag, and how we use the same command word delete to both delete one or more persons or delete one or more tags.

In general, the ability to delete a tag was implemented by modifying the existing delete command.

This modification involves:

  • Detection of the type of deletion in the DeleteCommandParser

  • Overloading the DeleteCommand constructor

  • Executing the respective logic based on which attributes in DeleteCommand are present/non-null.

As a result of this modification, delete can execute a delete on tags, or a delete on persons, depending on the parameters provided.

4.3.1. Detection of the Deletion Type

For both types of delete commands, the same delete command word is used but the parameters provided in the command line are different.

The two types of commands are distinguished by the preamble of the parameter arguments after the word delete, when tokenized against the t/ prefix for tags.

Preamble for

  • delete INDEX [MORE INDEXES]…​ (Delete Person(s)) : A digit String

  • delete t/TAG [t/TAG] (Delete Tag(s)) : A blank String

The implementation of this parse is shown below:

public DeleteCommand parse(String args) throws ParseException {
    ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args, PREFIX_TAG);
    String preamble = argMultimap.getPreamble();
    if (preamble.equals("")) {
        // there exists 't/'
        DeleteCommand deleteCommandForTag = parseForTags(argMultimap);
        if (deleteCommandForTag != null) {
            return deleteCommandForTag; (1)
        }
    } else {
        DeleteCommand deleteCommandForPerson = parseForPersonIndexes(args, preamble);
        if (deleteCommandForPerson != null) {
            return deleteCommandForPerson; (2)
        }
    }

    // ...
}

4.3.2. Overloading the DeleteCommand constructor

With reference to the previous code snippet the type of DeleteCommand returned during the parse is also different. They differ by the types of the parameters.

  1. A deleteCommandForTag which is a new DeleteCommand(Set<Tag>) is returned when deleting one or more tags.

  2. A deleteCommandForPerson which is a new DeleteCommand(Index) or a new DeleteCommand(ArrayList<Index>) is returned when deleting one or more persons.

The following code shows the respective object construction of the different types of DeleteCommand.

Depending on the constructor method called, either the targetIndexes attribute or the targetTags will be made null, which will lead on to the next section about command execution.

public class DeleteCommand extends UndoableCommand {
    // ...
    private final Index targetIndexes;

    private final Set<Tag> targetTags;

    public DeleteCommand(Set<Tag> targetTags) {
        this.targetIndexes = null;
        this.targetTags = targetTags;
    }

    public DeleteCommand(Index targetIndex) {
        this.targetIndexes = new ArrayList<>();
        targetIndexes.add(targetIndex);
        this.targetTags = null;
    }

    public DeleteCommand(ArrayList<Index> targetIndexes) {
        this.targetIndexes = targetIndexes;
        this.targetTags = null;
    }

    // ...
}

4.3.3. Logic Execution depending on which attributes are present.

If targetIndexes is present/non-null, execute the logic for deleting a person, else execute the logic for deleting a tag.

This trivial implementation is show below. The distinct command execution of the deleting of tags and the delete of person(s) have been abstracted to apply SLAP (Single Level of Abstraction Per method).

public CommandResult executeUndoableCommand() throws CommandException {
    if (targetTags == null && targetIndexes != null) {
        return executeCommandForPersons();

    } else {
        return executeCommandForTag();
    }
}

4.3.4. Command Logic

The delete command undergoes a typical command execution in the Logic Component. Refer to Figure 3.3.3.

The following sequence diagram shows the interactions with the Model Component.

Not shown in Figure 4.3.4.1, listTags are checked against listOfExistingTags, i.e. all tags to be deleted are checked whether each of them already exist in the address book. If this check fails, an exception is thrown. The sequence diagram demonstrates a successful deletion, hence this aspect of the logic is omitted for clarity.

DeleteCommandForTagSequenceDiagram1

Figure 4.3.4.1 : The tags parsed are put into an ArrayList and iterated through for deletion

DeleteCommandForTagSequenceDiagram2

Figure 4.3.4.2 : How each tag is removed from the Address Book and each Person’s list of tags

4.3.5. Design Considerations

Aspect: Implementation of Delete Tags
Alternative 1 (current choice): The existing delete command is modified.
Pros: The same command word delete is used which is an intuitive way to invoke a deletion of some object (person or tag).
Cons: The DeleteCommand class is no longer responsible for deletion of a person only but is now responsible for deleting a tag as well. Modifying the command via overriding constructors, adding new attributes and modifying the parse may seem too convoluted a solution. This Violates Single Responsibility Principle and Separation of Concerns as DeleteCommand now needs to do two different things. Also, users who are used to the previous version of the command may not appreciate the new change, especially if it causes new bugs.
Alternative 2: A new command deletetag is created.
Pros: The implementation of a new command is simple. This does not involve any major modification of the existing parse and command logic.
Cons: deletetag t/tag is not as intuitive in the command line interface especially to new or casual users. Users may try delete t/tag out of instinct and we would need to inform or prompt users of the deletetag command.


Aspect: Execution of delete command
Alternative 1 (current choice): On the Logic level, we iterate through an array of tags and invoke a Model method deleteTag(Tag tag) on each tag.
Pros: This maintains consistency with the Model API that deals with objects in singular amounts. (At the time of coding. See Note below.)
Cons: This requires a loop to delete the tags.
Alternative 2: On the Logic level, we invoke a method deleteTags(tagSet) on a Set<Tag> and implement deleteTags(Set<Tag> tagSet) in the Model component.
Pros: The code will be easier for future contributors to understand.
Cons: This does not maintain consistency of the API.

(Note: Pull Request #79 Delete multiple persons, chooses Alternative 2 as its design consideration with deletePersons(ArrayList<ReadOnlyPerson> targets) implemented in the Model Component.)

4.4. Edit Command [Tag] Mechanism

Editing a tag means editing a specified tag (the old tag) in all persons who contain that tag, as well as editing the tag from the master list of tags in the Address Book.

This is significantly different from editing a person’s tag via the edit command. There is a need for this because a user would like to edit a tag for multiple people containing that tag.

To edit a particular tag across multiple contacts, by editing each contact, would be a tedious process, hence, the addition of this feature.

In this section, you will see that the implementation of editing a tag is very similar to deleting a tag.

The existing edit command was also modified, to allow edit to execute a edit on tags, or a edit on persons, depending on the parameters provided.

It differs from delete tag in terms of executing the respective logic of person or tag. Instead of checking which attributes of EditCommand are present/non-null, a boolean variable determine which command logic to execute

4.4.1. Detection of the Edit Type

The concept of using the preamble, as seen in DeleteCommandParser, is also used in EditCommandParser.

Preamble for

  • edit INDEX …​ (Edit Person) : A digit String

  • edit old/TAG new/TAG (Edit Tag) : A blank String

The implementation of this parse is shown below. Similarly, SLAP (Single Level of Abstraction Per method) is applied by abstracting the distinct parsing between edit a person and editing a tag:

public EditCommand parse(String args) throws ParseException {
    //...

    if (preamble.matches("")) {
        return parseForTags(argsMultimap); (1)
    } else if (preamble.matches("\\d+")) {
        return parseForPersonDetails(argsMultimap); (2)
    }

    //...
}

4.4.2. Overloading the EditCommand constructor

With reference to the previous code snippet the type of EditCommand returned during the parse is also different. The parameter type of the EditCommand is different.

  1. A new EditCommand(Tag, Tag) from the method parseForTags(argsMultimap) is returned.

  2. A new EditCommand(Index, EditPersonDescriptor) from the method parseForPersonDetails(argsMultimap) is returned.

The following code shows the respective object construction of the different types of EditCommand.

Depending on the constructor method called, the irrelevant attributes will be made null. The boolean variable isEditForPerson is assigned the value true when the edit command is for editing a person, and false if it is for editing a tag.

public class EditCommand extends UndoableCommand {
    // ...
    private final boolean isEditForPerson;
    private final Index index;
    private final EditPersonDescriptor editPersonDescriptor;
    private final Tag oldTag;
    private final Tag newTag;

    public EditCommand(Index index, EditPersonDescriptor editPersonDescriptor) {
        requireNonNull(index);
        requireNonNull(editPersonDescriptor);

        this.isEditForPerson = true;
        this.index = index;
        this.editPersonDescriptor = new EditPersonDescriptor(editPersonDescriptor);
        this.oldTag = null;
        this.newTag = null;
    }

    public EditCommand(Tag oldTag, Tag newTag) {
        requireNonNull(oldTag);
        requireNonNull(newTag);

        this.isEditForPerson = false;
        this.index = null;
        this.editPersonDescriptor = null;
        this.oldTag = oldTag;
        this.newTag = newTag;
    }

    // ...
}

4.4.3. Logic Execution depending on which attributes are present.

If isEditForPerson is present, execute the logic for editing a person, else execute the logic for editing a tag.

This trivial implementation is show below. The distinct command execution of the editing of tags and the editing of person(s) have been abstracted to apply SLAP (Single Level of Abstraction Per method).

public CommandResult executeUndoableCommand() throws CommandException {
    if (isEditForPerson) {
        return executeCommandForPerson();
    } else {
        return executeCommandForTag();
    }
}

4.4.4. Command Logic

The edit command undergoes a typical command execution in the Logic Component. Refer to Figure 3.3.3.

The following sequence diagram shows the interactions with the Model Component.

EditCommandForTagSequenceDiagram

Figure 4.4.4.1 : How each tag is edited from the Address Book and each Person’s list of tags

4.4.5. Design Considerations

Aspect: Implementation of Edit Tags.

The design considerations are similar to the to Implementation of Delete Tags.

Modifying the existing edit command was picked over creating a new command edittag

4.5. Tag Colouring Mechanism

Tag labels appear in various UI components: PersonCard, TagListPanel and PersonInfoPanel.
In order for a tag to have the same color across all components, there was a need for the UI Components to keep track of what colors have been used and which color was a tag tied to.
You will be able to understand how a Singleton class TagColorMap was implemented.

ClassDiagramTagColorMap

Figure 4.5.1 : The class diagram for TagColorMap

As a result of this singleton class, coloring tags on initialisation is made extremely easy, since TagColorMap provided UI components an easy way to access the color mapping of tags and color the tags accordingly in the application, from anywhere in the code base.

The following code is common in PersonCard.java, TagListPanel.java, PersonInfoPanel.java as all the these components require rendering tags, especially in the initTags method shown below.

private void initTags(ReadOnlyPerson person) {
    person.getTags().forEach(tag -> {
            Label tagLabel = new Label(tag.tagName);
            tagLabel.setStyle("-fx-background-color: " + TagColorMap.getInstance().getTagColor(tag.tagName));
            tags.getChildren().add(tagLabel);
        }
    );
}

4.5.1. Design Considerations

Aspects: Implementation Coloring of Tag
Alternative 1 (current choice): A singleton class TagColorMap to provide colors, and mapping of tags to colors is used.
Pros: This is easy to implement and easy to access from any UI Component.
Cons: This increases coupling across the code base. Difficult to replace TagColorMap with a stub when doing tests.
Alternative 2: TagColorMap as a class attribute of MainWindow is used and is passed as a parameter to the constructors of relevant UI components.
Pros: This is a naive method and straightforward to implement.
Cons: This requires a large amount of modification of existing code base of the UI component.


4.6. Remark Command Mechanism

The remark command allows user to modify the remark of a contact, and it supports adding, editing and deleting remarks.
It is different from adding the tags using AddCommand as you should notice that it is used to store the unique information of the contact.
We are implementing this Remark Command because NUS students see a need to add additional information to their contacts as a reminder to themselves, such as owesMoney to someone.

Generally, the implementation of this command is similar to EditCommand.


These main classes are added to implement this enhancement:

  • Remark

  • RemarkCommand

  • RemarkCommandParser

  • …​

These main classes are significantly edited to implement this enhancement:

  • AddressBookParser

  • PersonListCard

  • PersonCardHandle

  • XmlAdaptedPerson

  • Person

  • EditCommand

  • AddCommand

  • …​

ℹ️
Instead of typing the command remark, an alternative would be rm.
The alias is added to the RemarkCommand Class.
The added remark will be displayed on the last line of the person card.
If a person is newly added to the personList by AddCommand, its remark field will be an empty string.
In the EditCommand class, a new attribute updatedRemark is added to the person, and it is independent from editPersonDescriptor.

4.6.1. Implementation of Remark Command

[Step 1] Logic: Teach the app to accept remark which does nothing

[Step 2] Logic: Teach the app to accept remark arguments

[Step 3] Ui: Add a placeholder for remark in PersonCard

[Step 4] Model: Add Remark class

[Step 5] Model: Modify ReadOnlyPerson to support a Remark field

[Step 6] Storage: Add Remark field to XmlAdaptedPerson class

[Step 7] Ui: Connect Remark field to PersonCard

[Step 8] Logic: Implement RemarkCommand#execute() logic

4.6.2. Codes and Diagrams

The following diagram shows the high-level sequence diagram of the RemarkCommand for you:

RemarkCommandHighLevelSequenceDiagram

Figure 4.6.2.1 : High-level sequence diagram

RemarkCommand extends UndoableCommand, which is an abstract subclass of abstract class command, so the user can also undo the added remark. The class inheritance diagram is shown below:

RemarkCommandClassInheritanceDiagram

Figure 4.6.2.2 : Class Inheritance Diagram

The implementation is shown below.

/*
 * Edits the remark of a person to the address book.
 */
public class RemarkCommand extends UndoableCommand {
    //...
}

After RemarkCommand is executed, the new data will be saved to the AddressBook. The logic component sequence diagram is shown below:

RemarkCommandLogicComponentSequenceDiagram

Figure 4.6.2.3 : Logic Component Sequence Diagram

We create a new Remark attribute, and the Person class is linked to it. Its model component class diagram is shown below:

RemarkCommandComponentClassDiagram

Figure 4.6.2.4 : Component Class Diagram

The implementation is shown below.

public class Person implements ReadOnlyPerson {
    //...
    private ObjectProperty<Address> address;
    private ObjectProperty<Timetable> timetable;
    private ObjectProperty<Remark> remark;

    // ...
}

4.6.3. Design Considerations

Aspects: UI Display of Remark
Alternative 1(current choice): The remark of the specified contact at the end of the personCard is displayed.
Pros: This has the consistent format with other fields in the person card.
Cons: This does not highlight the remark so that the user might hardly notice the additional remark information.
Alternative 2: The Remark is displayed next to the name.
Pros: This would be able to better reminds the user of the added remark information. Also, the font-size is larger that is easier to read.
Cons: This does not have the consistent formatting with other fields in the person card. If the remark is too long, it will be poorly displayed as well.


Aspects: The command nature of Remark
Alternative 1(current choice): A RemarkCommand to add remarks to a contact is used.
Pros: It is not the compulsory field when a person is added as most people do not add remarks to a newly added contact.
Cons: It is an extra command for the user to remember.
Alternative 2: AddCommand and EditCommand are used for adding and editing of the remark.
Pros: The command lines are more intuitive for the user.
Cons: The remark is perceived as a compulsory field of personal information for that contact, but this is not true.

4.7. Photo Command Mechanism

The photo command allows users to assign photos to their contacts, and it also supports adding, editing and deleting photos as the remark command. You will be able to understand how it accepts the absolute path in the user’s computer and copies the original photo to the default folder of the file. We are implementing this PhotoCommand as NUS students may want to keep themselves reminded of how their contacts look like.


These classes are added to implement this enhancement:

  • PhotoPath

  • PhotoCommand

  • PhotoCommandParser

  • PhotoPathNotFoundException

  • DuplicationPhotoPathException

  • UniquePhotoPathList

  • XmlAdaptedPhotoPath

  • …​

These classes are edited to implement this enhancement:

  • AddressBook

  • FileUtil

  • AddCommand

  • EditCommand

  • PersonInfoPanel

  • XmlAdaptedPerson

  • Person

  • …​


ℹ️
Instead of typing the command photo, an alternative would be ph.
The alias is added to the PhotoCommand Class.
The added photo will be displayed on the PersonInfoPanel.
If a photoPath is newly added to the photoList by PhotoCommand, it will be saved to the default folder and linked to the specified contact.
If a photoPath is removed from one contact, the link between the photo and the contact will be removed, but the photo file are still kept inside the folder until the next time the user starts the application in case the user wants to undo the command.
Up to now, the photo command hasn’t supported the RedoCommand.

4.7.1. Implementation of Photo Command

[Step 1] Logic: Create the photoCommandParser class to parse the input.

[Step 2] Logic: Teach the app to accept photoPath arguments

[Step 3] Ui: Add a Shape Circle for displaying the photo in personInfoPanel

[Step 4] Model: Add PhotoPath class

[Step 5] Model: Modify ReadOnlyPerson to support a photoPath field

[Step 6] Storage: Add the photoPath field to XmlAdaptedPerson class

[Step 7] Ui: Connect the photoPath field to PersonInfoPanel class, display the contact photo

[Step 8] Logic: Implement PhotoCommand#execute() logic

[Step 9] Commons: Implement related methods in FileUtil

[Step 10] Models: Implement how to initialize the UniquePhotoPathList and delete unused photo in AddressBook class

4.7.2. Codes and Diagrams

The interactions between multiple objects are complicated, so the following diagram shows the simplified high-level sequence diagram for you:

PhotoCommand highLevelSequenceDiagrams

Figure 4.7.2.1 : High-level Sequence Diagram

For the logic component part, the PhotoCommandParser is created by the AddressBookParser, and the PhotoCommand is created by the PhotoCommandParser. The logic component class diagram is shown below:

PhotoCommand logicComponentClassDiagram

Figure 4.7.2.2 : Logic Component Class Diagram

Also, the PhotoCommand class inherits from the UndoableCommand class. The implementation is shown below.

/**
 * Edits the photo path of the specified person.
 */
public class PhotoCommand extends UndoableCommand {
    //...
}

As shown in Figure 4.7.2.3, the AddressBook consists of one UniqueTagList, one UniquePersonList, and one UniquePhotoPathList. The UniquePhotoPathList acts as a container for PhotoPath objects.

PhotoCommand modelComponentClassDiagram

Figure 4.7.2.3 : Model Component Class Diagram

We create a new PhotoPath attribute, and the Person class is linked to it.

The implementation is shown below.

/**
 * Represents the path of a person's photo in the address book.
 */
public class PhotoPath {

    public static final String FILE_SAVED_PARENT_PATH = "src/main/resources/images/contactPhotos/";
    public static final String MESSAGE_APP_PHOTOPATH_CONSTRAINTS =
            "The app photo path should be a string starting with '"
                    + FILE_SAVED_PARENT_PATH
                    + "', following by the file name with a valid extension, like'photo.jpg'.\n"
                    + "The valid extensions are 'jpg', 'jpeg', 'png', 'gif' or 'bmp'.";

    public final String value;

    //...
}

4.7.3. Design Considerations

Aspects: The way the contact photo saved in users' computers is retrieved.
Alternative 1 (current choice): Users are required to specify the absolute path of the photo.
Pros: This might be inconvenient as users need additional steps to get the absolute file of the photo.
Cons: The image file is specified accurately by using the command line.
Alternative 2: Users are provided a pop-up window to choose the photo.
Pros: It is more convenient for the user to choose the file.
Cons: This becomes no more a command-line input in this command-line application.

4.8. Birthday Attribute

Users are able to store birthdays by inputting in the format of DDMMYYYY when adding a person. You will be able to understand how Birthday is being stored and parsed over. This allows the user to get a list of people having the same birthday month.

In general, the ability to store a person’s birthday was implemented via an augmentation of the component of Person.

4.8.1. Representation of Birthdays

Storing of birthdays is facilitated by an immutable Birthday object, which is a component of Person.

The following are the main classes edited to implement this:

  • AddCommand

  • AddCommandParser

  • EditCommand

  • EditCommandParser

  • Person

  • PersonListCard, PersonCardHandle

  • XmlAdaptedPerson

The following UML diagram represents the implementation of the classes in the Model component.

BirthdayModelComponentClassDiagram

Figure 4.8.1.1 : UML diagram for updated Model with Birthday

4.8.2. Validation of Birthdays

After the birthday is input, it will be checked if the date is valid. The number of digits input will be checked first. Then the year would be checked from the 20th century until now. Range of day input will then be checked according to month.

public static boolean isValidBirthday(String test) {

    if (test.matches(BIRTHDAY_VALIDATION_REGEX)) {
        try {
            DateFormat df = new SimpleDateFormat(DATE_FORMAT);
            df.setLenient(false);
            df.parse(test);
            return true;
        } catch (ParseException pe) {
            return false;
        }
    }
    return false;
}

4.8.3. Design Considerations

Aspect: Representation of birthdays
Alternative 1 (current choice): The birthday of the specified contact is displayed as string of numbers with / separating the day, month and year.
Pros: This is easy to implement as there is no need to alter the input.
Cons: It is difficult to recognise the date from the number displayed.
Alternative 2: The birthday is in the format of 25 Dec 1997.
Pros: It is simple and easy to understand.
Cons: It requires extra methods to change the format displayed.

4.9. Find Command [Filter] Mechanism

Finding a person by filters means that users will be able to find a person using different fields of information. Currently, UniFy supports users to find a person by name, phone, email, address, tags and birthday month. This allows users to have more flexibility in the way they search for their contacts.
Only persons who match all keywords in all fields will be returned. You will be able to understand how the result of the find command is determined.

In general, the ability to find persons by filters was implemented by modifying the existing find command.

The modification involves:

  • Parsing of user input in the FindCommandParser

  • Searching of different fields for the person list in the FindCommand

4.9.1. Parsing of user input

The input will be tokenized against the n/, p/, e/, a/, t/ and b/ prefixes which are for name, phone, email, address, tags and birthday month respectively. This can be done by the ArgumentTokenizer class.
The user input will be parsed as an ArrayList with prefixes and keywords separated. If the index of n/ is 1, the keywords for the name field will be at the index of 2 in the ArrayList.

The implementation of this parse is shown below:

if (argsMultimap.getValue(PREFIX_NAME).isPresent()) {
    nameList = argsMultimap.getValue(PREFIX_NAME).get();
    predicate.add(PREFIX_NAME.getPrefix());
    predicate.add(nameList);
}

Since the field of b/ only takes in birthday month, a small check is implemented to determine the validity of the keyword input. The birthday month is checked to only contain integer and be within the range of 1 to 12.

The implementation of this check is shown below:

// checks if birthday month contains non-integers, and returns "Keyword input must be in integer."
if (!birthdayList.matches("[0-9]+")) {
    throw new ParseException(FindCommand.MESSAGE_BIRTHDAYKEYWORD_NONNUMBER);

// checks if birthday month in out of bound, and returns "Month %1$s does not exist."
} else if (Integer.parseInt(birthdayList.trim()) > 12 || Integer.parseInt(birthdayList.trim()) < 1) {
    throw new ParseException(String.format(FindCommand.MESSAGE_BIRTHDAYKEYWORD_NONEXIST, birthdayList.trim()));

} else if (birthdayList.trim().length() == 1) {
    throw new ParseException(String.format(FindCommand.MESSAGE_BIRTHDAYKEYWORD_INVALID, birthdayList.trim()));
}

4.9.2. Searching of Persons using several fields of information

The search is done using the following steps.

  1. The code searches persons matching the keyword in the name field, followed by the rest of the fields.

  2. The persons matching the keyword will be added into a HashMap<String, Integer> that stores the name of the person and the number of times the person matches the keywords.

  3. The persons are then added to a new ArrayList if the number of times the person matches the keywords equals to the number of keywords input.

  4. The ArrayList containing names of persons, having information that matches all keywords in respective fields, will be updated in the filtered list.

  5. The find result displayed to users.

The implementation of person’s phone being searched is shown below:

public ArrayList<String> findPersonsWithPhone(String phone) {
    // Get the list of persons in UniFy
    ObservableList<ReadOnlyPerson> personList = model.getAddressBook().getPersonList();

    String[] phoneKeyword = phone.split(" ");

    // Keeping track of the number of keywords input in total
    count += phoneKeyword.length;

    ArrayList<String> phoneList = new ArrayList<>();

    for (ReadOnlyPerson person : personList) {
        for (String keyword : phoneKeyword) {
            String phones = person.getPhone().toString();

            // keyword is a subset of phones (do not have to match fully)
            if (phones.contains(keyword)) {
                phoneList.add(person.getName().toString());
            }
        }
    }
    return phoneList;
}

The implementation of tracking the number of times a person being matched is shown below:

// if phone prefix is input
if (predicates.equals(PREFIX_PHONE.getPrefix())) {

    // Result from the code above
    ArrayList<String> personsWithPhone = findPersonsWithPhone(predicate.get(i + 1));

    for (int j = 0; j < personsWithPhone.size(); j++) {

        // if it is the first time this person is being searched, add the person in with time of matches = 1
        if (!predicateMap.containsKey(personsWithPhone.get(j))) {
            predicateMap.put(personsWithPhone.get(j), 1);
            predicateList.add(personsWithPhone.get(j));

        // if the person is searched before, increase the time of matches by 1
        } else {
            predicateMap.put(personsWithPhone.get(j), predicateMap.remove(personsWithPhone.get(j)) + 1);
        }
    }
}

4.9.3. Command Logic

The following is the logic component class diagram for FindCommand

FindCommandLogicComponentSequenceDiagram

Figure 4.9.3.1 : FindCommand Logic Component Class Diagram

4.9.4. Design Considerations

Aspect: Implementation of find command
Alternative 1 (current choice): Only the persons matching all keywords are returned.
Pros: This aligns with the purpose of implementing this enhancement to allow users to refine and limit their search by inputting more keywords in different fields.
Cons: It is harder to implement as we need to keep track of how many times a person is being matched.
Alternative 2: All persons matching one or more keywords are returned.
Pros: It is simple to implement.
Cons: By typing more keywords in different fields, more persons matching one of the keywords will be returned which defeats the purpose of having this enhancement.

4.10. Suggest Command Mechanism

This feature will conduct spelling check if the command input does not match any of the existing commands. It will prompt an error message suggesting the correct spelling of the command word. You will be able to understand how the code determines the correct spelling.
This is implemented because there is many commands to remember in UniFy and we suspect users might have typos during their usage.

In general, the ability of this command was implemented by adding a SuggestCommand class.

4.10.1. Implementation of Suggest Command

SuggestCommand class calls the UniqueCommandList class to determine the possible correct spellings and to retrieve the list of command words existing in the address book.

We have identified a few spelling mistakes that our users might make.

  • Two alphabets swapping positions

  • One extra alphabet added

  • One alphabet lacking

  • One alphabet mistyped

The implementation of the determination of possible spellings is shown below:

public static TreeSet<String> getPossibleCommandList(String command) {
    possibleCommandList = new TreeSet<>();

    // Swapping i with i+1
    for (int i = 1; i < command.length() - 1; i++) {
        possibleCommandList.add(command.substring(0, i) + command.charAt(i + 1) + command.charAt(i) + command.substring(i + 2));
    }

    // deleting one char, skipping i
    for (int i = 0; i < command.length(); i++) {
        possibleCommandList.add(command.substring(0, i) + command.substring(i + 1));
    }

    // inserting one char
    for (int i = 0; i < command.length() + 1; i++) {
        for (char j = 'a'; j <= 'z'; j++) {
            possibleCommandList.add(command.substring(0, i) + j + command.substring(i));
            // replacing one char
            if (i < command.length()) {
                possibleCommandList.add(command.substring(0, i) + j + command.substring(i + 1));
            }
        }
    }
    return possibleCommandList;
}

4.10.2. Design Considerations

Aspect: Implementation of suggest command
Alternative 1 (current choice): An error message suggesting the correct spelling for the command word is returned.
Pros: This is easier to implement without modification of other command classes.
Cons: This would still require the user to correct his spelling error by himself.
Alternative 2: The suggested command is conducted then prompt to ask if the user is intending to conduct such an action.
Pros: This does not require the user to retype to correct his spelling error.
Cons: This is harder to implement and if the user do not intent to conduct the suggested command action, the user has to do an extra step to undo the command, which might be inconvenient.

4.11. Logging

We are using java.util.logging package for logging. The LogsCenter class is used to manage the logging levels and logging destinations.

  • The logging level can be controlled using the logLevel setting in the configuration file (See Configuration)

  • The Logger for a class can be obtained using LogsCenter.getLogger(Class) which will log messages according to the specified logging level

  • Currently log messages are output through: Console and to a .log file.

Logging Levels

  • SEVERE : Critical problem detected which may possibly cause the termination of the application

  • WARNING : Problems detected that does not affect the usage of app, but requires to continue with caution

  • INFO : Information showing the noteworthy actions by the App

  • FINE : Details that is not usually noteworthy but may be useful in debugging e.g. print the actual list instead of just its size

4.12. Configuration

Certain properties of the application can be controlled (e.g App name, logging level) through the configuration file (default: config.json).

5. Documentation

We use asciidoc for writing documentation.

ℹ️
We chose asciidoc over Markdown because asciidoc, although a bit more complex than Markdown, provides more flexibility in formatting.

5.1. Editing Documentation

You can see UsingGradle.adoc to learn how to render .adoc files locally to preview the end result of your edits. Alternatively, you can download the AsciiDoc plugin for IntelliJ, which allows you to preview the changes you have made to your .adoc files in real-time.

5.2. Publishing Documentation

You can see UsingTravis.adoc to learn how to deploy GitHub Pages using Travis.

5.3. Converting Documentation to PDF format

We use Google Chrome for converting documentation to PDF format, as Chrome’s PDF engine preserves hyperlinks used in webpages.

Here are the steps to convert the project documentation files to PDF format.

  1. Follow the instructions in UsingGradle.adoc to convert the AsciiDoc files in the docs/ directory to HTML format.

  2. Go to your generated HTML files in the build/docs folder, right click on them and select Open withGoogle Chrome.

  3. Within Chrome, click on the Print option in Chrome’s menu.

  4. Set the destination to Save as PDF, then click Save to save a copy of the file in PDF format. For best results, use the settings indicated in the screenshot below.

chrome save as pdf

Figure 5.6.1 : Saving documentation as PDF files in Chrome

6. Testing

6.1. Running Tests

There are three ways to run tests.

💡
The most reliable way to run tests is the 3rd one. The first two methods might fail some GUI tests due to platform/resolution-specific idiosyncrasies.

Method 1: Using IntelliJ JUnit test runner

  • To run all tests, right-click on the src/test/java folder and choose Run 'All Tests'

  • To run a subset of tests, you can right-click on a test package, test class, or a test and choose Run 'ABC'

Method 2: Using Gradle

  • Open a console and run the command gradlew clean allTests (Mac/Linux: ./gradlew clean allTests)

ℹ️
See UsingGradle.adoc for more info on how to run tests using Gradle.

Method 3: Using Gradle (headless)

Thanks to the TestFX library we use, our GUI tests can be run in the headless mode. In the headless mode, GUI tests do not show up on the screen. That means the developer can do other things on the Computer while the tests are running.

To run tests in headless mode, open a console and run the command gradlew clean headless allTests (Mac/Linux: ./gradlew clean headless allTests)

6.2. Types of tests

We have two types of tests:

  1. GUI Tests - These are tests involving the GUI. They include,

    1. System Tests that test the entire App by simulating user actions on the GUI. These are in the systemtests package.

    2. Unit tests that test the individual components. These are in seedu.address.ui package.

  2. Non-GUI Tests - These are tests not involving the GUI. They include,

    1. Unit tests targeting the lowest level methods/classes.
      e.g. seedu.address.commons.StringUtilTest

    2. Integration tests that are checking the integration of multiple code units (those code units are assumed to be working).
      e.g. seedu.address.storage.StorageManagerTest

    3. Hybrids of unit and integration tests. These test are checking multiple code units as well as how the are connected together.
      e.g. seedu.address.logic.LogicManagerTest

6.3. Troubleshooting Testing

Problem: HelpWindowTest fails with a NullPointerException.

  • Reason: One of its dependencies, UserGuide.html in src/main/resources/docs is missing.

  • Solution: Execute Gradle task processResources.

7. Dev Ops

7.1. Building Automation

See UsingGradle.adoc to learn how to use Gradle for build automation.

7.2. Continuous Integration

We use Travis CI and AppVeyor to perform Continuous Integration on our projects. See UsingTravis.adoc and UsingAppVeyor.adoc for more details.

7.3. Making a Release

Here are the steps to create a new release.

  1. Update the version number in MainApp.java.

  2. Generate a JAR file using Gradle.

  3. Tag the repo with the version number. e.g. v0.1

  4. Create a new release using GitHub and upload the JAR file you created.

7.4. Managing Dependencies

A project often depends on third-party libraries. For example, Address Book depends on the Jackson library for XML parsing. Managing these dependencies can be automated using Gradle. For example, Gradle can download the dependencies automatically, which is better than these alternatives.
a. Include those libraries in the repo (this bloats the repo size)
b. Require developers to download those libraries manually (this creates extra work for developers)

Appendix A: Use Cases

(For all use cases below, the System is the AddressBook and the Actor is the user, unless specified otherwise)

Use case: Delete person

MSS

  1. User requests to list persons

  2. AddressBook shows a list of persons

  3. User requests to delete the specific person(s) in the list

  4. AddressBook deletes the person(s)

    Use case ends.

Extensions

  • 2a. The list is empty.

    Use case ends.

  • 3a. One of the given indexes is invalid.

    • 3a1. AddressBook shows an error message.

      Use case resumes at step 2.

Use case: Edit a specific tag word

MSS

  1. User requests to edit a tag

  2. AddressBook shows the tag about to be edited

  3. User requests to a new word to replace the current tag

  4. AddressBook edits the tag word

    Use case ends.

Extensions

  • 3a. The tag does not exist

    Use case ends.

  • 3b. The new word to replace the given tag is an existing tag

    • 3b1. AddressBook shows an error message.

      Use case resumes at step 2.

Use case: Type an incorrect command

MSS

  1. User requests with an incorrect command

  2. AddressBook shows the suggested command based on user’s misspelling or prompts help if the incorrect command cannot be identified

  3. User requests with a correct command

    Use case ends.

Use case: Edit person

MSS

  1. User requests to list persons

  2. AddressBook shows a list of persons

  3. User requests to edit the details of the person identified by the index number in the listing

  4. AddressBook edits the details of the identified person

    Use case ends.

Extensions

  • 1a. AddressBook detects an error in the entered command

    • 1a1. AddressBook requests for the correct command

      Use case resumes at step 2

  • 3a. AddressBook detects an error in the entered command

    • 3a1. AddressBook requests for the correct command

    • 3a2. User enters new command

      Use case resumes from step 4.

Use case: Undo

MSS

  1. User requests to undo previous action

  2. AddressBook search for the previous action done

  3. AddressBook undo the previous action

    Use case ends.

Extensions

  • 3a. The previous command is undoable.

    Use case resume at step 2.

  • 3a. All previous commands are undoable.

    • 3a1. AddressBook shows an error message.

      Use case ends.

Appendix B: Non Functional Requirements

  1. Should work on any mainstream OS as long as it has Java 1.8.0_60 or higher installed.

  2. Should be able to hold up to 1000 persons without a noticeable sluggishness in performance for typical usage.

  3. A user with above average typing speed for regular English text (i.e. not code, not system admin commands) should be able to accomplish most of the tasks faster using commands than using the mouse.

  4. Have a user interface that is visible for use indoors as well as outdoors

  5. A user who is not very tech savvy will be able to familiar in using the application within 2 hours of use.

  6. Only the user himself can access his address book

  7. Should be able to easily find a person within a large amount of contacts in terms of robustness in searching capability (i.e. the use of multiple filters)

  8. Should be able to recover the address book data in case of loss of data

  9. User guide is clear and concise

  10. Should be as responsive as possible (a maximum of 0.3 millisecond)

  11. Should be possible to upgrade to it from any previous version when a new version is released

Appendix C: Glossary

Mainstream OS

Windows, Linux, Unix, OS-X

Private contact detail

A contact detail that is not meant to be shared with others.

Bright coloured mode

Using brighter colours for the user interface to make the AddressBook more visible under the sun.

Attribute

A characteristic of a person that is common across all people (e.g. Relationship/Marital Status, Birthday, Gender, Age).

Suggested (a command)

The app will conduct the suggested command based on the detection of a misspelling of a command (e.g. find is suggested when fnid is spelled).

Preamble

A short marker used to synchronize a transmission by indicating the end of the header information and the start of the data.