Skip to content

Latest commit

 

History

History
2040 lines (1510 loc) · 96.1 KB

DeveloperGuide.adoc

File metadata and controls

2040 lines (1510 loc) · 96.1 KB

Address++ - Developer Guide

1. Setting up

1.1. Prerequisites

  1. JDK 1.8.0_60 or later

    ℹ️
    Having any Java 8 version is not enough.
    This app will not work with earlier versions of Java 8.
  2. IntelliJ IDE

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

1.2. Setting up Address++ 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 a 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.

1.3. Verifying the setup

  1. Run the seedu.address.MainApp and try a few commands

  2. Run the tests to ensure they all pass.

1.4. Configurations to do before writing code

1.4.1. Configuring the coding style

This 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.*, 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 as you write code.

1.4.2. Updating documentation to match your fork

After forking the repo, links in the documentation will still point to the CS2103AUG2017-W09-B2/main repo. If you plan to develop this as a separate product (i.e. instead of contributing to the CS2103AUG2017-W09-B2/main) , you should replace the URL in the variable repoURL in DeveloperGuide.adoc and UserGuide.adoc with the URL of your fork.

1.4.3. Setting up CI

Set up Travis to perform Continuous Integration (CI) for your fork. See UsingTravis.adoc to learn how to set it up.

Optionally, you can set up AppVeyor as a second CI (see 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)

1.4.4. Getting started with coding

When you are ready to start coding,

  1. Get some sense of the overall design by reading the Architecture section.

  2. Take a look at the section Suggested Programming Tasks to Get Started.

2. Design

2.1. Architecture

Architecture

Figure 2.1.1 : Architecture Diagram

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

💡
The .pptx files used to create diagrams in this document can be found 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.

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

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

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

Commons represents a collection of classes used by multiple other components. Two of those 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 (i.e. a form of Event Driven design)

  • LogsCenter : Used by many classes to write log messages to the App’s log file.

The rest of the App consists of four components.

  • UI : The UI of the App.

  • Logic : The command executor.

  • Model : Holds the data of the App in-memory.

  • Storage : Reads data from, and writes data to, 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 (see the class diagram given below) defines it’s API in the Logic.java interface and exposes its functionality using the LogicManager.java class.

LogicClassDiagram

Figure 2.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 2.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 2.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 is an example of how this Event Driven approach helps us reduce direct coupling between components.

The sections below give more details of each component.

2.2. UI component

UiClassDiagram

Figure 2.2.1 : Structure of the UI Component

API : Ui.java

The UI consists of a MainWindow that is made up of parts e.g.CommandBox, ResultDisplay, PersonListPanel, StatusBarFooter, BrowserPanel etc. 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.

2.3. Logic component

LogicClassDiagram

Figure 2.3.1 : Structure of the Logic Component

LogicCommandClassDiagram

Figure 2.3.2 : Structure of Commands in the Logic Component. This diagram shows finer details concerning XYZCommand and Command in Figure 2.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 2.3.1 : Interactions Inside the Logic Component for the delete 1 Command

2.4. Model component

ModelClassDiagram

Figure 2.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.

  • exposes an unmodifiable ObservableList<ReadOnlyTask> that can be 'observed'.

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

2.5. Storage component

StorageClassDiagram

Figure 2.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.

2.6. Common classes

Classes used by multiple components are in the seedu.addressbook.commons package.

3. Implementation

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

3.1. Increase/Decrease/Reset Font Size

On some screens, the text appear to be too small. The aim of the increase/decrease/reset font size feature is to allow users to customize the application’s font size quickly on the go.

FontSizeUI

Figure 3.1.1 : Using the UI to change font size

There are two methods of calling changes in font size:

  1. onAction handlers are used to handle UI font size buttons. These handlers will post new events via ComponentManager.

  2. CLI commands also post new events to handle font size changes, when the relevant command is entered (e.g. fontsize increase).

FontSizeChangeSequenceDiagram

Figure 3.1.2 : Sequence diagram for fontsize changing

From the sequence diagram above, we can observe that the font size changes are handled by subscriber functions in PersonListPanel and TaskListPanel.

ℹ️
The initial implementation required access to the model from the UI. This implementation was replaced with one that standardised the handling of font size change requests through events.

3.1.1. Design Considerations

Aspect: Use either UI or CLI based implementations
Alternative 1 (current choice): Implementing both UI and CLI functionality
Pros: More options for the user. Not much increase in complexity when implementing the CLI version
Cons: This implementation required passing information between classes, which may cause unnecessary coupling.

Alternative 2: Implementing only UI functionality
Pros: Less tedious to implement and very intuitive for the user
Cons: Users who prefer typing commands will not have the option of editing their font sizes using the CLI

3.2. Setting Avatar on ViewPersonPanel

The following function allows the setting of URL for the ImageView attribute within the ViewPersonPanel class:

private void initializeAvatar() {
        try {
            String avatarPath = person.getAvatar().value;
            if (!avatarPath.equals("")) {
                logger.info("Initializing avatar to image at saved URL");
                Image newImage = new Image(avatarPath);
                avatarImage.setImage(newImage);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

The initializeAvatar method piggybacks on the handlePersonPanelSelectionChangedEvent event handler. Whenever there is a change in the person selection panel, this function will call the initializeAvatar method, which will update the ImageView attribute.

@Subscribe
private void handlePersonPanelSelectionChangedEvent(PersonPanelSelectionChangedEvent event) {
    logger.info(LogsCenter.getEventHandlingLogMessage(event));
    this.person = event.getNewSelection().person;
    initializeWithPerson(person);
    initializeAvatar();
}
ℹ️
As of v1.5, the avatar field supports only URLs sourced online. References to local files may work but require the prefix "file:"

3.3. Undo/Redo mechanism

The undo/redo mechanism 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. The following diagram shows the inheritance diagram for commands:

LogicCommandClassDiagram

Figure 3.3.1 : Command inheritance

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. Note that this 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 ...
    }
}

Suppose that 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. The 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 3.3.2 : Initial status of undo/redo stack

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 3.3.3 : After executing `delete 5`

ℹ️
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 3.3.4 : Executing undo

ℹ️
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 3.3.5 : Undo/redo sequence diagram

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 3.3.6 : Executing `clear`

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 3.3.7 : Stack is not changed after `list`

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

UndoRedoActivityDiagram

Figure 3.3.8 : Undo/Redo activity diagram

3.3.1. Design Considerations

Aspect: Implementation of UndoableCommand
Alternative 1 (current choice): Add a new abstract method executeUndoableCommand()
Pros: We will not lose any undone/redone functionality as it is now part of the default behaviour. Classes that deal with Command do not have to know that executeUndoableCommand() exist.

Cons: Hard for new developers to understand the template pattern.
Alternative 2: Just override execute()
Pros: Does not involve the template pattern, easier for new developers to understand.
Cons: Classes that inherit from UndoableCommand must remember to call super.execute(), or lose the ability to undo/redo.


Aspect: How undo & redo executes
Alternative 1 (current choice): Saves the entire address book.
Pros: Easy to implement.
Cons: May have performance issues in terms of memory usage.

Alternative 2: Individual command knows how to undo/redo by itself.
Pros: Will use less memory (e.g. for delete, just save the person being deleted).
Cons: We must ensure that the implementation of each individual command are correct.


Aspect: Type of commands that can be undone/redone
Alternative 1 (current choice): Only include commands that modifies the address book (add, clear, edit).
Pros: We only revert changes that are hard to change back (the view can easily be re-modified as no data are lost).
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: Include all commands.
Pros: Might be more intuitive for the user.
Cons: User have no way of skipping such commands if he or she just want 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): Use separate stack for undo and redo
Pros: Easy to understand for new Computer Science student undergraduates to understand, 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: Use HistoryManager for undo/redo
Pros: We do not need to maintain a separate stack, and just reuse what is already in the codebase.
Cons: Requires 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.

3.4. Task Object

The Task object stores information related to a single deadline or task, in a manner similar to how Person information is stored.
As such, it also shares the same types of commands as the Person object, namely the add, delete, find, select, and edit commands. Object inheritance is thus used to create the commands that are shared with those used to handle Person objects.

An example of using inheritance to handle Person vs Task addition:

public class AddPersonCommand extends AddCommand {
}

public class AddTaskCommand extends AddCommand {
}
public AddCommand parse(String args) throws ParseException {
    int objectType = checkType(args);

    if (objectType == HANDLE_TYPE_PERSON) {
        Person toAdd = createNewPerson(args);
        return AddPersonCommand(toAdd);
    } else if (objectType == HANDLE_TYPE_TASK) {
        Task toAdd = createNewTask(args);
        return AddTaskCommand(toAdd);
    }
}

The Parser in charge of the command will thus return either an AddPersonCommand, or an AddTaskCommand, depending on whether you specify to add a Task or not in the arguments.
The sequence diagram below shows how this is done:

AddTaskSeq

Figure 3.4.1.1 : Sequence Diagram for adding a Task

3.4.2. Task structure and subclasses

The Task object has several subclasses, which store information about the task. The following class diagram illustrates the structure of a Task object.

TaskClassDiagram

Figure 3.4.2.1 : Class Diagram for the Task class

Each subclass contains its own methods for input validation, and the Assignees class supports some methods for changing its assignedList.

3.4.3. Task Object Storage

---
    <persons>
        <name>someone else</name>
        <phone></phone>
        <email></email>
        <address></address>
    </persons>
    <tasks>
        <name>Buy new pencil</name>
        <description>Buy new pencil for writing purposes</description>
        <deadline></deadline>
        <priority>2</priority>
    </tasks>
---

Task objects are stored in a similar manner to Person objects, and share the same level of hierarchy as Person objects. During startup, tasks are read and entered into the UniqueTaskList, which handles all the tasks that are present in the address book.

3.4.4. Design Considerations

Aspect: Implementation of Task-related commands

Alternative 1 (current choice): Use inheritance to implement different commands for Task and Person objects
Pros: Can be easily extended to allow handling of other types of objects, and preserves Separation of Concerns.
Cons: Minor code duplication occurs as the commands for Person and Tasks objects share the same structure.

Alternative 2: Use polymorphism to allow existing commands to implement task handling
Pros: Code duplication is kept to a minimum as the Command will handle Task and Person objects in the same class.
Cons: Single Responsibility Principle is violated as each Command class now needs to handle 2 different types of objects.


Aspect: Storage of Task objects

Alternative 2: Store Task objects together in the default XML storage file
Pros Only 1 storage file is needed. The storage manager thus only needs to refer to one storage
Cons Any changes to the Person or Task will affect the storage of both the Person and Task objects. This will increase coupling between the Person and Task classes.

Alternative 1 (current choice): Store Tasks objects in a separate XML file
Pros: Easier to manage as Person storage will not interfere with Task storage, and vice versa.
Cons: All existing save/load functions will require an additional method to handle Task storage.

3.5. Assign and Dismiss Commands

The assign and dismiss command allows you to assign contacts to and from your tasks, thus aiding coordination and collaboration.
The Assignees class stores information related to who is assigned to a particular task through maintaining an internal ArrayList that keeps track of all the indexes of the people who are assigned to the task.

The indexes stored in the Assignees class refer to the index of the person in the UniquePersonList, not the visible index shown to the user in the UI. This means that the indexes will not change even if the list shown in the UI changes, such as after a find operation.
For example, given the below list of persons:

AssignIndexMovement

Figure 3.5.1 : Mapping of indexes to a task

After a find operation, only the second, fourth and fifth persons are visible. When you call assign 1 2 to/1, while the first and second persons in the visible list will be assigned to the first Task, in this case the "Second person" and "Fourth person", internally the assignee list contain Indexes corresponding the following values:

assignedList = {1, 3}

The indexes 1 and 3 refer to the zero-based index of the "Second person" and "Fourth person" in the complete list.

Due to this requirement, when the UniquePersonList changes, the assigned indexes of each task will be updated as well.

The add operation will not require the assigned indexes to be updated, as each newly added person is not assigned to any task by default, and when a person is added, he is inserted to the end of the list, thus the order of the other persons will not change.

After a clear operation that clears only the persons list, all task assignee lists will be cleared and re-initialized.

After a delete operation, the order of the persons in the persons list may change. This is especially so when the first person is deleted, as this will cause the positions of all other persons to decrease by 1. The activity diagram below illustrates the process of updating task assignee lists when a person is deleted.

AssignIndexDelete

Figure 3.5.2 : Activity Diagram for updating Assignees after deleting a Person

After a sort operation, the order of the persons in the persons list may change as well. However, in comparison to delete, the new position of the person is not fixed. To ensure that the indexes are updated properly, the change in positions after each sort operation is maintained as well inside the UniquePersonList.

AssignIndexSort

Figure 3.5.3 : Mapping of indexes after a sort operation

All task assignee lists will thus be updated using the mappings from the sort operation. Each index in the list will be replaced by the value given in the mappings. For example, if a task previously had an index of "1" assigned to it, it be replaced by an index of "4".

3.5.1. Design Considerations

Aspect: Storage of assigned persons in the Assignee class
Alternative 1 (current choice): Store the Indexes of the persons only
Pros: The assigned persons will only need to be retrieved on a per-need basis, rather than residing in the Assignee class all the time, thus making storage simpler
Cons: UniquePersonList will be coupled to Tasks, as Tasks will need to retrieve information from the UniquePersonList in order to update itself after any operation that could potentially change the UniquePersonList ordering.
Alternative 2: Store the whole person in the Assignees class
Pros: The Assignees class will not need to depend on the UniquePersonList as its internal list is independent from that of the UniquePersonList
Cons: Repetition of information is incurred in the storage file, as the same person can appear multiple times if he is assigned to multiple tasks. This will increase the size of the storage file, and make read-write operations slow.


3.6. Sort Command

The sort command is facilitated by the sortBy methods in UniquePersonList and UniqueTaskList. It supports sort by ascending or by descending order in any field.

The sort enhancement utilises the Java Collections Sort API by passing it a custom Comparator.

The sort command is parsed through SortCommandParser, which passes control over to the SortCommand class. The actual sorting happens via the UniquePersonList class or the UniqueTaskList class.

The UML Class diagram for sort commands that trigger sorting in person listings is shown below:

SortCommandPersonDiagram

Figure 3.6.1 : Sort command class diagram

Likewise, the UML Class diagram for sort commands that trigger sorting in task listings is shown below:

SortCommandTaskDiagram

Figure 3.6.1 : Sort task command class diagram

We can deduce from the UML diagrams diagrams above that the only difference between the implementation of the sorting for persons and tasks lies in the location where the sorting is actually executed. The sorting of persons happens in UniquePersonList class while the sorting of tasks happens in UniqueTaskList.

Suppose a user enters a new command sort person name desc. The following sequence diagram demonstrates how the sort command works.

SortSequenceDiagram

Figure 3.6.1 : Sort command sequence diagram

Note that the execution of the sort methods results in the actual person or task list being sorted. This list will be reflected in both the application’s storage as well as the graphical user interface.

3.6.1. Design Considerations

Aspect: Implementation of sort Command

Alternative 1 (current choice): Implement sorting functionality in UniquePersonList and UniqueTaskList class.
Pros: Delegates the concern of sorting to the class that is responsible for the core of most operations done to the lists. Future changes to the implementation will be easier as a consequence.
Cons: Hard for new developers to understand the flow of control passed between classes at first.

Alternative 2: Implement the sorting functionality within other classes like AddressBook or SortCommand.
Pros: May be more intuitive for new developers and it is easier to trace function calls between lesser classes involved.
Cons: Violates Separation of Concern principle and causes unnecessary content coupling whereby the UniquePersonList and UniqueTaskList will have to rely on the SortCommand class.


Aspect: Temporary Sort Implementation vs. Persistent Sort Implementation

Alternative 1 (current choice): Saves the entire address book after sorting.
Pros: More intuitive and reduces complexity in implementation.
Cons: Old order of contact instances in the address book will be lost

Alternative 2: Duplicate a temporary version of the list and sort it for viewing (i.e. the actual list is not sorted)
Pros: Old order of contact instances remains intact.
Cons: Will use more memory and may be less intuitive for developer to understand and in terms of user experience. Also, sorting will not persist in the system.

3.7. Backup Command

The backup command uses the event handler BackupRequestEvent. When raised, this event notifies the subscriber backupAddressBook method in Storage class.

The outlining sequence diagram for this process (excluding the interaction with the BackupRequestEvent) is shown below:

BackupSequenceDiagram

Figure 3.7.1 : Backup command sequence diagram

3.7.1. Design Considerations

Aspect: Implementation of backup Command

Alternative 1 (current choice): Use an event handler to initialize the backup process
Pros: Avoids coupling the logic to the storage unnecessarily.
Cons: May not be as intuitive for some developers in the beginning

Alternative 2: Access storage component directly instead of using event handlers
Pros: May be more intuitive as it is a direct approach
Cons: Violates the Law of Demeter.

3.8. Lock and Unlock Command

The lock and unlock commands utilise the Model to access the user preferences of the application.

Arguments are processed in the UnlockCommandParser or LockCommandParser, which passes control over to the UnlockCommand and LockCommand class respectively. These Command classes will then call the Model to toggle the lock’s state.

The activity diagram below outlines the basic logic of the lock states concept.:

LockStatesActivityDiagram

Figure 3.8.1 : Lock/Unlock command activity diagram

From the activity diagram we can see that lock states are preserved in the preferences.json file after the application closes by passing the lock state into the UserPrefs class to be saved by the Storage component.

ℹ️
The default state of the lock is set to False (i.e. locked) when the user first opens the application. Subsequent changes to the lock will persist in the user preferences.

3.8.1. Design Considerations

Aspect: Implementation of lock and unlock Commands

Alternative 1 (current choice): Call methods in the Model directly to change UserPrefs
Pros: More intuitive. Highest returns for minimal amount of code
Cons: May be confusing to some developers in the beginning, since another intuitive approach is to use event handlers

Alternative 2: Use Event Handlers
Pros: More intuitive for some developers
Cons: Will still have to access Model, which makes its advantage over direct calls next to none

3.9. ChangePassword Command

The default password when users first open Address++ is password. The ChangePassword command sets a new password in the temporary User Preferences. When the application is closed, this information is passed to the Storage Component to be saved into the file preferences.json

To illustrate this concept better, let us have a look at the preferences.json file:

{
  "guiSettings" : {
    "windowWidth" : 1309.0,
    "windowHeight" : 720.0,
    "windowCoordinates" : {
      "x" : 0,
      "y" : 22
    }
  },
  "addressBookFilePath" : "data/addressbook.xml",
  "addressBookName" : "My Address++",
  "addressBookLockState" : false,
  "addressBookEncryptedPassword" : "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
  "theme" : "/view/DarkTheme.css"
}

As shown in the cope snippet above, the password is stored as one of the entries in the JSON file.

ℹ️
SHA256 encryption was used to calculate a hash for the password. This is to delay anyone snooping around the user’s file directories from seeing the real password immediately.

Validation Checks

  1. Password Validation → Is the password correct?

  2. Password Confirmation → Does the new password and confirmation password match?

  3. Password Uniqueness → Is the new password different from the old password?

The activity diagram below outlines the process flow for the ChangePasswordCommand:

ChangePasswordActivityDiagram

Figure 3.9.1 : ChangePassword command activity diagram

3.9.1. Design Considerations

Aspect: On Demand Saving vs. Save On Exit

Alternative 1 (current choice): Save On Exit
Pros: Simplifies process flow as the command class no longer has to access both Model and Storage components
Cons: Any system/application crash may cause change password data to be lost

Alternative 2: On Demand Saving
Pros: Changes may persist even through system and application crashes
Cons: May slow down application, although not significantly. Complicates process flow.

3.10. Privacy of fields

The Name, Phone, Email, Address and Remark of a Person contains a boolean isPrivate, which will determine if the field belonging to that person is private or not.

PersonClassDiagramPrivacy

Figure 3.10.1 : Class diagram for a Person, only Name, Phone, Email, Address and Remark contain an isPrivate boolean to indicate if it is private or not

Adding a person with private fields uses the same AddCommand as adding a person with no public fields.
To determine if the field that is added should be set to private, a p is added to the start of the prefix.
Hence, pe/[EMAIL] will set that person’s email to be private, whereas if e/[EMAIL] was used, that person’s email would be public.

These new prefixes can be found in CliSyntax, and AddCommandParser will take data with these prefixes. AddCommandParser will then call the appropriate method in ParserUtil, which will parse the string provided into a new field. Depending on whether or not the field is supposed to be private, ParsetUtil will call the appropriate constructor. Upon obtaining all the fields anc creating a new Person, AddCommandParser will create a new AddCommand to handle the addition of the new Person.

AddPrivateSequenceDiagram

Figure 3.10.2 : Sequence Diagram for adding a Person with private fields

If a field is private, then the toString method will return a string <Private [FIELD]>, where [FIELD] is the name of that field.
This can be seen from the toString method in Name:

@Override
public String toString() {
    if (isPrivate) {
        return "<Private Name>";
    }
    return fullName;
}

Since the information displayed in a person’s card in the UI gets the value of the field through the toString() method, this hides the actual value of the field in the UI.

In addition, if isPrivate is true for Name, clicking on a person’s card in the UI will not trigger a search on Google for that person’s name.

Instead, a NewResultAvailableEvent will be raised by BrowserPanel to inform the user that they are not allowed to search for a person possessing a private Name.

To keep track of whether each field is private or not, XmlAdaptedPerson will have to store the isPrivate value for each field of Person. This is done by adding the following

@XmlElement(required = true)
   private Boolean nameIsPrivate;
@XmlElement(required = true)
   private Boolean phoneIsPrivate;
@XmlElement(required = true)
   private Boolean emailIsPrivate;
@XmlElement(required = true)
   private Boolean addressIsPrivate;
@XmlElement(required = true)
   private Boolean remarkIsPrivate;

Which results in a Person being saved in the xml file in the following format

<persons>
    <name>Alex Yeoh</name>
    <nameIsPrivate>false</nameIsPrivate>
    <phone>87438807</phone>
    <phoneIsPrivate>false</phoneIsPrivate>
    <email>[email protected]</email>
    <emailIsPrivate>false</emailIsPrivate>
    <address>Blk 30 Geylang Street 29, #06-40</address>
    <addressIsPrivate>false</addressIsPrivate>
    <remark>cheerful lad</remark>
    <remarkIsPrivate>false</remarkIsPrivate>
    <tagged>friends</tagged>
</persons>

If an old save file without privacy data is loaded, then the toModelType() method in XmlAdaptedPerson will set isPrivate to be false for each field of Person, to keep the displayed information the same.

ℹ️
If a private field is to be edited by EditCommand, createEditedPerson() in EditCommand will not modify the data of that field, even though EditCommand will create a new CommandResult with a success message.
Hence, a private field will remain private and the value stored by that field will remain the same as it originally was.

This is done through the createEditedPerson method in EditCommand. createEditedPerson sets the boolean areFieldsAllPrivate to initially be true.

As the new instance of each field is being generated, if any field contains a value in the input EditPersonDescriptor and that field was not originally private, areFieldsAllPrivate is set to false.

This can be seen from the following code, which is used for the generation of a new Name object.

private static Name createUpdatedName(ReadOnlyPerson personToEdit, EditPersonDescriptor editPersonDescriptor) {
    Name updatedName;
    if (!personToEdit.getName().isPrivate()) {
        updatedName = editPersonDescriptor.getName().orElse(personToEdit.getName());
        if (editPersonDescriptor.getName().isPresent()) {
            areFieldsAllPrivate = false;
        }
    } else {
        updatedName = personToEdit.getName();
    }
    return updatedName;
}

Upon generation of all the fields, if areFieldsAllPrivate is still true, createEditedPerson will throw an IllegalArgumentException, which will cause EditCommand to throw a CommandException and prevent the command from continuing.

3.10.1. Design Considerations

Aspect: Implementation of isPrivate

Alternative 1 (current choice): Add a boolean to each field class.
Pros: Similar implementation to how the fields are currently being implemented. Privacy settings can be obtained directly from the field class itself.
Cons: Repetitive code. Additional overloaded constructor and methods are needed to set and get the value of isPrivate.

Alternative 2: Store a person’s privacy settings outside of the field classes in an Array or a HashMap in Person.
Pros: Can access and modify the privacy settings of all fields easily.
Cons: The fields themselves do not have any indication of whether or not they are private, and will have to check with the Person the belong to.


Aspect: How to determine if a field for a newly added person should be private.

Alternative 1 (current choice): Add a p to the start of each field’s prefix to signify that that field should be private.
Pros: Can add Person containing any combination of private and public fields in 1 command line.
Cons: Have to modify AddCommand, AddCommandParser, ParserUtil and other classes to detect the new prefix and call a separate constructor when a field is private.

Alternative 2: A Person is added with all field public, a separate command will then have to be used to set the desired fields to be private.
Pros: Easier implementation, do not have to modify AddCommand.
Cons: Requires 2 command lines to create a Person with private fields, which takes more time and is more inconvenient for users.

3.11. Changing of a Person’s Privacy

ChangePrivacyCommand facilitates the setting of an existing person’s field’s privacy. Depending on the user’s input, ChangePrivacyCommand will use each field’s setPrivate() method to set the value of isPrivate.

The sequence diagram for ChangePrivacyCommand is illustrated below.

ChangePrivacySequenceDiagram

Figure 3.11.1 : Sequence Diagram for changing the privacy of a Person’s fields

Upon receiving a String containing the arguments from AddressBookParser, ChangePrivacyCommandParser will create a PersonPrivacySettings object.

Depending on the input, the ChangePrivacyCommandParser will set the privacy values, represented by Booleans, in the PersonPrivacySettings object to be true or false. This is illustrated in the code below, which shows how the privacy of Name is set in PersonPrivacySettings:

private void checkName(ArgumentMultimap argMultimap, PersonPrivacySettings pps) throws ParseException {
    if (argMultimap.getValue(PREFIX_NAME).isPresent()) {
        if (argMultimap.getValue(PREFIX_NAME).toString().equals("Optional[true]")) {
            pps.setNameIsPrivate(true);

        } else if (argMultimap.getValue(PREFIX_NAME).toString().equals("Optional[false]")) {
            pps.setNameIsPrivate(false);
        } else {
            throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
                    ChangePrivacyCommand.MESSAGE_USAGE));
        }
    }
}

ChangePrivacyCommandParser will then create a new ChangePrivacyCommand using the input Index and the PersonPrivacySettings

When ChangePrivacyCommand starts executing, it will create a new Person based on the data of the Person at the specified Index. It will then adjust the privacy values based on the input PersonPrivacySettings. For example, the new Name is created in the code snippet below:

private static Name createNameWithPrivacy(ReadOnlyPerson person, PersonPrivacySettings pps) {
    Name name;
    try {
        if (person.getName().getIsPrivate()) {
            person.getName().setPrivate(false);
            name = new Name(person.getName().toString());
            person.getName().setPrivate(true);
        } else {
            name = new Name(person.getName().toString());
        }
    } catch (IllegalValueException e) {
        throw new AssertionError("Invalid Name");
    }
    if (pps.getNameIsPrivate() != null) {
        name.setPrivate(pps.getNameIsPrivate());
    } else {
        name.setPrivate(person.getName().getIsPrivate());
    }
    return name;
}

Once it is done, it will update the original Person with the newly created Person in Model.

ℹ️
If there are missing fields in the input string, the getter methods in PersonPrivacySettings will return false, but the actual value stored will remain as null. This allows isAnyFieldNonNull to check if the user has input any field at all.

3.11.1. Design Considerations

Aspect: Implementation of changing of a person’s privacy.

Alternative 1 (current choice): Create a separate command to do so.
Pros: It is clear to users and developers that changeprivacy is to modify a person’s privacy while edit changes the actual data if the relevant field is not private.
Cons: Additional command, parser and tests must be created.

Alternative 2: Enhance the functionality of EditCommand.
Pros: Can make use of existing code to aid the implementation.
Cons: Increases the complexity of EditCommand for both users and developers. More ambiguous as to how editing a private field will affect the data.

3.12. Changing the address book’s privacy level

PrivacyLevelCommand allows the user to change the privacy level of Address++, letting users easily reveal data hidden by private fields, or hide persons containing private fields entirely.

The sequence diagram for PrivacyLevelCommand is illustrated below.

PrivacyLevelSequenceDiagram

Figure 3.12.1 : Sequence Diagram for changing the privacy level of the address book

PrivacyLevelCommandParser will accept any integer that is input in the command line, and create a PrivacyLevelCommand that stores the integer, which represents the privacy level to switch to.

Upon execution,PrivacyLevelCommand will first check if the integer falls within the range of the minimum and maximum privacy level. If it does not, a new CommandException is thrown, reminding the user of the valid input levels.

If the integer is within the valid range, PrivacyLevelCommand will update the privacy level of Model. Following that, it will proceed to update the privacy level of each person.

Model, each Person and each field that can be set as private all contain a privacyLevel variable to indicate the current privacy level. This value should remain the same between all of these objects throughout the operation of Address++.

PersonClassDiagramPrivacyLevel

Figure 3.12.2 : Class Diagram of Person, which shows which classes contain an integer to indicate the privacy level

Finally, depending on the privacy level, PrivacyLevelCommand will update the call model.updateFilteredPersonList() with the appropriate predicate.

This process is illustrated in the code snippet below.

public CommandResult execute() throws CommandException {
    requireNonNull(model);
    if (level < MIN_PRIVACY_LEVEL || level > MAX_PRIVACY_LEVEL) {
        throw new CommandException(WRONG_PRIVACY_LEVEL_MESSAGE);
    }
    model.setPrivacyLevel(level);
    for (int i = 0; i < model.getAddressBook().getPersonList().size(); i++) {
        ReadOnlyPerson toReplace = model.getPersonAtIndexFromAddressBook(i);
        Person newPerson = new Person(toReplace);
        newPerson.setPrivacyLevel(level);
        try {
            model.updatePerson(toReplace, newPerson);
        } catch (DuplicatePersonException e) {
            throw new CommandException(MESSAGE_DUPLICATE_PERSON);
        } catch (PersonNotFoundException e) {
            throw new AssertionError("The target person cannot be missing");
        }
    }
    if (level == 3) {
        model.updateFilteredPersonList(new ShowAllPrivacyLevelPredicate());
    } else {
        model.updateFilteredPersonList(Model.PREDICATE_SHOW_ALL_PERSONS);
    }
    return new CommandResult(String.format(CHANGE_PRIVACY_LEVEL_SUCCESS, Integer.toString(level)));
}

3.12.1. Design Considerations

Aspect: Storing of the privacy level

Alternative 1 (current choice): Have each relevant class store a privacy level integer.
Pros: Less coupling, less modification of existing code required.
Cons: Have to modify every relevant object every time PrivacyLevelCommand is called. Runs the risk that an object may accidentally not have its privacy level modified to match the other objects if privacy levels are not properly updated.

Alternative 2: Store the privacy level in the model and have any object that needs to check it query from model.
Pros: Only one integer needs to be modified for the privacy level of the entire address book to change, which also eliminates any possibility that privacy level may be different when used by different objects.
Cons: Increases coupling, classes such as Name will need to have a Model object as one of its variables to access Model. Large scale modification of existing code and tests are necessary.

3.13. Locating a Person on Google Maps

Locating a person’s address allows users to take the address that is stored by a person and search it on Google Maps in the browser.

Upon calling the locate command, LocateCommandParser will parse the input string into an Index, and create a new LocateCommand. Should the arguments be a non-integer, a ParseException will be thrown.
This can be seen from the code snippet below:

 public LocateCommand parse(String args) throws ParseException {
    try {
        Index index = ParserUtil.parseIndex(args);
        return new LocateCommand(index);
    } catch (IllegalValueException ive) {
        throw new ParseException(
                String.format(MESSAGE_INVALID_COMMAND_FORMAT, LocateCommand.MESSAGE_USAGE));
    }
}

Upon execution of LocateCommand, it will search the Model for the Person at the input Index. If the Index is out of range of the list of persons, a CommandException will be thrown.

Otherwise, LocateCommand will post a new BrowserPanelLocateEvent and pass in the Person found to that event. It will then return a CommandResult indicating the success of its execution.

This code for this can be found below:

public CommandResult execute() throws CommandException {

    List<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

    if (targetIndex.getZeroBased() >= lastShownList.size()) {
        throw new CommandException(Messages.MESSAGE_INVALID_PERSON_DISPLAYED_INDEX);
    }

    EventsCenter.getInstance().post(new BrowserPanelLocateEvent(
            model.getFilteredPersonList().get(targetIndex.getZeroBased())));
    return new CommandResult(String.format(MESSAGE_LOCATE_PERSON_SUCCESS, targetIndex.getOneBased()));

}

BrowserPanel will then use handleBrowserPanelLocationEvent to process this newly created event. It will call loadMapsPage, which will check if the Person’s `Address is private or not. If their Address is public, it will launch the browser, showing the Address of that Person on Google Maps. Otherwise, an error message will be printed, as can be seen below:

 private void loadMapsPage(ReadOnlyPerson person) {
    if (person.getAddress().isPrivate()) {
        raise(new NewResultAvailableEvent(PRIVATE_ADDRESS_CANNOT_SEARCH));
    } else {
        loadPage(GOOGLE_MAPS_URL_PREFIX + person.getAddress().toString().replaceAll(" ", "+")
            + GOOGLE_MAPS_URL_SUFFIX);
    }
}

The overall sequence of events is illustrated by the following sequence diagram:

LocateSequenceDiagram

Figure 3.13.1 : Sequence Diagram for Locating a Person’s Address

3.13.1. Design Considerations

Aspect: Implementation of the Google Maps to search for a person’s Address

Alternative 1 (current choice): Create a separate command locate.
Pros: No modification needed for existing commands, which makes it clear the purpose of each command.
Cons: Additional commands will need to be learnt for both developers and users.

Alternative 2: Add the functionality into SelectCommand.
Pros: Expands the utility of SelectCommand beyond performing a Google search on their name.
Cons: Will require significant modification of existing code, and may make it more confusing for users.

3.14. Navigating from one address to another using Google Maps

When the navigate command is entered into the command line, NavigateCommandParse will first reset its internal from, to, fromIndex, toIndex to null. It will then check for the input prefixes and ensure that only one of the prefixes from the group fp/, ft/, and fa/, which we will subsequently call the from prefixes are present. It then does the same with the prefixes from the group tp/, tt/ and ta/, which we will call the to prefixes.

This is done by invoking the checkFrom and checkTo methods as can be seen from the code snippet below. For the example checkFrom, it takes in 3 booleans on whether or not each prefix is present and checks whether or not there is exactly one kind of from prefix. It throws an error if there are no from prefixes or more than one type of from prefixes.

private void checkFrom(ArgumentMultimap argumentMultimap, boolean fromAddress, boolean fromPerson, boolean fromTask)
        throws ParseException {
    if (!(fromAddress || fromPerson || fromTask)) {
        throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, NavigateCommand.MESSAGE_USAGE));
    } else if ((fromAddress && (fromPerson || fromTask)) || (fromPerson && fromTask)) {
        // If 2 or more from prefixes are present
        throw new ParseException(NavigateCommand.MESSAGE_MULTIPLE_FROM_ERROR);
    } else {
        try {
            setArgsForNavigateCommand(argumentMultimap, fromAddress, fromPerson, true);
        } catch (IllegalValueException e) {
            throw new ParseException(e.getMessage(), e);
        }
    }
}

checkFrom calls setArgsForNavigateCommand, which sets the variables in the NavigateCommandParser to the appropriate values depending on whether the address originates from a person, a task or is a manual input by the user.

private void setArgsForNavigateCommand(ArgumentMultimap argumentMultimap, boolean address, boolean person, boolean forFrom) throws IllegalValueException {
    if (address) {
        if (forFrom) {
            from = new Location(ParserUtil.parseLocationFromAddress(
                    argumentMultimap.getValue(PREFIX_NAVIGATE_FROM_ADDRESS)).get().toString());
        } else {
            to = new Location(ParserUtil.parseLocationFromAddress(
                    argumentMultimap.getValue(PREFIX_NAVIGATE_TO_ADDRESS)).get().toString());
        }
    } else if (person) {
        if (forFrom) {
            fromIndex = ParserUtil.parseIndex(argumentMultimap
                    .getValue(PREFIX_NAVIGATE_FROM_PERSON).get());
        } else {
            toIndex = ParserUtil.parseIndex(argumentMultimap
                    .getValue(PREFIX_NAVIGATE_TO_PERSON).get());
        }
    } else {
        if (forFrom) {
            fromIndex = ParserUtil.parseIndex(argumentMultimap
                    .getValue(PREFIX_NAVIGATE_FROM_TASK).get());
        } else {
            toIndex = ParserUtil.parseIndex(argumentMultimap
                    .getValue(PREFIX_NAVIGATE_TO_TASK).get());
        }
    }
}

Finally, NavigateCommandParser will create a new NavigateCommand based on the inputs as set by setArgsForNavigateCommand.

When NavigateCommand is created, it first checks if there are duplicate from or to addresses that are passed into it and throws an error if that is the case.

private void checkDuplicateFromAndToLocation(Location locationFrom, Location locationTo, Index fromIndex, Index toIndex) throws IllegalArgumentException {
    if (locationFrom != null && fromIndex != null) {
        throw new IllegalArgumentException(MESSAGE_MULTIPLE_FROM_ERROR);
    }
    if (locationTo != null && toIndex != null) {
        throw new IllegalArgumentException(MESSAGE_MULTIPLE_TO_ERROR);
    }
}

If it passes this check, NavigateCommand stores fromLocation and toLocation, which are the Locations of any manually added address by the user to navigate from and to respectively. It also stores toIndex and fromIndex, which are the Indexes of the Person or Task to extract the address from as well as toIsTask and fromIsTask, which are booleans that indicate whether toIndex and fromIndex are indexes of Persons or Tasks.

Upon execution of NavigateCommmand, it will first check if it has a non-null fromIndex, if it does, it will create a new Location based on its fromIndex and fromIsTask values using the setLocationByIndex method. Otherwise, it will set the Location to be the Location in locationfrom. This can be seen below:

if (fromIndex != null) {
    try {
        from = setLocationByIndex(fromIndex, fromIsTask);
    } catch (IllegalValueException e) {
        throw new IllegalArgumentException(MESSAGE_PRIVATE_PERSON_ADDRESS_ERROR);
    }
} else {
    from = locationFrom;
}

setLocationByIndex throws CommandException if the target Person or Task does not have a valid Address to extract due to the Address being blank, or it being private.

 private Location setLocationByIndex(Index index, boolean isTask) throws IllegalValueException, CommandException {
    if (isTask) {
        if (model.getFilteredTaskList().get(index.getZeroBased()).getTaskAddress().toString().equals("")) {
            throw new CommandException(String.format(MESSAGE_TASK_HAS_NO_ADDRESS_ERROR, index.getOneBased()));
        } else {
            return new Location(model.getFilteredTaskList().get(index.getZeroBased()).getTaskAddress().toString());
        }
    } else {
        if (model.getFilteredPersonList().get(index.getZeroBased()).getAddress().toString().equals("")) {
            throw new CommandException(String.format(MESSAGE_PERSON_HAS_NO_ADDRESS_ERROR, index.getOneBased()));
        } else if (model.getFilteredPersonList().get(index.getZeroBased()).getAddress().getIsPrivate()) {
            throw new CommandException(String.format(MESSAGE_PRIVATE_PERSON_ADDRESS_ERROR, index.getOneBased()));
        } else {
            return new Location(model.getFilteredPersonList().get(index.getZeroBased())
                    .getAddress().toString());
        }
    }
}

NavigateCommand does the same for the Address to navigate To and posts a new BrowserPanelNavigateEvent, passing in the Location to navigate From and the Location to navigate To.
NavigateCommand will then create a new CommandResult to indicate a successful Command.

BrowserPanel will then get the information from this BrowserPanelNavigateEvent, and load the appropriate Google Maps URL after replacing information such as the Unit Number and extra whitespaces. This has to be done as Google Maps does not function properly with Unit Numbers or spaces in its URL.

private void loadDirectionsPage(String fromLocation, String toLocation) {
    loadPage(GOOGLE_MAPS_DIRECTIONS_PREFIX + "&origin="
            + fromLocation.replaceAll("#(\\w+)\\s*", "").replaceAll(" ", "+")
            .replaceAll("-(\\w+)\\s*", "")
            + "&destination="
            + toLocation.replaceAll("#(\\w+)\\s*", "").replaceAll(" ", "+")
            .replaceAll("-(\\w+)\\s*", "")
            + GOOGLE_MAPS_DIRECTIONS_SUFFIX);
}

The overall sequence of events is illustrated by the following sequence diagram:

NavigateSequenceDiagram

Figure 3.14.1 : Sequence Diagram for Navigating from one Address to another

3.14.1. Design Considerations

Aspect: How to pass the appropriate information to NavigateCommand

Alternative 1 (current choice): Have a constructor that takes in a large number of arguments so that NavigateCommand can correctly identify what kind of Location to post in BrowserPanelNavigateEvent.
Pros: Only 1 constructor needed.
Cons: Additional methods will be needed to properly identify which Location to use for navigation.

Alternative 2: Create many constructors to segregate the different possible scenarios that might happen.
Pros: It is clear what information to use to generate the Locations
Cons: Requires large numbers of constructors to be created, easy for mistakes to occur as Constructors all share the same name but different argument types.

Aspect: How to transfer information of the address from one class to another

Alternative 1 (current choice): Wrap the address in a Location class before posting the BrowserPanelNavigateEvent.
Pros: Only Locations, which indicates that the address is properly parsed, will be passed for the BrowserPanel to read, reducing the possibility of BrowserPanel reading stray unwanted strings as addresses to navigate to and from. The value stored inside each Location cannot be altered once that Location object has been created.
Cons: A new class has to be created and Strings, Addresses and TaskAddresses will need to be converted to Locations first.

Alternative 2: Simply pass on a String containing the address from class to class
Pros: Easy to read and transfer information, lower overhead
Cons: It is easier for stray Strings to pollute the information, and the Strings can be unintentionally modified.

3.15. Opening and Saving of the .xml save file

Both OpenCommand and SaveAsCommand function in a very similar way. When open or save is input by the user, AddressBookParser will create a new OpenCommand or SaveAsCommand.

These two commands will then post a new OpenRequestEvent or a new SaveAsRequestEvent and return a successful CommandResult.

MainWindow will have two methods, HandleOpenRequestEvent and HandleSaveAsRequestEvent that subscribe to the above two events and will call handleOpen and handleSaveAs.

private void handleOpen() throws IOException, DataConversionException {
    // Set extension filter
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
            "XML files (*.xml)", "*.xml");
    fileChooser.getExtensionFilters().add(extFilter);

    // Show open file dialog
    File file = fileChooser.showOpenDialog(primaryStage);
    if (file != null) {
        // Change file path to the opened file
        storage.changeFilePath(file.getPath(), prefs);
        // Reset data in the model to the data from the opened file
        model.resetData(XmlFileStorage.loadDataFromSaveFile(file));
        // Update the UI
        fillInnerParts();
    }
}
private void handleSaveAs() throws IOException {
    // Set extension filter
    FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter(
            "XML files (*.xml)", "*.xml");
    fileChooser.getExtensionFilters().add(extFilter);

    // Show save file dialog
    File file = fileChooser.showSaveDialog(primaryStage);

    if (file != null) {
        // Make sure it has the correct extension
        if (!file.getPath().endsWith(".xml")) {
            file = new File(file.getPath() + ".xml");
        }
        // Change file path to the new save file
        storage.changeFilePath(file.getPath(), prefs);
        // Save the address book data and the user preferences
        storage.saveAddressBook(model.getAddressBook());
        storage.saveUserPrefs(prefs);
        // Update the UI
        fillInnerParts();
    }
}

Both handleOpen and handleSaveAs will create a new FileChooser extension filter that only allows the pop-up window to save files and load files in the .xml format.

Upon successfully selecting a file to load or a location to save as in the pop-up window, both methods will call changefilepath in Storage to the selected file path.

Finally, both commands diverge as handleOpen will call resetData to reset the data using the new save file, while handleSaveAs will call saveAddressBook and saveUserPrefs to save the data. Both methods will finally call fillInnerParts() to refresh the data displayed on the UI.

This process is illustrated using the sequence diagram below:

OpenSequenceDiagram

Figure 3.15.1 : Sequence Diagram for Opening a save file

3.15.1. Design Considerations

Aspect: How does OpenCommand and SaveAsCommand determine the file location to save or load the save file from

Alternative 1 (current choice): Open a FileChooser window, allowing the user to move through their file directory to acquire their save location and to select the name of the save file.
Pros: User friendly, many other applications function similarly when saving and loading. Easier to implement and use as part of the dropdown menu in the User Interface.
Cons: Not entirely command line based.

Alternative 2: Input the file directory and file name to save or load from as part of the command.
Pros: Entirely command line based, may be more preferable for users who prefer using the command line.
Cons: Requires more complex code. Command must check if the file location to save or load from is valid, and that there is a valid file of that name.

3.16. Changing the theme of the address book

The original style of the address book may not be for everyone. ThemeCommand allows users to switch between multiple preset themes.

ThemeCommandParser trims the arguments after the word theme in the command line, removing any whitespaces leading up to and following that word. If the entire String ended up trimmed, then ThemeCommandParser will throw a ParseException. Otherwise, it creates a new ThemeCommand, passing in the trimmed word as seen below:

public ThemeCommand parse(String args) throws ParseException {
    String trimmed = args.trim();
    if (trimmed.isEmpty() || trimmed == null) {
        throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT, ThemeCommand.MESSAGE_USAGE));
    } else {
        return new ThemeCommand(trimmed);
    }
}

When initialising the Address Book, the AddressBook class will create a HashMap<String, String> to store the keys and values of the themes.

private void initialiseStyleMap() {
    styleMap.put("dark", "DarkTheme.css");
    styleMap.put("Dark", "DarkTheme.css");
    styleMap.put("light", "LightTheme.css");
    styleMap.put("Light", "LightTheme.css");
}

The keys correspond to the possible user inputs, such as light or dark, while the values contain the filepath of the .css files, such as DarkTheme.css. This way, users do not need to remember and will not have to know what the .css files are like to use the theme command.

On executing ThemeCommand, it first checks if the input string can be found in the set of keys in the HashMap contained by the AddressBook class. If it cannot be found, or if the value corresponding to the input string is identical to that of the value of the file path of the .css file stored in Model, then a CommandException is thrown, as users cannot change to a non-existent theme, or a theme that is already in use.

If the string is valid, ThemeCommand will post a ChangeThemeRequestEvent and set the theme to the new file path corresponding to the input String in Model. Model will then continue on to set the theme in UserPrefs as well, so that it can be loaded on starting the application.

MainWindow contains a method handleChangeThemeEvent that subscribes to the ChangeThemeRequestEvent. handleChangeThemeEvent calls handlChangeTheme, which first checks if there is an existing theme, if there is, it removes it, then sets adds the new theme through the file path that was passed to it.

public void handleChangeTheme(String theme) {
    if (getRoot().getStylesheets().size() > 1) {
         getRoot().getStylesheets().remove(1);
     }
     getRoot().getStylesheets().add(VIEW_PATH + theme);
 }

After all is done, ThemeCommand returns a CommandResult, indicating the success of the command. The overall execution of ThemeCommand is seen in the following code snippet.

public CommandResult execute() throws CommandException {
    requireNonNull(model);

    String styleSheet;

    if (model.getStyleMap().containsKey(style)) {
        styleSheet = model.getStyleMap().get(style);
    } else {
        throw new CommandException(String.format(MESSAGE_THEME_NOT_AVAILABLE, style));
    }

    if (model.getTheme().equals(styleSheet)) {
        throw new CommandException(String.format(MESSAGE_THEME_IN_USE, style));
    }

    EventsCenter.getInstance().post(new ChangeThemeRequestEvent(styleSheet));
    model.setTheme(styleSheet);
    return new CommandResult(String.format(MESSAGE_THEME_CHANGE_SUCCESS, style));
}

The sequence diagram for the whole process is show below:

ThemeSequenceDiagram

Figure 3.16.1 : Sequence Diagram for Changing Themes

3.16.1. Design Considerations

Aspect: Getting the correct file path to the .css file
Alternative 1 (current choice): Store the file path in a HashMap, where the keys are the possible inputs that the user may type and the values are the actual filepaths
Pros: Easier on the user. They do not need to remember any complicated .css names or file paths, and the input string can be customisable by changing the names of the keys added to the HashMap.
Cons: Slightly more work needed to initialise the HashMap and check if the file paths are valid.
Alternative 2: Change the name of the .css file and file paths such that what the user directly inputs can correspond to the actual .css file.
Pros: A HashMap is no longer needed, instead, the input string just needs to be parsed to be turned into a file path. This makes it easier to add additional .css files, as developers do not have to keep modifying the initialisation of the HashMap
Cons: Less flexibility in naming the file, user may break the code if they realise the input string directly used as part of the file path.

3.17. Add/Delete Tag mechanism

The add/delete tag mechanism is facilitated by personArrayList, which resides inside LogicManager. It supports add/delete tag for all persons in the address book. This command will inherit from UndoableCommand.

The add/delete tag command are executed by AddTagCommand and DeleteTagCommand are parsed through AddTagCommandParser and DeleteTagCommandParser. It is different from edit [INDEX] [TAG] since it allows the user to perform the addition and deletion of tags for multiple people at once. If the user wants to add the t/friends tag for the first 3 persons in the address book, the AddTagCommand (add tag/ 1 2 3 t/friends) will be executed. The same operation will happen for delete tag/ command.

The AddTagCommand goes through all the persons in the address book and add tag to the persons with specific index. The DeleteTagCommand works in a similar way.

The example of how AddTagCommand is working:

/**
 * Adds a tag to the persons in the list from the address book.
 */
public class AddTagCommand extends AddCommand {
    /**
         * Check whether the index within the range then checks whether the specific persons have the tag.
         * If not, add the tag to the person that doesn't have the given tag.
         */
        @Override
        public CommandResult executeUndoableCommand() throws CommandException {

            for (Index targetIndex : targetIndexes) {
                // check whether the index within the range
            }
            for (int i = 0; i < targetIndexes.size(); i++) {
                // check whether all persons have the given tag
            }
            // throw exception for duplicated tag
            return new CommandResult();
        }

Suppose the user enter the add tag/ 1 2 t/friends command. The following sequence diagram shows how the add tag command works:

AddTagSdForLogic

Figure 3.17.1 : Add Tag Sequence Diagram for Logic
The delete tag/ command works the same as add tag/ command with different name only.

ℹ️
If the input index does not exist, the AddTagCommand and DeleteTagCommand will throw an exception.
If the tag to be deleted does not exist, the DeleteTagCommand will throw an exception.
If the tag to be added exists in every target person in the address book, the AddTagCommand will throw an exception.

3.17.1. Design Considerations

Aspect: Implementation of the add tag/ and delete tag/
Alternative 1 (current choice): implement the methods in ModelManager
Pros: Easier to implement. ModelManager includes all the methods and variables.
Cons: Must modify Model also to fit the ModelManager. Beginner may have difficulty to understand the different functions in Model component+

Alternative 2: Implement the addtag and deletetag in AddTagCommand and DeleteTagCommand respectively.
Pros: Easier to understand.
Cons: Repetitive code. Additional overload constructor needs to be implement. The AddTagCommand and DeleteTagCommand will have to update the person list. This violates the Single Responsibility Principle.


Aspect: Implementation of the AddTagCommand and DeleteTagCommand
Alternative 1 (current choice): create new command add tag/ and delete tag/
Pros: Less modification of existing command and parser
Cons: Users have to learn how to use the additional commands

Alternative 2: Modify the existing add and delete command
Pros: Users could use the same commands to achieve different purpose
Cons: Additional override the constructor for the existing command. It might not be easy for the beginner.

3.18. Find Tag mechanism

The find tag mechanism is facilitated by an ArrayList of Tags, which resides inside LogicManager. It supports finding persons by their tags in the address book. This command will not inherit from UndoableCommand.

The find tag/ command is executed by FindTagCommand and is parsed through FindTagCommandParser. After parsing through FindTagCommandParser, it does not goes to the FindTagCommand straightly. The list of tags input will be processed by NameContainsTagsPredicate first. It is similar to the find command since find persons through their names and find persons through their tags are quite similar.

Please take not that although FindTagCommand is similar to FindCommand, there are still some differences. FindTagCommand provides exclusive finding whereas FindCommand does not. It is achieved in the NameContainsTagsPredicate.

This is the example of how NameContainsTagsPredicate is working: Firstly, it will convert a Set of Tag to String.

private String convertTagToString(ReadOnlyPerson person) {
        Set<Tag> personTags = person.getTags();
        StringBuilder allTagNames = new StringBuilder();
        for (Tag tag : personTags) {
            allTagNames.append(tag.getTagName());
            allTagNames.append(" ");
        }
        return allTagNames.toString().trim();
    }

After having a list of string, it will then split strings into two ArrayList. One is for the tags we are looking for and another one is for the tags to be excluded.

/**
     * Update the wantedTag and unwantedTag list
     * @param wantedTag list of tags to be searched
     * @param unwantedTag list of tags to not be searched
     */
    private void updateWantedTagUnwantedTag(List<String> wantedTag, List<String> unwantedTag) {
        for (String everyTag : tags) {
            if (!everyTag.startsWith("/not")) {
                wantedTag.add(everyTag);
            } else {
                unwantedTag.add(everyTag.substring(4));
            }
        }
    }

Lastly, it will return the result according to the user input.
Suppose the user enter find tag/ friends command. The following sequence diagram shows how the find tag command works:

FindTagSequenceDiagram

Figure 3.18.1 : Find Tag Sequence Diagram for Logic

ℹ️
If the input index tags do not exist, the FindTagCommand will give a empty list.

3.18.1. Design Considerations

Aspect: Implementation of the find tag/
Alternative 1 (current choice): implement a new command find tag/
Pros: Easier to implement. find tag/ command will be similar to the find command.
Cons: Must create NameContainsTagsPredicate in model. It does not fully utilize the existing NameContainsKeywordsPredicate.

Alternative 2: Implement the find tag/ in FindCommand.
Pros: Easier for user. They do not have to memorize some many commands.
Cons: The existing FindCommand will not only response for finding persons through names only. This Violates Single Responsibility Principle and Separation of Concerns as FindCommand now needs to do two different things.

3.19. Favourite/Unfavourite Person mechanism

To favourite a person is achieved by FavouriteCommand. It basically changes the value of the favourite status of a Person but there is no specific Favourite field for person.

In this sense, a boolean value needs to be created to store the favourite status of a contact. As AddCommand does not involve favourite, the default favourite status for every newly added Person is false.

The favourite status is a boolean value and it will be set as true through FavouriteCommand. Then, the target person will be updated.

public CommandResult executeUndoableCommand() throws CommandException {

        List<ReadOnlyPerson> lastShownList = model.getFilteredPersonList();

        // throw invalid person index

        // update favourite status
        ReadOnlyPerson personToFavourite = lastShownList.get(targetIndex.getZeroBased());
        Person editedPerson = new Person(personToFavourite.getName(),
                personToFavourite.getPhone(), personToFavourite.getEmail(),
                personToFavourite.getAddress(), true,
                personToFavourite.getRemark(), personToFavourite.getAvatar(),
                personToFavourite.getTags());
        // update target person
        try {
            model.updatePerson(personToFavourite, editedPerson);
        } catch (DuplicatePersonException dpe) {
            // throw exception
        }
        model.updateFilteredPersonList(PREDICATE_SHOW_ALL_PERSONS);

        return new CommandResult(String.format(MESSAGE_FAVOURITE_PERSON_SUCCESS, personToFavourite));
    }

FavouriteCommand takes in an integer as its argument. The command is first being parsed in AddressBookParser to be identified as an instance of FavouriteCommand. Then it is parsed by FavouriteCommandParser to parse the index. Invalid indexes will be handled by throwing an exception. This is how FavouriteCommandParser is implemented:

/**
     * Parses the given {@code String} of arguments in the context of the FavouriteCommand
     * and returns an FavouriteCommand object for execution.
     * @throws ParseException if the user input does not conform the expected format
     */
    public FavouriteCommand parse(String args) throws ParseException {
        try {
            Index index = ParserUtil.parseIndex(args);
            return new FavouriteCommand(index);
        } catch (IllegalValueException ive) {
            throw new ParseException(
                    String.format(MESSAGE_INVALID_COMMAND_FORMAT, FavouriteCommand.MESSAGE_USAGE));
        }
    }

The following sequence diagram shows how a FavouriteCommand is processed:

FavouriteSequenceDiagram

Figure 3.19.1 : Favourite Sequence Diagram for Logic

To indicate that a person has been favoured, PersonCard is modified to contain a favouriteLabel that changes its appearance based on the favourite status of the person. It will first detect the boolean favourite status of the person. If the person is a favourite contact, a heart will be shown. The colours of the border and the background of the label are set to transparent, so that only the background picture, which is a heart, will be shown.

3.19.1. Design Consideration

Aspect: Implementation of favourite
Alternative 1 (current choice): implement a new command favourite.
Pros: Easier to implement. Does not need to modify existing command.
Cons: Must modify Person class to update the person status. The constructor of person has been modified so all the person in the address book must change accordingly.
Alternative 2: Implement the favourite in AddCommand
Pros: Easier for user. They do not have to memorize some many commands.
Cons: Difficult to implement. The favourite status will be treated as an optional field when using AddCommand. In order to change favourite status, EditCommand may be modified which is very troublesome.


Aspect: Store Favourite values
Alternative 1 (current choice): Store it as a Boolean value
Pros: Easier to implement. Does not need to create another class.
Cons: Must modify Model and ModelManager to update the person status.It is also prone to bugs when developers forget to change the ObjectProperty to String in UI classes.

Alternative 2: Add a new Favourite field
Pros: Similar way to store other personal information. It also follows the open-close principle and exercises cohesion, where all matters related to Favourite field is dealt in its own class.
Cons: Difficult to implement. Adding a new field will cause many changes in UI, Logic, Model and Storage. Some test cases will be rewritten.

3.20. 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 : Can continue, but 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

3.21. Configuration

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

4. 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.

4.1. Editing Documentation

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.

4.2. Publishing Documentation

See UsingTravis.adoc to learn how to deploy GitHub Pages using Travis.

4.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

5. Testing

5.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)

5.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

5.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.

6. Dev Ops

6.1. Build Automation

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

6.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.

6.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.

6.4. Managing Dependencies

A project often depends on third-party libraries. For example, Address++ 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: User Stories

Priorities: High (must have) - * * *, Medium (nice to have) - * *, Low (unlikely to have) - *

Priority As a …​ I want to …​ So that I can…​

* * *

new user

see usage instructions

refer to instructions when I forget how to use the App

* * *

user

add a new person

keep track of my contacts

* * *

user

delete a person

remove entries that I no longer need

* * *

user

add a new task

keep track of my tasks and assignments

* * *

user

delete a person

remove entries that I no longer need

* * *

user

have a search function

easily search for the contact I am looking for without browsing through thousands of contacts

* * *

user

have the option to edit my created contacts

make changes to the contacts that I have added

* * *

error-prone user

have the ability to Undo and Redo

automatically undo or redo the changes that I have made

* * *

user with secretive friends

be able to add contacts with incomplete data

operate without the need to create dummy values

* * *

cautious user

be able to lock my address book application whenever I want with a password

prevent people with malicious intent from making changes to my data

* *

user

hide private contact details by default

minimize chance of someone else seeing them by accident

* *

user

load contact data from any file of my choosing

have more flexibility for my file’s storage location

* *

user

save contact data in a directory of my choosing

save the file in a location that fits my needs

* *

user

type commands partially and have the application fill in the rest for me

increase typing productivity

* *

multi-tasking user

be able to record things other than contacts, such as tasks

manage myself better

* *

user

be able to filter my contacts based on tags

view the people who are relevant to me

* *

organized user

be able to sort my contacts by different fields such as by name and birthday

better organize my contacts

* *

user with multiple devices

be able to import and export my address book

use the address book without having to add all my contacts when I switch platforms

* *

user who values privacy

be able to to choose and modify which contacts and what information are to be displayed

hide information I do not want to share from others

* *

cautious user

be able to back up my address book data

retrieve my back up data in the event I make breaking changes to my actual address book and there is no way of undoing them

* *

user with poor eyesight

be able to increase the font size

use the application without straining my eyes

* *

forgetful user

be able to see who is assigned to a task

find my contacts who are in charge more quickly

*

lazy user

have an easy way to add a person with his full details into my address book

add new contacts quickly

*

user who values aesthetics

be able to customize my layout

display self-identity, and use a layout that I like

*

user

have the ability to add a short description to my contacts

add more information about my contacts

*

user

be able to mark my favourite contacts

find them more easily

*

long-time user

be able to access shortcut commands

use the address book more efficiently

*

user

be able to update the address book application easily when new updates are published

continue using the address book easily with any newly added features

Appendix B: 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 a specific person in the list

  4. AddressBook deletes the person

    Use case ends.

Extensions

  • 2a. The list is empty.

    Use case ends.

  • 3a. The given index is invalid.

    • 3a1. AddressBook shows an error message.

      Use case resumes at step 2.

Use case: Search for person

MSS

  1. User requests to search for a person with criteria

  2. AddressBook shows a list of persons who match the criteria

    Use case ends.

Extensions

  • 2a. The list is empty.

    Use case ends.

  • 2b. No such person was found.

    • 2b1. AddressBook informs the user that no matching users were found.

      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 change the details of a specific person in the list

  4. AddressBook changes the details of the specified person.

  5. AddressBook shows the new details of the person.

    Use case ends.

Extensions

  • 2a. The list is empty.

    Use case ends.

  • 3a. The given index is invalid.

    • 3a1. AddressBook shows an error message.

      Use case resumes at step 2.

  • 3b. The specified detail to change is invalid.

    • 3b1. AddressBook shows an error message.

      Use case resumes at step 2.

  • 4a. The specified detail to change is exactly the same as the previous detail.

    • 4a1. AddressBook informs the user that no change was made.

      Use case ends.

Use case: Undo/Redo by multiple steps

MSS

  1. User requests to undo/redo a specified number of steps

  2. AddressBook undos/redos the last X commands, where X was the number of commands to undo/redo

  3. AddressBook displays a success message

  4. AddressBook displays a list of all the commands that were undone/redone.

    Use case ends.

Extensions

  • 2a. The number of commands entered were less than the specified number of undo commands.

    • 2a1. AddressBook undos all previous commands.

      Use case resumes at step 3.

  • 2b. The number of commands entered were less than the specified number of redo commands.

    • 2b1. AddressBook redos all previously undone commands.

      Use case resumes at step 3

Use case: Sort

MSS

  1. User requests to sort by a criteria

  2. AddressBook sorts the contacts by the criteria

  3. AddressBook shows a success message.

    Use case ends.

Extensions

  • 2a. The list is empty.

    Use case ends.

  • 1a. The given criteria is invalid.

    • 1a1. AddressBook shows an error message.

      Use case resumes at step 1.

Appendix C: 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. Feature sets are to be rolled out on a regular weekly basis, following the proper forking workflow procedure.

  5. The application should be intuitive the target users: students (and professionals) who prefer typing over using the mouse.

  6. Future versions of the application should be backwards compatible with data saved in versions after v1.0.

  7. The application is not required to handle physical printing.

Appendix D: Glossary

Mainstream OS

Windows, Linux, Unix, OS-X

Backwards Compatible

In the context of this project, backwards compatible save data refers to the ability for multiple versions of this application to use the same saved data.