Skip to content

Latest commit

 

History

History
1243 lines (901 loc) · 56.6 KB

DeveloperGuide.adoc

File metadata and controls

1243 lines (901 loc) · 56.6 KB

SocialBook - 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 the project 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 se-edu/addressbook-level4 repo. If you plan to develop this as a separate product (i.e. instead of contributing to the se-edu/addressbook-level4) , 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. Styling and Themes

StyleSheetColorNames

Figure 2.2.2 : Important variable names of the Stylesheet

The Stylesheets loaded are mainly controlled with the following global stylesheet variables

* {
    -fx-base-background-color-0: #181b1d;
    -fx-base-background-color-1: #2e3138;
    -fx-base-text-fill-color: white;
    -fx-base-text-fill-color-alt: black;
    -fx-base-text-fill-color-labels: white;
    -fx-label-text-fill-color: #010505;
    -fx-list-cell-even: #3c3e3f;
    -fx-list-cell-odd: #4a4f58;
    -fx-list-cell-selected: #36435f;
    -fx-list-cell-selected-border: #3e7b91;
    -fx-list-cell-empty: #383838;
}

Any new components added to the themes or stylesheets should utilise these base colors or variables to ensure the ease of creation and importation into other themes.

2.4. Default.html

defaultPage

Figure 2.4.1 : Default Landing page of the SocialBook App

The first page that the User sees is the landing page of the application. This landing page resides in the default.html file and the corresponding default theme along with it DarkTheme.css.

This landing page is to present the first time users with some form of feedback when they are first introduced to the application.

Additional Ui help such as arrows and pointers that can be implemented in the HTML with simple CSS stylings will be coming in V2.0.

2.5. DetailedPersonCard and PersonCard

detailedPersonCard

Figure 2.5.1 : Majority of contact information is to be shown in the DetailedPersonCard

personCard

Figure 2.5.2 : Condensed information to be shown in PersonCard

The main design principles used here is to focus on the Social Aspect of the User’s contacts.

In order to do so, the main bulk of the real estate given to the User has to be the Browser.

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

  • stores the UserPerson object that represents the user’s own contact card.

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

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

  • can save UserPerson objects in xml format and read it back.

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

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

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
ℹ️
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
ℹ️
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

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

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

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

UndoRedoActivityDiagram

3.1.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.
Additional Info: See our discussion here.


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.

ModelClassDiagram

The Weblink class creates objects to store social website URL information of each person in the addressBook. The information will be assessed by Web command to display the website in Social Book.

One of the unique aspect of the WebLink class is that weblinks being inputted by the user will automatically be assigned into one of the 4 default categories: Facebook, Instagram, Linkedin and Others. Each weblink objects has a attributed weblinkTag to indicate the category. Also only one weblink will be accepted for each category. For example, if user `add n/jiasheng w/https://www.facebook.com/rand w/https://facebook.com/rand2, this will not be accepted. Only 1 website for each category will be loaded in Social Book.

WebLink

public WebLink(String name) throws IllegalValueException {

        requireNonNull(name);
        this.webLinkInput = name.trim();
        if (!isValidWebLink(webLinkInput)) {
            throw new IllegalValueException(MESSAGE_WEB_LINK_CONSTRAINTS);
        }
        this.webLinkTag = DEFAULT_TAG;

        HashMap<String, String> webLinkTagMap = new WebLinkUtil().getMatchingWebsites();
        Iterator<String> keySetIterator = webLinkTagMap.keySet().iterator();

        while (keySetIterator.hasNext()) {
            String webLinkMatchingRegex = keySetIterator.next();
            if (webLinkInput.matches(webLinkMatchingRegex)) {
                this.webLinkTag = webLinkTagMap.get(webLinkMatchingRegex);
                break;
            }
        }
    }

WebLinkUtil

    /*tag names for the categorized web links*/
    public static final String FACEBOOK_TAG = "facebook";
    public static final String TWITTER_TAG = "twitter";
    public static final String INSTAGRAM_TAG = "instagram";

    /*Keywords that can be used to match website to certain categories. */
    private static final String INSTAGRAM_MATCH_REGEX = "(?i)^^.*(instagram.com|instagram|insta).*$";
    private static final String FACEBOOK_MATCH_REGEX = "(?i)^^.*(facebook.com|fb.com/|facebook).*$";
    private static final String TWITTER_MATCH_REGEX = "(?i)^^.*(twitter.com|t.co|twitter).*$";

    private HashMap<String, String> matchingWebsites = new HashMap<>();


    public WebLinkUtil() {
        matchingWebsites.put(FACEBOOK_MATCH_REGEX, FACEBOOK_TAG);
        matchingWebsites.put(INSTAGRAM_MATCH_REGEX, INSTAGRAM_TAG);
        matchingWebsites.put(TWITTER_MATCH_REGEX, TWITTER_TAG);
    }

    public HashMap<String, String> getMatchingWebsites() {
        return matchingWebsites;
    }

In the while loop, if the webLink input matches a regex in the Hashmap MatchingWebsites in WebLinkUtil, the "tag" that matches the regex key will be assigned to this.webLinkTag. For example, if the link matches INSTAGRAM_MATCH_REGEX, INSTAGRAM_TAG will be retrieved from the MatchingWebsites and assigned to WebLinkTag.

ParserUtil

   public static Set<WebLink> parseWebLink(Collection<String> webLinks) throws IllegalValueException {
        requireNonNull(webLinks);
        final Set<WebLink> webLinkSet = new HashSet<>();
        for (String inputWebLinkString : webLinks) {
            if (checkRepeatedWebLinkInCategory(webLinkSet, inputWebLinkString)) {
                webLinkSet.add(new WebLink(inputWebLinkString));
            } else {
                throw new IllegalValueException("Only one link per category: facebook ,"
                        + "instagram or twitter");
            }
        }
        return webLinkSet;
    }

    /**
     * Checks whether webLinkSet to be passed contains weblinks from the same category.
     */
    public static boolean checkRepeatedWebLinkInCategory (Set<WebLink> webLinkSet, String inputWebLinkString)
            throws IllegalValueException {
        boolean duplicateCheck = TRUE;
        WebLink inputWebLink = new WebLink(inputWebLinkString);
        String inputWebLinkTag = inputWebLink.toStringWebLinkTag();
        if (webLinkSet.isEmpty()) {
            return duplicateCheck;
        } else {

            for (Iterator<WebLink> iterateInternalList = webLinkSet.iterator(); iterateInternalList.hasNext(); ) {
                WebLink webLinkForChecking = iterateInternalList.next();
                String webLinkTagForChecking = webLinkForChecking.toStringWebLinkTag();
                if (inputWebLinkTag.equals(webLinkTagForChecking)) {
                    duplicateCheck = FALSE;
                    break;
                }
            }
            return duplicateCheck;
        }
    }

The constraint of allowing one WebLink per category allowed is implemented in the method checkRepeatedWebLinkInCategory. If this boolean method returns false, parseWebLink will throw an IllegalValueException. In the CheckRepeatedWebLinkCategory, a WebLink object will be created using the parameter inputWebLinkString, and the webLinkTag of the object will be check against the webLinkTag of the given webLinkSet.

3.2.2. Design consideration

Aspect: Matching of tags to different URLs in when creating WebLink object Alternative: An alternative to using the current regex HashMap implementation is to simply list out the String constants in WeblinkUtil class, the matching will be done through the String API contains at the WebLink Class.
Justification: However, the current implementation was kept. Firstly, regex offers more flexibility and control over what kind of URL we want to match to each website category, compared to contains String API. In addition, with the HashMap implementation, if new category were to be added, only WebLinkUtil needs to be updated. With the alternative implementation, WebLink class and possibly ParserUtil CheckRepeatedWebLinkInCategory method will need to be updated as well. This can be very messy and prone to bugs.

3.2.3. Future Implementation

Can consider creating a master UniqueWebLinkList in Address Class. List class can be enhanced to create a complied list of all websites to the user that is tracked by this master UniqueWebLinkList.

The web selection commmand mechanism is executed with the use of a WebsiteSelectionRequestEvent, which resides inside commons.events.ui. This allows for the event to be handled by the UI component required.

WebsiteSelectionEvent

As you can see from the diagram, the link between the Logic and the Ui exists in the EventsCenter. Other commands that utilise this mechanism includes Select.

This mechanism allows for the addition of other Ui components, such as buttons or tabs to replace the trigger event.

3.3.1. Design Considerations

Aspect: Implementation of URL loadings
Alternative 1 (current choice): Implement URL loadings within the BrowserPanel
Pros: We will not have a separation of classes, or the need to update any data values within any dynamically generated objects. BrowserPanel handles all URLs, URL parsings, and had the necessary information to process or execute these commands.
Cons: BrowserPanel has to be pre-loaded with website URLs, if not the Websites within the Person class has to be a full URL

The button bar implemented within the UI is operated by the use of an event trigger ButtonSelectionPressedEvent, which resides inside the commons classes. The actual implementation of the web page loading is done within the BrowserPanel class.

The buttons residing within the button bar raises ButtonSelectionPressedEvent that parses its own button FX.id to the BrowserPanel, which then triggers the internal functions that calls the URL to be loaded.

UiClassDiagram

As you can see from the diagram, WebsiteButtonBar resides within the MainWindow, despite not having any interactions with the BrowserPanel directly.

Suppose that the user has just launched the application. The BrowserPanel will not be loaded.

Once the User selects a person from the PersonListPanel, which is a PersonCard, the SelectedPerson is updated through the use of an event trigger. The BrowserPanel then stores this SelectedPerson until it is updated through listening for the event trigger.

Residing in BrowserPanel, the available social WebLinks are loaded and dynamically created. Supposed a person does not have any social links, only a simple google search and address search button will be displayed as a result.

The User then clicks on a button within the WebsiteButtonBar. The buttons that exist within the ButtonBar is dynamically created through the list of websites that exists within the Person object coming in v1.3.

ℹ️
If a button is pressed before the selection of a PersonCard, the event trigger would simply load a default page.

3.4.1. Design Considerations

Aspect: Implementation of URL loadings
Alternative 1 (current choice): Implement URL loadings within the BrowserPanel via event handlers
Pros: We will not have a seperation of classes, or the need to update any data values within any dynamically generated objects. BrowserPanel handles all URLs, URL parsings, and had the necessary information to process or execute these commands.
Alternative 2: Create different BrowserPanel s for each new Website
Pros: Swaps each Panel using tabs and allows for various design elements to be made for each URL loaded
Cons: Increases the number of Tabs to be created with each person website, and increases the complexities at the UI level.

3.5. Sort Command

The SortCommand modifies the listing in the AddressBook data. It will permanently sort the list of contacts by the filterType indicated, which has to be one of the following: Name, Email, Phone, Address or Default. The default sorting will sort the list by name. + The command parameters are 'sort FILTERTYPE'. Simply entering 'sort' will set FILTERTYPE to default. Aliases are available for each of the sorting methods for convenience. The aliases are simply the first letter in each filter.

The Sort Command will first remember the current filteredList’s predicate, call the method sortFilteredList in the model’s AddressBook, modify the PersonList via the sort method in UniquePersonList, then indicate that the AddressBook has been changed, which then calls a method that saves the data locally. The old predicate is reapplied to the new filteredList. Thus, the list is permanently modified and overwritten. The original list is lost permanently, unless it is one of the other sorted lists, whereby the Sort Command can be used to obtain the required list again by passing in the relevant filter as a parameter.

The sort method implementation is displayed below. A switch case excerpt is used to determine the type of comparison that the anonymously declared comparator will use to order 2 persons. If more types of filters are desired, they simply have to be added to the list of cases below. Default currenlty sorts by name as there is no way to sort by the original listing, which is date added.

    public void sortPersons(String filterType) {

        Comparator<ReadOnlyPerson> personComparator = (ReadOnlyPerson person1,
                                                   ReadOnlyPerson person2) -> {

            String arg1;
            String arg2;
            switch (filterType) {
            case ARG_NAME:
                arg1 = person1.getName().toString().toLowerCase();
                arg2 = person2.getName().toString().toLowerCase();
                break;
            case ARG_PHONE:
                arg1 = person1.getPhone().toString();
                arg2 = person2.getPhone().toString();
                break;
            case ARG_EMAIL:
                arg1 = person1.getEmail().toString();
                arg2 = person2.getEmail().toString();
                break;
            case ARG_ADDRESS:
                arg1 = person1.getAddress().toString();
                arg2 = person2.getAddress().toString();
                break;
            default:
                arg1 = person1.getName().toString();
                arg2 = person2.getName().toString();
                break;
            }
            return arg1.compareTo(arg2);
        };

        FXCollections.sort(internalList, personComparator);
    }

Sorting by name will display the list with names in ascending alphabetical order, regardless of capitalisation.
Sorting by phone will display the list with phone numbers in ascending order.
Sorting by email will display the list with emails in ascending alphabetical order, with priority given to the first email entered for a person. This means that the primary email for a person should be entered first.
Sorting by address will display the list with addresses in ascending alphabetical order.
Sorting by default will do the same as sorting by name currently.

3.5.1. Design Considerations

Aspect: Implementation of sorting.
Alternative 1 (current choice): Modify list internally and permanently.
Pros: Easier to implement, allows for greater flexibility as the internal list can be modified.
Cons: Unable to re-obtain original list of persons, which is sorted by date added, without changing Person.
Alternative 2: Modify displayed list, only for visual purposes.
Pros: Able to preserve original listing of date added.
Cons: Unable to implement without massive changes as Model’s filteredPersonList is immutable and thus cannot be sorted easily.

3.5.2. Design Considerations

Aspect: Sort Command vs List Command
Pros: A user might only want to enter sort once, but does not want to have to enter the entire command again to obtain the same listing. Thus, Sort Command will sort the list while List Command will redisplay the last sorted list.
Cons: Multiple commands might confuse the user.

3.5.3. Design Considerations

Aspect: Display entire list vs Display filtered list
Current choice: Display filtered list Pros: Good for those who want to see the filtered list sorted. Gives list command more value.
Cons: Extra code to remember previous predicate.

3.5.4. Design Considerations

Aspect: FilterType aliases
Pros: Greater flexibility and convenience for the user
Cons: Extra code and variables to maintain

3.5.5. Further enhancements

Sorting by date added by adding a "date added" attribute to each person in the address book.
Sorting in descending order.

3.6. AddressBook and UserProfile Storage

The AddressBook and UserProfile data is stored in data/AddressBook.xml and data/UserProfile.x ml. The AddressBook converts all Persons, Tags and WebLinks into XML format, which is then saved to the xml file. Upon initialising the app, the AddressBook will read the xml file and convert it back to Persons, Tags and Weblink respectively before setting the data.

Similarly for UserProfile, the UserPerson is stored as an XMLAdaptedPerson, saved as an xml file and then retrived upon initialisation of the app. Whenever the UserPerson is edited using the Update Command, the userProfile is saved to the file.

A UserProfile Window was added as a UI Component to display the User Profile information. Additionally, the User Profile can be modified from the textfields in the UI directly. The UserProfile is only saved when "OK" is clicked. Invalid values will be detected and changes will not be saved. The "Enter" key is added as an accelerator for the OK button and the "Escape" key is added as an accelerator for the cancel button. The UserProfile can be found under "File" -→ "User Profile" and has an accelerator key "F2".

UserProfileWindow
UserProfileWindowInvalidEntry

3.6.1. Design Considerations

Aspect: Choice of location for storing UserProfile Data
Alternative 1 (current choice): Separately from AddressBook.
Justification: This path was chosen taking into consideration the two following cases: A User can have multiple AddressBooks, or multiple users can share one AddressBook.
In the former case, the User would not have to modify his UserProfile for each AddressBook.
In the latter case, an AddressBook should not be tied to only one UserPerson in particular.
Pros: Greater flexibility, portability
Cons: More code and java classes to maintain, changes the structure of Model to support multiple variables.
Alternative 2: Together with AddressBook
Pros: Easier to manage, with only one Storage file and fewer classes to maintain
Cons: Reduced flexibility as now, both AddressBook data and UserProfile cannot be separated

3.6.2. Further enhancements

+ Modify settings and userPrefs in the UserProfile

3.7. Find Command and Filter Command

The find and filter command controls the person panels to be displayed to the user by modifying the filteredPerson FilteredList in model. The find and filter command will updated filteredPerson by calling the updateFilterPersonList to change the predicate. The main enhancement done is to allow find and filter command to be able to match keywords with all the attributes of a Person object (Name, Phone, Address, Email, Tag & WebLink) instead of just Name for find command and Tag for filter command(Our team’s initial implementation).

3.7.1. Find Command

Find command displays the a list of person in the address book with attributes that matches any of the keywords entered by the user. Find command creates a new ContainKeywordsPredicate object to be be used a parameter for the updateFilterPersonList method.

public class ContainsKeywordsPredicate implements Predicate<ReadOnlyPerson> {
    private final List<String> keywords;

    public ContainsKeywordsPredicate(List<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public boolean test(ReadOnlyPerson person) {
        return (containsKeyWordInName(person) || containsKeyWordInAddress(person)
                || containsKeyWordInPhone(person) || containsKeyWordInTag(person)
                || containsKeyWordInWebLink(person) || containsKeyWordInEmail(person));
    }

    private boolean containsKeyWordInName(ReadOnlyPerson person) {
        return keywords.stream().anyMatch(keyword
            -> StringUtil.containsWordIgnoreCase(person.getName().fullName, keyword));
    }

    private boolean containsKeyWordInPhone(ReadOnlyPerson person) {
        return keywords.stream().anyMatch(keyword
            -> StringUtil.containsWordIgnoreCase(person.getPhone().value, keyword));
    }

    private boolean containsKeyWordInAddress(ReadOnlyPerson person) {
        return keywords.stream().anyMatch(keyword
            -> StringUtil.containsWordIgnoreCase(person.getAddress().value, keyword));
    }

    private boolean containsKeyWordInTag(ReadOnlyPerson person) {
        return person.getTags().stream().anyMatch(s -> keywords.stream()
                .anyMatch(keyword -> StringUtil.containsWordIgnoreCase(s.toStringFilter(), keyword)));
    }

    private boolean containsKeyWordInWebLink(ReadOnlyPerson person) {
        return person.getWebLinks().stream().anyMatch(s -> keywords.stream()
                .anyMatch(keyword -> StringUtil.containsWordIgnoreCase(s.toStringWebLink(), keyword)));
    }

    private boolean containsKeyWordInEmail(ReadOnlyPerson person) {
        return person.getEmail().stream().anyMatch(s -> keywords.stream()
                .anyMatch(keyword -> StringUtil.containsWordIgnoreCase(s.toString(), keyword)));
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof ContainsKeywordsPredicate // instanceof handles nulls
                && this.keywords.equals(((ContainsKeywordsPredicate) other).keywords)); // state check
    }

}

There are 6 boolean methods to check whether any of the given keywords is contained in each of a Person’s attributed, using Java Stream API anyMatch. The test method will return true for the ReadOnlyperson if either of these methods return true, indicating that at least one keyword matches with one of the 6 attributes.

3.7.2. Filter Command

Filter command displays the a list of person in the address book with attributes that matches all of the keywords entered by the user, just like an actual filter function we find on certain websites. Filter Command’s implementation is fairly similar to Find. Main difference is that a FilterKeywordsPredicate predicate object is created instead.

    public FilterKeywordsPredicate(List<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public boolean test(ReadOnlyPerson person) {

        String combinedReferenceList = person.getAsOneString();

        return !keywords.isEmpty() && keywords.stream().allMatch(keyword
            -> StringUtil.containsWordIgnoreCase(combinedReferenceList, keyword) && !keyword.contains("[")
                && !keyword.contains("]"));

Below is the getAsOneString method implementation in the ReadOnlyPerson API that is being called by the test method in FilterKeywordsPredicate.

default String getAsOneString() {
        final StringBuilder builder = new StringBuilder();
        builder.append(getName())
                .append(" ")
                .append(getPhone())
                .append(" ")
                .append(getEmail())
                .append(" ")
                .append(getAddress())
                .append(" ")
                .append(getRemark())
                .append(" ");
        getTags().forEach(builder::append);
        builder.append(" ");
        getWebLinks().forEach(builder::append);
        return builder.toString();
    }

getAsOneString method appends all the attributes into one complete string delimited by space. In test method in FilterKeywordsPredicate, test method uses the Java Stream API allMatch to ensure that all combinedReferenceList contains all the keywords entered by the user. The keyword.contains("[")&& !keyword.contains("]") portion in the test method is to catch for instances when user enters "[" or "]". This is because toString method in Tag, WebLink and email being called by StringBuilder in getAsOneString method contains a bracket by default.

3.7.3. Design Consideration

Aspect1: Cleaner implementation for ContainKeywordsPredicate? Why have 6 boolean methods for ContainKeywordsPredicate?
Alternative: For the test method, use GetAsOneString() method for part 1 as well, with anyMatch Java Stream API.
Justification: However, the current implementation was kept, as it opens possibility for future enhancements, suchs as Find n/ or Find e/ to search in specific attributes. The separate boolean methods for each attribute in ContainKeywordsPredicate allows for easier implementation.

Aspect2: A flexible search approach Alternative: Find & Filter command’s current implementation uses a more flexible search approach. It means that if the keyword is a substring in the string of the attribute that is checked, it is considered a match. For example, Pan will match with Pang.

StringUtil

    public static boolean containsWordIgnoreCase(String sentence, String word) {
        requireNonNull(sentence);
        requireNonNull(word);

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

        for (String wordInSentence : wordsInPreppedSentence) {
            if (wordInSentence.toLowerCase().contains(preppedWord.toLowerCase())) {
                return true;
            }
        }
        return false;

The alternative implementation would be to replace contains with a more constraining check (Example. equals() implementation) in the containsWordIgnorecase method.
Justification: However, from a UX perspective, a more flexible search method will be more useful for a user, for example when the user searches Gwen to find a person called Gwendolyn.

3.7.4. Future enhancements

Find Command is able to search under specific attributes with prefix. Example, Find e/ to search under email.

3.8. tagDelete

The tagDelete command allows users to delete a Tag from all person in the addressbook that has the Tag.

Implementation for DeleteTag method in Model API

    public void deleteTag(Tag tag) throws PersonNotFoundException, DuplicatePersonException {
        Boolean checkTagExistence = false;

        for (int i = 0; i < addressBook.getPersonList().size(); i++) {
            ReadOnlyPerson oldPerson = addressBook.getPersonList().get(i);
            Person newPerson = new Person(oldPerson);
            Set<Tag> newTags = newPerson.getTags();
            if (newTags.contains(tag)) {
                checkTagExistence = true;
            }
            newTags.remove(tag);
            newPerson.setTags(newTags);

            addressBook.updatePerson(oldPerson, newPerson);
        }

        if (!checkTagExistence) {
            throw new ParserException("Tag does not exist.");
        }
    }

DeleteTag Command implements Undoable command. It overrides the execute method and calls on the DeleteTag method in Model API to execute the command. DeleteTag method iterates through the ObservableList of ReadOnlyPerson and checks whether it contains tag in the method parameter. if checkTagExistence boolean is false, deleteTag will throw ParserException to indicate that the tag does not exist.

3.8.1. Future Enhancement

deleteTag can be extended to other attributes of a person as well. For example, a method can be implemented to iterate through all the address of the person in the address book, and delete every that stays in a certain location.

3.9. 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.10. 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 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: 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

* * *

user

delete a person

remove entries that I no longer need

* * *

user

find a person by name

locate details of persons without having to go through the entire list

* * *

user

find a person by phone number or email

locate details of person without knowing their name

* * *

user

add a multiple phone numbers to a person

* * *

user

add a multiple email addresss to a person

* * *

user

see the Social Media links of a contact in the browser

see the latest updates of the person

* * *

user

share contacts with other people

easily share contact information

* * *

user

have my own contact on the addressbook

see how my information is displayed

* * *

user

display contacts with either First or Last name first

* * *

user

add todo tasks to the front page of the app

see a list of tasks to do

* *

user

share my default contact with another person

friend does not need to enter the entire add command manually

* *

user

hide private contact details by default

minimize chance of someone else seeing them by accident

* *

user with many persons in the address book

list persons as favourites

see most important contacts at a glance

* *

user

assign a todo task to a contact

remember a task that is associated to a person

* *

user

filter todo list by contacts

see the list of actions to take associated to the person

*

user with many persons in the address book

sort persons by name

locate a person easily

*

user with many persons in the address book

create custom lists of persons

see a group of pre-defined persons

{More to be added}

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: Batch-add person

MSS

  1. User requests to batch-add persons

  2. AddressBook asks for a file or command to add

  3. AddressBook adds all persons added

  4. AddressBook lists all new persons added

    Use case ends.

Extensions

  • 2a. User requests to upload file

    • 2a1. AddressBook requests .csv file location

    • 2a2. User uploads .csv file

      Use case resumes at step 3.

  • 2b. User requests to input command

    • 2b1. User inputs multiple persons details

      Use case resumes at step 3.

Use case: Share Contact

MSS

  1. User requests to list persons

  2. AddressBook shows a list of persons

  3. User requests to share a specific person in the list

  4. AddressBook generates add command for the person in a new window

  5. User copies generated command

  6. User closes window

    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.

{More to be added}

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. A user should open the application with the previous entries in a addressbook pre-loaded.

  5. Should not experience visible lag or delays when running any command within the addressbook.

  6. Should display a pleasing image when working in offline mode.

  7. Regardless of the availability of internet access, the core functionality should not be affected.

{More to be added}

Appendix D: Glossary

Mainstream OS

Windows, Linux, Unix, OS-X

Private contact detail

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

Contact List

A list that displays contacts that were added to it, a contact can exist on multiple lists

User Person

A contact that is persistent to you. A self-contact such that you can see how you look like in the addressbook of others

Contact History

Past interactions made with the contact person (e.g. email on 01-10-2017, CS2103 Updates)

Appendix E: Product Survey

Product Name

Author: …​

Pros:

  • …​

  • …​

Cons:

  • …​

  • …​