CS2113/T Jan '19
  • Week 1 [Jan 14]
  • Week 2 [Jan 21]
  • Week 3 [Jan 28]
  • Week 4 [Feb 4]
  • Week 5 [Feb 11]
  • Week 6 [Feb 18]
  • Week 7 [Mar 4]
  • Week 8 [Mar 11]
  • Week 9 [Mar 18]
  • Week 10 [Mar 25]
  • Week 11 [Apr 1]
  • Week 12 [Apr 8]
  • Week 13 [Apr 15]
  • Textbook
  • Admin Info
  • Report Bugs
  • Slack
  • Forum
  • Project Info
  • Instructors
  • Announcements
  • File Submissions
  • Tutorial Schedule
  • Java Coding Standard
  • samplerepo-things
  • Addressbook-level1
  • Addressbook-level2
  • Addressbook-level3
  • Addressbook-level4
  • Projects List
  • config.json templates for Reposense
  • Project Code Dashboard (BETA)
  • Repl.it classroom
  • Previous WeekNext Week

    Week 6 [Feb 18]

    Graded coding exercise

    • This week you need to make an enhancement to Addressbook-Level3; this can earn you 3 participation points.

    • Though the deadline is Week 7 before the tutorial, you are strongly encouraged to finish this soon, so that you have enough time to work on the project.

    • Refer to the project tab for more details.

    💹 Project progress

    • To get you up to speed to work with AB-4, we recommend you to play around with the AB-3 code base (i.e., fork, clone, setup, and enhance) before moving to AB-4. You can practice with AB-3 while at the the same time updating docs of AB-4 as required by the next project milestone.

    • At this point of the project there are several non-trivial tools you need to learn e.g., JavaFX, Gradle, Travis, Java 8 features, Git, etc. We recommend that you divide up the learning tasks among team members and plan to learn them gradually over the next few weeks.

    • Be reminded that your performance in meeting individual/team project milestones (as detected by our scripts and observed by tutors) will be counted towards your project grade under the project management component. Please do follow exact setup instructions because deviations will affect our script's ability to detect your work.

    Using AB-3?

    • If you choose to use AB-3 for your project, be informed that there will be no disadvantage in terms of marks (i.e., you will not be penalized for starting from AB-3).

    • However some points to take note:

      • Some of the project infrastructure that is readily available in AB-4 will not be available in AB-3. You need to set it up yourself.
      • Adding features/commands available in AB-4 but not in AB-3 alone to your project does not earn credits.

    💰 Participation points

    After reaching 15 participation points:

    • We encourage you to continue to do module activities (irrespective of whether they have participation points) because every time you skip a module activity, it can potentially make the remainder of the module a harder for you to follow, due to the highly-connect and iterative nature of this module.

    🆘 Seeking help

    If you need help

    • Do inform your tutor (or write to the module email) if you are falling behind or cannot cope with the module requirements. While we try to avoid hand holding or spoon feeding students, we do want to help you keep up with the module pace when necessary.

    • If you encounter any technical difficulties when setting up AB-4, please post in our forum so that AB-4 developers can follow up with you. Unlike in first year programming modules, there is no guarantee that tutors will know solutions to your technical problems -- it is not reasonable to even expect so. But you can increase your chances of a solution if you post in the forum as soon as you encounter them. Also, see Admin » Appendix D: Getting Help in this Module

    Tutorials

    • Tutorials this week will be most effective if you work out the tutorial questions beforehand. You can discuss your answers with your team and your tutor during the tutorial.

    [W6.1] Continuous Integration/Deployment

    [W6.1a] Implementation → Integration → Introduction → What

    Can explain integration

    Combining parts of a software product to form a whole is called integration. It is also one of the most troublesome tasks and it rarely goes smoothly.

    [W6.1b] Implementation → Integration → Build Automation → What

    Can explain build automation tools

    Build automation tools automate the steps of the build process, usually by means of build scripts.

    In a non-trivial project, building a product from source code can be a complex multi-step process.  For example, it can include steps such as to pull code from the revision control system, compile, link, run automated tests, automatically update release documents (e.g. build number), package into a distributable, push to repo, deploy to a server, delete temporary files created during building/testing, email developers of the new build, and so on. Furthermore, this build process can be done ‘on demand’, it can be scheduled (e.g. every day at midnight) or it can be triggered by various events (e.g. triggered by a code push to the revision control system).

    Some of these build steps such as to compile, link and package are already automated in most modern IDEs.  For example, several steps happen automatically when the ‘build’ button of the IDE is clicked. Some IDEs even allow customization to this build process to some extent.

    However, most big projects use specialized build tools to automate complex build processes.

    Some popular build tools relevant to Java developers:

    Some other build tools : Grunt (JavaScript), Rake (Ruby)

    Some build tools also serve as dependency management tools. Modern software projects often depend on third party libraries that evolve constantly. That means developers need to download the correct version of the required libraries and update them regularly. Therefore, dependency management is an important part of build automation. Dependency Management tools can automate that aspect of a project.

    Maven and Gradle, in addition to managing the build process, can play the role of dependency management tools too.

    Gradle_is used used for,

    • a. better revision control
    • b. build automation
    • c. UML diagramming
    • d. project collaboration

    (b)

    [W6.1c] Implementation → Integration → Build Automation → Continuous Integration and Continuous Deployment

    Can explain continuous integration and continuous deployment

    An extreme application of build automation is called continuous integration (CI) in which integration, building, and testing happens automatically after each code change.

    A natural extension of CI is Continuous Deployment (CD) where the changes are not only integrated continuously, but also deployed to end-users at the same time.

    Some examples of CI/CD tools:

    [W6.2] CodeQuality


    Readability

    [W6.2a] Implementation → Code Quality → Readability → Introduction

    Can explain the importance of readability

    Programs should be written and polished until they acquire publication quality. --Niklaus Wirth

    Among various dimensions of code quality, such as run-time efficiency, security, and robustness, one of the most important is understandability. This is because in any non-trivial software project, code needs to be read, understood, and modified by other developers later on. Even if we do not intend to pass the code to someone else, code quality is still important because we all become 'strangers' to our own code someday.

    The two code samples given below achieve the same functionality, but one is easier to read.

         

    Bad

    int subsidy() {
        int subsidy;
        if (!age) {
            if (!sub) {
                if (!notFullTime) {
                    subsidy = 500;
                } else {
                    subsidy = 250;
                }
            } else {
                subsidy = 250;
            }
        } else {
            subsidy = -1;
        }
        return subsidy;
    }
    

      

    Good

    int calculateSubsidy() {
        int subsidy;
        if (isSenior) {
            subsidy = REJECT_SENIOR;
        } else if (isAlreadySubsidised) {
            subsidy = SUBSIDISED_SUBSIDY;
        } else if (isPartTime) {
            subsidy = FULLTIME_SUBSIDY * RATIO;
        } else {
            subsidy = FULLTIME_SUBSIDY;
        }
        return subsidy;
    }
    

         

    Bad

    def calculate_subs():
        if not age:
            if not sub:
                if not not_fulltime:
                    subsidy = 500
                else:
                    subsidy = 250
            else:
                subsidy = 250
        else:
            subsidy = -1
        return subsidy
    

      

    Good

    def calculate_subsidy():
        if is_senior:
            return REJECT_SENIOR
        elif is_already_subsidised:
            return SUBSIDISED_SUBSIDY
        elif is_parttime:
            return FULLTIME_SUBSIDY * RATIO
        else:
            return FULLTIME_SUBSIDY
    

    [W6.2b] Implementation → Code Quality → Readability → Basic → Avoid Long Methods

    Can improve code quality using technique: avoid long methods

    Be wary when a method is longer than the computer screen, and take corrective action when it goes beyond 30 LOC (lines of code). The bigger the haystack, the harder it is to find a needle.

    [W6.2c] Implementation → Code Quality → Readability → Basic → Avoid Deep Nesting

    Can improve code quality using technique: avoid deep nesting

    If you need more than 3 levels of indentation, you're screwed anyway, and should fix your program. --Linux 1.3.53 CodingStyle

    In particular, avoid arrowhead style code.

    Example:

    [W6.2d] Implementation → Code Quality → Readability → Basic → Avoid Complicated Expressions

    Can improve code quality using technique: avoid complicated expressions

    Avoid complicated expressions, especially those having many negations and nested parentheses. If you must evaluate complicated expressions, have it done in steps (i.e. calculate some intermediate values first and use them to calculate the final value).

    Example:

    Bad

    return ((length < MAX_LENGTH) || (previousSize != length)) && (typeCode == URGENT);
    

    Good

    
    boolean isWithinSizeLimit = length < MAX_LENGTH;
    boolean isSameSize = previousSize != length;
    boolean isValidCode = isWithinSizeLimit || isSameSize;
    
    boolean isUrgent = typeCode == URGENT;
    
    return isValidCode && isUrgent;
    

    Example:

    Bad

    return ((length < MAX_LENGTH) or (previous_size != length)) and (type_code == URGENT)
    

    Good

    is_within_size_limit = length < MAX_LENGTH
    is_same_size = previous_size != length
    is_valid_code = is_within_size_limit or is_same_size
    
    is_urgent = type_code == URGENT
    
    return is_valid_code and is_urgent
    

    The competent programmer is fully aware of the strictly limited size of his own skull; therefore he approaches the programming task in full humility, and among other things he avoids clever tricks like the plague. -- Edsger Dijkstra

    [W6.2e] Implementation → Code Quality → Readability → Basic → Avoid Magic Numbers

    Can improve code quality using technique: avoid magic numbers

    When the code has a number that does not explain the meaning of the number, we call that a magic number (as in “the number appears as if by magic”). Using a named constant makes the code easier to understand because the name tells us more about the meaning of the number.

    Example:

         

    Bad

    return 3.14236;
    ...
    return 9;
    

      

    Good

    static final double PI = 3.14236;
    static final int MAX_SIZE = 10;
    ...
    return PI;
    ...
    return MAX_SIZE-1;
    

    Note: Python does not have a way to make a variable a constant. However, you can use a normal variable with an ALL_CAPS name to simulate a constant.

         

    Bad

    return 3.14236
    ...
    return 9
    

      

    Good

    PI = 3.14236
    MAX_SIZE = 10
    ...
    return PI
    ...
    return MAX_SIZE-1
    

    Similarly, we can have ‘magic’ values of other data types.

    Bad

    "Error 1432"  // A magic string!
    
    [W6.2f] Implementation → Code Quality → Readability → Basic → Make the Code Obvious

    Can improve code quality using technique: make the code obvious

    Make the code as explicit as possible, even if the language syntax allows them to be implicit. Here are some examples:

    • [Java] Use explicit type conversion instead of implicit type conversion.
    • [Java, Python] Use parentheses/braces to show grouping even when they can be skipped.
    • [Java, Python] Use enumerations when a certain variable can take only a small number of finite values. For example, instead of declaring the variable 'state' as an integer and using values 0,1,2 to denote the states 'starting', 'enabled', and 'disabled' respectively, declare 'state' as type SystemState and define an enumeration SystemState that has values 'STARTING', 'ENABLED', and 'DISABLED'.
    [W6.2g] Implementation → Code Quality → Readability → Intermediate → Structure Code Logically

    Can improve code quality using technique: structure code logically

    Lay out the code so that it adheres to the logical structure. The code should read like a story. Just like we use section breaks, chapters and paragraphs to organize a story, use classes, methods, indentation and line spacing in your code to group related segments of the code. For example, you can use blank lines to group related statements together. Sometimes, the correctness of your code does not depend on the order in which you perform certain intermediary steps. Nevertheless, this order may affect the clarity of the story you are trying to tell. Choose the order that makes the story most readable.

    [W6.2h] Implementation → Code Quality → Readability → Intermediate → Do Not 'Trip Up' Reader

    Can improve code quality using technique: do not 'trip up' reader

    Avoid things that would make the reader go ‘huh?’, such as,

    • unused parameters in the method signature
    • similar things look different
    • different things that look similar
    • multiple statements in the same line
    • data flow anomalies such as, pre-assigning values to variables and modifying it without any use of the pre-assigned value
    [W6.2i] Implementation → Code Quality → Readability → Intermediate → Practice KISSing

    Can improve code quality using technique: practice kissing

    As the old adage goes, "keep it simple, stupid” (KISS). Do not try to write ‘clever’ code. For example, do not dismiss the brute-force yet simple solution in favor of a complicated one because of some ‘supposed benefits’ such as 'better reusability' unless you have a strong justification.

    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan

    Programs must be written for people to read, and only incidentally for machines to execute. --Abelson and Sussman

    [W6.2j] Implementation → Code Quality → Readability → Intermediate → Avoid Premature Optimizations

    Can improve code quality using technique: avoid premature optimizations

    Optimizing code prematurely has several drawbacks:

    • We may not know which parts are the real performance bottlenecks. This is especially the case when the code undergoes transformations (e.g. compiling, minifying, transpiling, etc.) before it becomes an executable. Ideally, you should use a profiler tool to identify the actual bottlenecks of the code first, and optimize only those parts.
    • Optimizing can complicate the code, affecting correctness and understandability
    • Hand-optimized code can be harder for the compiler to optimize (the simpler the code, the easier for the compiler to optimize it). In many cases a compiler can do a better job of optimizing the runtime code if you don't get in the way by trying to hand-optimize the source code.

    A popular saying in the industry is make it work, make it right, make it fast which means in most cases getting the code to perform correctly should take priority over optimizing it. If the code doesn't work correctly, it has no value on matter how fast/efficient it it.

    Premature optimization is the root of all evil in programming. --Donald Knuth

    Note that there are cases where optimizing takes priority over other things e.g. when writing code for resource-constrained environments. This guideline simply a caution that you should optimize only when it is really needed.

    [W6.2k] Implementation → Code Quality → Readability → Intermediate → SLAP Hard

    Can improve code quality using technique: SLAP hard

    Avoid varying the level of abstraction within a code fragment. Note: The Productive Programmer (by Neal Ford) calls this the SLAP principle i.e. Single Level of Abstraction Per method.

    Example:

    Bad

    readData();
    salary = basic*rise+1000;
    tax = (taxable?salary*0.07:0);
    displayResult();
    

    Good

    readData();
    processData();
    displayResult();
    
     

    Design → Design Fundamentals → Abstraction →

    What

    Abstraction is a technique for dealing with complexity. It works by establishing a level of complexity we are interested in, and suppressing the more complex details below that level.

    The guiding principle of abstraction is that only details that are relevant to the current perspective or the task at hand needs to be considered. As most programs are written to solve complex problems involving large amounts of intricate details, it is impossible to deal with all these details at the same time. That is where abstraction can help.

    Ignoring lower level data items and thinking in terms of bigger entities is called data abstraction.

    Within a certain software component, we might deal with a user data type, while ignoring the details contained in the user data item such as name, and date of birth. These details have been ‘abstracted away’ as they do not affect the task of that software component.

    Control abstraction abstracts away details of the actual control flow to focus on tasks at a simplified level.

    print(“Hello”) is an abstraction of the actual output mechanism within the computer.

    Abstraction can be applied repeatedly to obtain progressively higher levels of abstractions.

    An example of different levels of data abstraction: a File is a data item that is at a higher level than an array and an array is at a higher level than a bit.

    An example of different levels of control abstraction: execute(Game) is at a higher level than print(Char) which is at a higher than an Assembly language instruction MOV.

    Abstraction is a general concept that is not limited to just data or control abstractions.

    Some more general examples of abstraction:

    • An OOP class is an abstraction over related data and behaviors.
    • An architecture is a higher-level abstraction of the design of a software.
    • Models (e.g., UML models) are abstractions of some aspect of reality.
    [W6.2l] Implementation → Code Quality → Readability → Advanced → Make the Happy Path Prominent

    Can improve code quality using technique: make the happy path prominent

    The happy path (i.e. the execution path taken when everything goes well) should be clear and prominent in your code. Restructure the code to make the happy path unindented as much as possible. It is the ‘unusual’ cases that should be indented. Someone reading the code should not get distracted by alternative paths taken when error conditions happen. One technique that could help in this regard is the use of guard clauses.

    Example:

    Bad

    if (!isUnusualCase) {  //detecting an unusual condition
        if (!isErrorCase) {
            start();    //main path
            process();
            cleanup();
            exit();
        } else {
            handleError();
        }
    } else {
        handleUnusualCase(); //handling that unusual condition
    }
    

    In the code above,

    • Unusual condition detection is separated from their handling.
    • Main path is nested deeply.

    Good

    if (isUnusualCase) { //Guard Clause
        handleUnusualCase();
        return;
    }
    
    if (isErrorCase) { //Guard Clause
        handleError();
        return;
    }
    
    start();
    process();
    cleanup();
    exit();
    

    In contrast, the above code

    • deals with unusual conditions as soon as they are detected so that the reader doesn't have to remember them for long.
    • keeps the main path un-indented.

    Naming

    [W6.2m] Implementation → Code Quality → Naming → Introduction

    Can explain the need for good names in code

    Proper naming improves the readability. It also reduces bugs caused by ambiguities regarding the intent of a variable or a method.

    There are only two hard things in Computer Science: cache invalidation and naming things. -- Phil Karlton

    [W6.2n] Implementation → Code Quality → Naming → Basic → Use Nouns for Things and Verbs for Actions

    Can improve code quality using technique: use nouns for things and verbs for actions

    Every system is built from a domain-specific language designed by the programmers to describe that system. Functions are the verbs of that language, and classes are the nouns. ― Robert C. Martin, Clean Code: A Handbook of Agile Software Craftsmanship

    Use nouns for classes/variables and verbs for methods/functions.

    Examples:

    Name for a Bad Good
    Class CheckLimit LimitChecker
    method result() calculate()

    Distinguish clearly between single-valued and multivalued variables.

    Examples:

    Good

    Person student;
    ArrayList<Person> students;
    

    Good

    student = Person('Jim')
    students = [Person('Jim'), Person('Alice')]
    
    [W6.2o] Implementation → Code Quality → Naming → Basic → Use Standard Words

    Can improve code quality using technique: use standard words

    Use correct spelling in names. Avoid 'texting-style' spelling. Avoid foreign language words, slang, and names that are only meaningful within specific contexts/times e.g. terms from private jokes, a TV show currently popular in your country

    [W6.2p] Implementation → Code Quality → Naming → Intermediate → Use Name to Explain

    Can improve code quality using technique: use name to explain

    A name is not just for differentiation; it should explain the named entity to the reader accurately and at a sufficient level of detail.

    Examples:

    Bad Good
    processInput() (what 'process'?) removeWhiteSpaceFromInput()
    flag isValidInput
    temp

    If the name has multiple words, they should be in a sensible order.

    Examples:

    Bad Good
    bySizeOrder() orderBySize()

    Imagine going to the doctor's and saying "My eye1 is swollen"! Don’t use numbers or case to distinguish names.

    Examples:

    Bad Bad Good
    value1, value2 value, Value originalValue, finalValue
    [W6.2undefined] Implementation → Code Quality → Naming → Intermediate → Not Too Long, Not Too Short

    Can improve code quality using technique: not too long, not too short

    While it is preferable not to have lengthy names, names that are 'too short' are even worse. If you must abbreviate or use acronyms, do it consistently. Explain their full meaning at an obvious location.

    [W6.2undefined] Implementation → Code Quality → Naming → Intermediate → Avoid Misleading Names

    Can improve code quality using technique: avoid misleading names

    Related things should be named similarly, while unrelated things should NOT.

    Example: Consider these variables

    • colorBlack : hex value for color black
    • colorWhite : hex value for color white
    • colorBlue : number of times blue is used
    • hexForRed : : hex value for color red

    This is misleading because colorBlue is named similar to colorWhite and colorBlack but has a different purpose while hexForRed is named differently but has very similar purpose to the first two variables. The following is better:

    • hexForBlack hexForWhite hexForRed
    • blueColorCount

    Avoid misleading or ambiguous names (e.g. those with multiple meanings), similar sounding names, hard-to-pronounce ones (e.g. avoid ambiguities like "is that a lowercase L, capital I or number 1?", or "is that number 0 or letter O?"), almost similar names.

    Examples:

    Bad Good Reason
    phase0 phaseZero Is that zero or letter O?
    rwrLgtDirn rowerLegitDirection Hard to pronounce
    right left wrong rightDirection leftDirection wrongResponse right is for 'correct' or 'opposite of 'left'?
    redBooks readBooks redColorBooks booksRead red and read (past tense) sounds the same
    FiletMignon egg If the requirement is just a name of a food, egg is a much easier to type/say choice than FiletMignon

    Unsafe Practices

    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Introduction

    Can explain the need for avoiding error-prone shortcuts

    It is safer to use language constructs in the way they are meant to be used, even if the language allows shortcuts. Some such coding practices are common sources of bugs. Know them and avoid them.

    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Basic → Use the Default Branch

    Can improve code quality using technique: use the default branch

    Always include a default branch in case statements.

    Furthermore, use it for the intended default action and not just to execute the last option. If there is no default action, you can use the 'default' branch to detect errors (i.e. if execution reached the default branch, throw an exception). This also applies to the final else of an if-else construct. That is, the final else should mean 'everything else', and not the final option. Do not use else when an if condition can be explicitly specified, unless there is absolutely no other possibility.

    Bad

    if (red) print "red";
    else print "blue";
    

    Good

    if (red) print "red";
    else if (blue) print "blue";
    else error("incorrect input");
    
    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Basic → Don't Recycle Variables or Parameters

    Can improve code quality using technique: don't recycle variables or parameters

    • Use one variable for one purpose. Do not reuse a variable for a different purpose other than its intended one, just because the data type is the same.
    • Do not reuse formal parameters as local variables inside the method.

    Bad

    double computeRectangleArea(double length, double width) {
        length = length * width;
        return length;
    }
    
    

    Good

    double computeRectangleArea(double length, double width) {
        double area;
        area = length * width;
        return area;
    }
    
    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Basic → Avoid Empty Catch Blocks

    Can improve code quality using technique: avoid empty catch blocks

    Never write an empty catch statement. At least give a comment to explain why the catch block is left empty.

    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Basic → Delete Dead Code

    Can improve code quality using technique: delete dead code

    We all feel reluctant to delete code we have painstakingly written, even if we have no use for that code any more ("I spent a lot of time writing that code; what if we need it again?"). Consider all code as baggage you have to carry; get rid of unused code the moment it becomes redundant. If you need that code again, simply recover it from the revision control tool you are using. Deleting code you wrote previously is a sign that you are improving.

    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Intermediate → Minimise Scope of Variables

    Can improve code quality using technique: minimise scope of variables

    Minimize global variables. Global variables may be the most convenient way to pass information around, but they do create implicit links between code segments that use the global variable. Avoid them as much as possible.

    Define variables in the least possible scope. For example, if the variable is used only within the if block of the conditional statement, it should be declared inside that if block.

    The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. -- Effective Java, by Joshua Bloch

    Resources:

    [W6.2undefined] Implementation → Code Quality → Error-Prone Practices → Intermediate → Minimise Code Duplication

    Can improve code quality using technique: minimise code duplication

    Code duplication, especially when you copy-paste-modify code, often indicates a poor quality implementation. While it may not be possible to have zero duplication, always think twice before duplicating code; most often there is a better alternative.

    This guideline is closely related to the DRY Principle.

    Supplmentary → Principles →

    DRY Principle

    DRY (Don't Repeat Yourself) Principle: Every piece of knowledge must have a single, unambiguous, authoritative representation within a system The Pragmatic Programmer, by Andy Hunt and Dave Thomas

    This principle guards against duplication of information.

    The functionality implemented twice is a violation of the DRY principle even if the two implementations are different.

    The value a system-wide timeout being defined in multiple places is a violation of DRY.


    Code Comments

    [W6.2undefined] Implementation → Code Quality → Comments → Introduction

    Can explain the need for commenting minimally but sufficiently

    Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’ Improve the code and then document it to make it even clearer. --Steve McConnell, Author of Clean Code

    Some think commenting heavily increases the 'code quality'. This is not so. Avoid writing comments to explain bad code. Improve the code to make it self-explanatory.

    [W6.2undefined] Implementation → Code Quality → Comments → Basic → Do Not Repeat the Obvious

    Can improve code quality using technique: do not repeat the obvious

    If the code is self-explanatory, refrain from repeating the description in a comment just for the sake of 'good documentation'.

    Bad

    // increment x
    x++;
    
    //trim the input
    trimInput();
    
    [W6.2undefined] Implementation → Code Quality → Comments → Basic → Write to the Reader

    Can improve code quality using technique: write to the reader

    Do not write comments as if they are private notes to self. Instead, write them well enough to be understood by another programmer. One type of comments that is almost always useful is the header comment that you write for a class or an operation to explain its purpose.

    Examples:

    Bad Reason: this comment will only make sense to the person who wrote it

    // a quick trim function used to fix bug I detected overnight
    void trimInput(){
        ....
    }
    

    Good

    /** Trims the input of leading and trailing spaces */
    void trimInput(){
        ....
    }
    

    Bad Reason: this comment will only make sense to the person who wrote it

    # a quick trim function used to fix bug I detected overnight
    def trim_input():
        ...
    

    Good

    def trim_input():
    """Trim the input of leading and trailing spaces"""
        ...
    
    [W6.2undefined] Implementation → Code Quality → Comments → Intermediate → Explain WHAT and WHY, not HOW

    Can improve code quality using technique: explain what and why, not how

    Comments should explain what and why aspect of the code, rather than the how aspect.

    What : The specification of what the code supposed to do. The reader can compare such comments to the implementation to verify if the implementation is correct

    Example: This method is possibly buggy because the implementation does not seem to match the comment. In this case the comment could help the reader to detect the bug.

    /** Removes all spaces from the {@code input} */
    void compact(String input){
        input.trim();
    }
    

    Why : The rationale for the current implementation.

    Example: Without this comment, the reader will not know the reason for calling this method.

    // Remove spaces to comply with IE23.5 formatting rules
    compact(input);
    

    How : The explanation for how the code works. This should already be apparent from the code, if the code is self-explanatory. Adding comments to explain the same thing is redundant.

    Example:

    Bad Reason: Comment explains how the code works.

    // return true if both left end and right end are correct or the size has not incremented
    return (left && right) || (input.size() == size);
    

    Good Reason: Code refactored to be self-explanatory. Comment no longer needed.

    
    boolean isSameSize = (input.size() == size) ;
    return (isLeftEndCorrect && isRightEndCorrect) || isSameSize;
    

    [W6.3] Design: Models

    [W6.3a] Design → Modelling → Introduction → What

    Can explain models

    A model is a representation of something else.

    A class diagram is a model that represents a software design.

    A class diagram is a diagram drawn using the UML modelling notation.
    An example class diagram:

    A model provides a simpler view of a complex entity because a model captures only a selected aspect. This omission of some aspects implies models are abstractions.

     

    Design → Design Fundamentals → Abstraction →

    What

    Abstraction is a technique for dealing with complexity. It works by establishing a level of complexity we are interested in, and suppressing the more complex details below that level.

    The guiding principle of abstraction is that only details that are relevant to the current perspective or the task at hand needs to be considered. As most programs are written to solve complex problems involving large amounts of intricate details, it is impossible to deal with all these details at the same time. That is where abstraction can help.

    Ignoring lower level data items and thinking in terms of bigger entities is called data abstraction.

    Within a certain software component, we might deal with a user data type, while ignoring the details contained in the user data item such as name, and date of birth. These details have been ‘abstracted away’ as they do not affect the task of that software component.

    Control abstraction abstracts away details of the actual control flow to focus on tasks at a simplified level.

    print(“Hello”) is an abstraction of the actual output mechanism within the computer.

    Abstraction can be applied repeatedly to obtain progressively higher levels of abstractions.

    An example of different levels of data abstraction: a File is a data item that is at a higher level than an array and an array is at a higher level than a bit.

    An example of different levels of control abstraction: execute(Game) is at a higher level than print(Char) which is at a higher than an Assembly language instruction MOV.

    Abstraction is a general concept that is not limited to just data or control abstractions.

    Some more general examples of abstraction:

    • An OOP class is an abstraction over related data and behaviors.
    • An architecture is a higher-level abstraction of the design of a software.
    • Models (e.g., UML models) are abstractions of some aspect of reality.

    A class diagram captures the structure of the software design but not the behavior.

    Multiple models of the same entity may be needed to capture it fully.

    In addition to a class diagram (or even multiple class diagrams), a number of other diagrams may be needed to capture various interesting aspects of the software.

    [W6.3b] Design → Modelling → Introduction → How

    Can explain how models are used

    In software development, models are useful in several ways:

    a) To analyze a complex entity related to software development.

    Some examples of using models for analysis:

    1. Models of the problem domain (i.e. the environment in which the software is expected to solve a problem) can be built to aid the understanding of the problem to be solved.
    2. When planning a software solution, models can be created to figure out how the solution is to be built. An architecture diagram is such a model.

    b) To communicate information among stakeholders. Models can be used as a visual aid in discussions and documentations.

    Some examples of using models to communicate:

    1. We can use an architecture diagram to explain the high-level design of the software to developers.
    2. A business analyst can use a use case diagram to explain to the customer the functionality of the system.
    3. A class diagram can be reverse-engineered from code so as to help explain the design of a component to a new developer.

    An architecture diagram depicts the high-level design of a software.

    c) As a blueprint for creating software. Models can be used as instructions for building software.

    Some examples of using models to as blueprints:

    1. A senior developer draws a class diagram to propose a design for an OOP software and passes it to a junior programmer to implement.
    2. A software tool allows users to draw UML models using its interface and the tool automatically generates the code based on the model.
    Model Driven Development tangential

    Model-driven development (MDD), also called Model-driven engineering, is an approach to software development that strives to exploit models as blueprints. MDD uses models as primary engineering artifacts when developing software. That is, the system is first created in the form of models. After that, the models are converted to code using code-generation techniques (usually, automated or semi-automated, but can even involve manual translation from model to code). MDD requires the use of a very expressive modeling notation (graphical or otherwise), often specific to a given problem domain. It also requires sophisticated tools to generate code from models and maintain the link between models and the code. One advantage of MDD is that the same model can be used to create software for different platforms and different languages. MDD has a lot of promise, but it is still an emerging technology

    Further reading:

    Choose the correct statements about models.

    • a. Models are abstractions.
    • b. Models can be used for communication.
    • c. Models can be used for analysis of a problem.
    • d. Generating models from code is useless.
    • e. Models can be used as blueprints for generating code.

    (a) (b) (c) (e)

    Explanation: Models generated from code can be used for understanding, analysing, and communicating about the code.

    Explain how models (e.g. UML diagrams) can be used in a class project.

    Can models be useful in evaluating the design quality of a software written by students?

    [W6.4] UML: Class/Ojbect Diagrams - Basics

    [W6.4a] Design → Modelling → Modelling Structure OO Structures

    Can explain structure modelling of OO solutions

    An OO solution is basically a network of objects interacting with each other. Therefore, it is useful to be able to model how the relevant objects are 'networked' together inside a software  i.e. how the objects are connected together.

    Given below is an illustration of some objects and how they are connected together.  Note: the diagram uses an ad-hoc notation.

    Note that these object structures within the same software can change over time.

    Given below is how the object structure in the previous example could have looked like at a different time.

    However, object structures do not change at random; they change based on a set of rules, as was decided by the designer of that software. Those rules that object structures need to follow can be illustrated as a class structure  i.e. a structure that exists among the relevant classes.

    Here is a class structure (drawn using an ad-hoc notation) that matches the object structures given in the previous two examples. For example, note how this class structure does not allow any connection between Genre objects and Author objects, a rule followed by the two object structures above.

    UML Object Diagrams are used to model object structures and UML Class Diagrams are used to model class structures of an OO solution.

    Here is an object diagram for the above example:

    And here is the class diagram for it:

    [W6.4b] Design → Modelling → Modelling Structure Class Diagrams (Basics)

    Can use basic-level class diagrams

    Classes form the basis of class diagrams.

    Associations are the main connections among the classes in a class diagram.

    The most basic class diagram is a bunch of classes with some solid lines among them to represent associations, such as this one.

    An example class diagram showing associations between classes.

    In addition, associations can show additional decorations such as association labels, association roles, multiplicity and navigability to add more information to a class diagram.

    Here is the same class diagram shown earlier but with some additional information included:

    Which association notatations are shown in this diagram?

    • a. association labels
    • b. association roles
    • c. association multiplicity
    • d. class names

    (a) (b) (c) (d)

    Explanation: '1’ is a multiplicity, ‘mentored by’ is a label, and ‘mentor’ is a role.

    Explain the associations, navigabilities, and multiplicities in the class diagram below:

    Draw a class diagram for the code below. Show the attributes, methods, associations, navigabilities, and multiplicities in the class diagram below:

    class Box {
        private Item[] parts = new Item[10];
        private Item spareItem;
        private Lid lid; // lid of this box
        private Box outerBox;
    
        public void open(){
            //...
        }
    }
    
    class Item {
        public static int totalItems;
    }
    
    class Lid {
        Box box; // the box for which this is the lid
    }
    
    [W6.4c] Design → Modelling → Modelling Structure Object Diagrams

    Can use basic object diagrams

    Object diagrams can be used to complement class diagrams. For example, you can use object diagrams to model different object structures that can result from a design represented by a given class diagram.

    This question is based on the following question from another topic:

    Draw a class diagram for the code below. Show the attributes, methods, associations, navigabilities, and multiplicities in the class diagram below:

    class Box {
        private Item[] parts = new Item[10];
        private Item spareItem;
        private Lid lid; // lid of this box
        private Box outerBox;
    
        public void open(){
            //...
        }
    }
    
    class Item {
        public static int totalItems;
    }
    
    class Lid {
        Box box; // the box for which this is the lid
    }
    

    Draw an object diagram to match the code. Include objects of all three classes in your object diagram.

    [W6.4d] Tools → UML → Object vs Class Diagrams

    Can distinguish between class diagrams and object diagrams

    Compared to the notation for a class diagrams, object diagrams differ in the following ways:

    • Shows objects instead of classes:
      • Instance name may be shown
      • There is a : before the class name
      • Instance and class names are underlined
    • Methods are omitted
    • Multiplicities are omitted

    Furthermore, multiple object diagrams can correspond to a single class diagram.

    Both object diagrams are derived from the same class diagram shown earlier. In other words, each of these object diagrams shows ‘an instance of’ the same class diagram.

    Which of these class diagrams match the given object diagram?

    • a
    • b

    (a) (b)

    Explanation: Both class diagrams allow one Unit object to be linked to one Item object.

    [W6.5] UML: Class Diagrams - Intermediate

    [W6.5a] Tools → UML → Notes

    Can use UML notes

    UML notes can augment UML diagrams with additional information. These notes can be shown connected to a particular element in the diagram or can be shown without a connection. The diagram below shows examples of both.

    Example:

    [W6.5b] Tools → UML → Constraints

    Can specify constraints in UML diagrams

    A constraint can be given inside a note, within curly braces. Natural language or a formal notation such as OCL (Object Constraint Language) may be used to specify constraints.

    Example:

    [W6.5c] Tools → UML → Class Diagrams → Associations as Attributes

    Can show an association as an attribute

    An association can be shown as an attribute instead of a line.

    Association multiplicities and the default value too can be shown as part of the attribute using the following notation. Both are optional.

    name: type [multiplicity] = default value

    The diagram below depicts a multi-player Square Game being played on a board comprising of 100 squares. Each of the squares may be occupied with any number of pieces, each belonging to a certain player.

    A Piece may or may not be on a Square. Note how that association can be replaced by an isOn attribute of the Piece class. The isOn attribute can either be null or hold a reference to a Square object, matching the 0..1 multiplicity of the association it replaces. The default value is null.

    The association that a Board has 100 Sqaures can be shown in either of these two ways:

    [W6.5d] Design → Modelling → Modelling Structure Class Diagrams - Intermediate

    Can use intermediate-level class diagrams

    A class diagram can also show different types of associations: inheritance, compositions, aggregations, dependencies.

    Modeling inheritance

    Modeling composition

    Modeling aggregation

    Modeling dependencies

    A class diagram can also show different types of class-like entities:

    Modeling enumerations

    Modeling abstract classes

    Modeling interfaces

    Which of these statements match the class diagram?

    • a. A Snake must belong to at least one Board.
    • b. A SnakeHeadSquare can contain only one Snake head.
    • c. A Square can contain a Snake head.
    • d. A Snake head can be in more than one SnakeHeadSquare
    • e. The Board has exactly 5 Snakes.

    (a)(b)(c)(d)(e)

    Explanation:

    (a) does not match because a Snake may or may not belong to a Board (multiplicity is 0..1)
    (b) matches the diagram because the multiplicity given in 1
    (c) matches the diagram because SnakeHeadSquare is a Square (due to inheritance)
    (d) matches the diagram because the multiplicity given is *
    (e) matches the diagram because the multiplicity given in 5

    Explain the meaning of various class diagram notations in the following class diagram:

    Consider the code below:

    public interface Billable {
        void bill();
    }
    
    public abstract class Item
             implements Billable {
        public abstract void print();
    }
    
    public class StockItem extends Item {
        private Review review;
        private String name;
    
        public StockItem(
            String name, Rating rating){
    
            this.name = name;
            this.review = new Review(rating);
        }
    
        @Override
        public void print() {
            //...
        }
    
        @Override
        public void bill() {
            //...
        }
    }
    
    public enum Rating {
        GOOD, OK, POOR
    }
    
    public class Review {
        private final Rating rating;
    
        public Review(Rating rating) {
            this.rating = rating;
        }
    }
    
    import java.util.List;
    
    public class Inventory {
        private List<Item> items;
    
        public int getItemCount(){
            return items.size();
        }
    
        public void generateBill(Billable b){
            // ...
        }
    
        public void add(Item s) {
            items.add(s);
        }
    }
    

    (a) Draw a class diagram to represent the code
    (b) Draw an object diagram to represent the situation where the inventory has one item with a name spanner and a review of POOR rating.

    Project Preparation: 3 KLoC

    To get up to speed working with AB-4 (~10KLoc), we recommend that you play around with [AddressBook - Level3] for a bit before moving to AB-4. As before, fork, clone, set up project in your Computer, and try to do a small enhancement to AB-3.

    Suggested exercise

    • add a new command to AB-3 or enhance an existing feature in AB-3
    • update the User Guide to reflect your enhancement
    • add new Unit tests for your enhancement and update existing tests if necessary

    How AB-3 differs from AB-2:

    • A simple GUI has been added to replace the Text UI.
    • No more I/O tests
    • A Logic class has been added together with a LogicTest class.

    Grading

    This coding exercise can earn you three participation points.

    Deadline

    Complete this exercise before Week 7 tutorial to earn participation points.

    Project Milestone: mid-v1.1

    Set up project repo, start moving UG and DG to the repo, attempt to do local-impact changes to the code base.

    Project Management:

    Set up the team org and the team repo as explained below:

    Relevant: [Admin Appendix E(extract): Organization setup ]

     

    Organization setup

    Please follow the organization/repo name format precisely because we use scripts to download your code or else our scripts will not be able to detect your work.

    After receiving your team ID, one team member should do the following steps:

    • Create a GitHub organization with the following details:
      • Organization name : CS2113-AY1819S2-TEAM_ID. e.g.  CS2113-AY1819S2-M11-1
      • Plan:  Open Source ($0/month)
    • Add members to the organization:
      • Create a team called developers to your organization.
      • Add your team members to the developers team.

    Relevant: [Admin Appendix E(extract): Repo setup ]

     

    Repo setup

    Only one team member:

    1. Fork either Address Book Level 3 or Address Book Level 4 to your team org.
    2. Rename the forked repo as main. This repo (let's call it the team repo) is to be used as the repo for your project.
    3. Ensure the issue tracker of your team repo is enabled. Reason: our bots will be posting your weekly progress reports on the issue tracker of your team repo.
    4. Ensure your team members have the desired level of access to your team repo.
    5. Enable Travis CI for the team repo.
    6. Set up auto-publishing of docs. When set up correctly, your project website should be available via the URL https://nus-cs2113-ay1819s2-{team-id}.github.io/main e.g., https://cs2113-ay1819s2-w13-1.github.io/main/. This also requires you to enable the GitHub Pages feature of your team repo and configure it to serve the website from the gh-pages branch.
    7. create a team PR for us to track your project progress: i.e., create a PR from your team repo master branch to [nuscs2113-AY1819S2/addressbook-level4] master branch. PR name: [Team ID] Product Name e.g., [T09-2] Contact List Pro.  As you merge code to your team repo's master branch, this PR will auto-update to reflect how much your team's product has progressed. In the PR description @mention the other team members so that they get notified when the tutor adds comments to the PR.

    All team members:

    1. Watchthe main repo (created above) i.e., go to the repo and click on the watch button to subscribe to activities of the repo
    2. Fork the main repo to your personal GitHub account.
    3. Clone the fork to your Computer.
    4. Recommended: Set it up as an Intellij project (follow the instructions in the Developer Guide carefully).
    5. Set up the developer environment in your computer. You are recommended to use JDK 9 for AB-4 as some of the libraries used in AB-4 have not updated to support Java 10 yet. JDK 9 can be downloaded from the Java Archive.

    Note that some of our download scripts depend on the following folder paths. Please do not alter those paths in your project.

    • /src/main
    • /src/test
    • /docs
    1. Note: If you fork from Address Book Level 3, ensure that the folder structure is similar to the one in Address Book Level 4

    When updating code in the repo, follow the workflow explained below:

    Relevant: [Admin Appendix E(extract): Workflow ]

     

    Workflow

    Before you do any coding for the project,

    • Ensure you have set the Git username correctly (as explained in Appendix E) in all Computers you use for coding.
    • Read our reuse policy (in Admin: Appendix B), in particular, how to give credit when you reuse code from the Internet or classmates:
     

    Setting Git Username to Match GitHub Username

    We use various tools to analyze your code. For us to be able to identify your commits, you should use the GitHub username as your Git username as well. If there is a mismatch, or if you use multiple user names for Git, our tools might miss some of your work and as a result you might not get credit for some of your work.

    In each Computer you use for coding, after installing Git, you should set the Git username as follows.

    1. Open a command window that can run Git commands (e.g., Git bash window)
    2. Run the command git config --global user.name YOUR_GITHUB_USERNAME
      e.g., git config --global user.name JohnDoe

    More info about setting Git username is here.

     

    Policy on reuse

    Reuse is encouraged. However, note that reuse has its own costs (such as the learning curve, additional complexity, usage restrictions, and unknown bugs). Furthermore, you will not be given credit for work done by others. Rather, you will be given credit for using work done by others.

    • You are allowed to reuse work from your classmates, subject to following conditions:
      • The work has been published by us or the authors.
      • You clearly give credit to the original author(s).
    • You are allowed to reuse work from external sources, subject to following conditions:
      • The work comes from a source of 'good standing' (such as an established open source project). This means you cannot reuse code written by an outside 'friend'.
      • You clearly give credit to the original author. Acknowledge use of third party resources clearly e.g. in the welcome message, splash screen (if any) or under the 'about' menu. If you are open about reuse, you are less likely to get into trouble if you unintentionally reused something copyrighted.
      • You do not violate the license under which the work has been released. Please  do not use 3rd-party images/audio in your software unless they have been specifically released to be used freely. Just because you found it in the Internet does not mean it is free for reuse.
      • Always get permission from us before you reuse third-party libraries. Please post your 'request to use 3rd party library' in our forum. That way, the whole class get to see what libraries are being used by others.
      • This also ensures you learn the ethics to attribute credits to the correct stake holders/owners.

    Giving credit for reused work

    Given below are how to give credit for things you reuse from elsewhere. These requirements are specific to this module  i.e., not applicable outside the module (outside the module you should follow the rules specified by your employer and the license of the reused work)

    If you used a third party library:

    • Mention in the README.adoc (under the Acknowledgements section)
    • mention in the Project Portfolio Page if the library has a significant relevance to the features you implemented

    If you reused code snippets found on the Internet  e.g. from StackOverflow answers or
    referred code in another software or
    referred project code by current/past student:

    • If you read the code to understand the approach and implemented it yourself, mention it as a comment
      Example:
      //Solution below adapted from https://stackoverflow.com/a/16252290
      {Your implmentation of the reused solution here ...}
      
    • If you copy-pasted a non-trivial code block (possibly with minor modifications  renaming, layout changes, changes to comments, etc.), also mark the code block as reused code (using @@author tags)
      Format:
      //@@author {yourGithubUsername}-reused
      //{Info about the source...}
      
      {Reused code (possibly with minor modifications) here ...}
      
      //@@author
      
      Example of reusing a code snippet (with minor modifications):
      persons = getList()
      //@@author johndoe-reused
      //Reused from https://stackoverflow.com/a/34646172 with minor modifications
      Collections.sort(persons, new Comparator<CustomData>() {
          @Override
          public int compare(CustomData lhs, CustomData rhs) {
              return lhs.customInt > rhs.customInt ? -1 : (lhs.customInt < rhs.customInt) ? 1 : 0;
          }
      });
      //@@author
      return persons;
      

    Adding @@author tags indicate authorship

    • Mark your code with a //@@author {yourGithubUsername}. Note the double @.
      The //@@author tag should indicates the beginning of the code you wrote. The code up to the next //@@author tag or the end of the file (whichever comes first) will be considered as was written by that author. Here is a sample code file:

      //@@author johndoe
      method 1 ...
      method 2 ...
      //@@author sarahkhoo
      method 3 ...
      //@@author johndoe
      method 4 ...
      
    • If you don't know who wrote the code segment below yours, you may put an empty //@@author (i.e. no GitHub username) to indicate the end of the code segment you wrote. The author of code below yours can add the GitHub username to the empty tag later. Here is a sample code with an empty author tag:

      method 0 ...
      //@@author johndoe
      method 1 ...
      method 2 ...
      //@@author
      method 3 ...
      method 4 ...
      
    • The author tag syntax varies based on file type e.g. for java, css, fxml. Use the corresponding comment syntax for non-Java files.
      Here is an example code from an xml/fxml file.

      <!-- @@author sereneWong -->
      <textbox>
        <label>...</label>
        <input>...</input>
      </textbox>
      ...
      
    • Do not put the //@@author inside java header comments.
      👎

      /**
        * Returns true if ...
        * @@author johndoe
        */
      

      👍

      //@@author johndoe
      /**
        * Returns true if ...
        */
      

    What to and what not to annotate

    • Annotate both functional and test code There is no need to annotate documentation files.

    • Annotate only significant size code blocks that can be reviewed on its own  e.g., a class, a sequence of methods, a method.
      Claiming credit for code blocks smaller than a method is discouraged but allowed. If you do, do it sparingly and only claim meaningful blocks of code such as a block of statements, a loop, or an if-else statement.

      • If an enhancement required you to do tiny changes in many places, there is no need to annotate all those tiny changes; you can describe those changes in the Project Portfolio page instead.
      • If a code block was touched by more than one person, either let the person who wrote most of it (e.g. more than 80%) take credit for the entire block, or leave it as 'unclaimed' (i.e., no author tags).
      • Related to the above point, if you claim a code block as your own, more than 80% of the code in that block should have been written by yourself. For example, no more than 20% of it can be code you reused from somewhere.
      • 💡 GitHub has a blame feature and a history feature that can help you determine who wrote a piece of code.
    • Do not try to boost the quantity of your contribution using unethical means such as duplicating the same code in multiple places. In particular, do not copy-paste test cases to create redundant tests. Even repetitive code blocks within test methods should be extracted out as utility methods to reduce code duplication. Individual members are responsible for making sure code attributed to them are correct. If you notice a team member claiming credit for code that he/she did not write or use other questionable tactics, you can email us (after the final submission) to let us know.

    • If you wrote a significant amount of code that was not used in the final product,

      • Create a folder called {project root}/unused
      • Move unused files (or copies of files containing unused code) to that folder
      • use //@@author {yourGithubUsername}-unused to mark unused code in those files (note the suffix unused) e.g.
      //@@author johndoe-unused
      method 1 ...
      method 2 ...
      

      Please put a comment in the code to explain why it was not used.

    • If you reused code from elsewhere, mark such code as //@@author {yourGithubUsername}-reused (note the suffix reused) e.g.

      //@@author johndoe-reused
      method 1 ...
      method 2 ...
      
    • You can use empty @@author tags to mark code as not yours when RepoSense attribute the to you incorrectly.

      • Code generated by the IDE/framework, should not be annotated as your own.

      • Code you modified in minor ways e.g. adding a parameter. These should not be claimed as yours but you can mention these additional contributions in the Project Portfolio page if you want to claim credit for them.

     

    At the end of the project each student is required to submit a Project Portfolio Page.

    • Objective:

      • For you to use  (e.g. in your resume) as a well-documented data point of your SE experience
      • For us to use as a data point to evaluate your,
        • contributions to the project
        • your documentation skills
    • Sections to include:

      • Overview: A short overview of your product to provide some context to the reader.

      • Summary of Contributions:

        • Code contributed: Give a link to your code on Project Code Dashboard, which should be https://nuscs2113-ay1819s2.github.io/dashboard-beta/#=undefined&search=github_username_in_lower_case (replace github_username_in_lower_case with your actual username in lower case e.g., johndoe). This link is also available in the Project List Page -- linked to the icon under your photo.
        • Features implemented: A summary of the features you implemented. If you implemented multiple features, you are recommended to indicate which one is the biggest feature.
        • Other contributions:
          • Contributions to project management e.g., setting up project tools, managing releases, managing issue tracker etc.
          • Evidence of helping others e.g. responses you posted in our forum, bugs you reported in other team's products,
          • Evidence of technical leadership e.g. sharing useful information in the forum
      • Relevant descriptions/terms/conventions: Include all relevant details necessary to understand the document, e.g., conventions, symbols or labels introduced by you, even if it was not introduced by you.

      • Contributions to the User Guide: Reproduce the parts in the User Guide that you wrote. This can include features you implemented as well as features you propose to implement.
        The purpose of allowing you to include proposed features is to provide you more flexibility to show your documentation skills. e.g. you can bring in a proposed feature just to give you an opportunity to use a UML diagram type not used by the actual features.

      • Contributions to the Developer Guide: Reproduce the parts in the Developer Guide that you wrote. Ensure there is enough content to evaluate your technical documentation skills and UML modelling skills. You can include descriptions of your design/implementations, possible alternatives, pros and cons of alternatives, etc.

      • If you plan to use the PPP in your Resume, you can also include your SE work outside of the module (will not be graded)

    • Format:

      • File name: docs/team/githbub_username_in_lower_case.adoc e.g., docs/team/johndoe.adoc

      • Follow the example in the AddressBook-Level4

      • 💡 You can use the Asciidoc's include feature to include sections from the developer guide or the user guide in your PPP. Follow the example in the sample.

      • It is assumed that all contents in the PPP were written primarily by you. If any section is written by someone else  e.g. someone else wrote described the feature in the User Guide but you implemented the feature, clearly state that the section was written by someone else  (e.g. Start of Extract [from: User Guide] written by Jane Doe).  Reason: Your writing skills will be evaluated based on the PPP

    • Page limit:

      Content Limit
      Overview + Summary of contributions 0.5-1 (soft limit)
      Contributions to the User Guide 1-3 (soft limit)
      Contributions to the Developer Guide 3-6 (soft limit)
      Total 5-10 (strict)
      • The page limits given above are after converting to PDF format. The actual amount of content you require is actually less than what these numbers suggest because the HTML → PDF conversion adds a lot of spacing around content.
      • Reason for page limit: These submissions are peer-graded (in the PE) which needs to be done in a limited time span.
        If you have more content than the limit given above, you can give a representative samples of UG and DG that showcase your documentation skills. Those samples should be understandable on their own. For the parts left-out, you can give an abbreviated version and refer the reader to the full UG/DG for more details.
        It's similar to giving extra details as appendices; the reader will look at the UG/DG if the PPP is not enough to make a judgment. For example, when judging documentation quality, if the part in the PPP is not well-written, there is no point reading the rest in the main UG/DG. That's why you need to put the most representative part of your writings in the PPP and still give an abbreviated version of the rest in the PPP itself. Even when judging the quantity of work, the reader should be able to get a good sense of the quantity by combining what is quoted in the PPP and your abbreviated description of the missing part. There is no guarantee that the evaluator will read the full document.

    Follow the forking workflow in your project up to v1.1. In particular,

    • Get team members to review PRs. A workflow without PR reviews is a risky workflow.
    • Do not merge PRs failing CI. After setting up Travis, the CI status of a PR is reported at the bottom of the PR page. The screenshot below shows the status of a PR that is passing all CI checks.

      If there is a failure, you can click on the Details link in corresponding line to find out more about the failure. Once you figure out the cause of the failure, push the a fix to the PR.
    • After setting up Netlify, you can use Netlify PR Preview to preview changes to documentation files, if the PR contains updates to documentation. To see the preview, click on the Details link in front of the Netlify status reported (refer screenshot above).

    After completing v1.1, you can adjust process rigor to suit your team's pace, as explained below.

    • Reduce automated tests have benefits, but they can be a pain to write/maintain; GUI tests are especially hard to maintain because their behavior can sometimes depend on things such as the OS, resolution etc.
      It is OK to get rid of some of the troublesome tests and rely more on manual testing instead. The less automated tests you have, the higher the risk of regressions; but it may be an acceptable trade-off under the circumstances if tests are slowing you down too much.
      There is no direct penalty for removing GUI tests. Also note our expectation on test code.

    • Reduce automated checks: You can also reduce the rigor of checkstyle checks to expedite PR processing.

    • Switch to a lighter workflow: While forking workflow is the safest, it is also rather heavy. You an switch to a simpler workflow if the forking workflow is slowing you down. Refer the textbook to find more about alternative workflows: branching workflow, centralized workflow. However, we still recommend that you use PR reviews, at least for PRs affecting others' features.

    You can also increase the rigor/safety of your workflow in the following ways:

    • Use GitHub's Protected Branches feature to protect your master branch against rogue PRs.
     
    • There is no requirement for a minimum coverage level. Note that in a production environment you are often required to have at least 90% of the code covered by tests. In this project, it can be less. The less coverage you have, the higher the risk of regression bugs, which will cost marks if not fixed before the final submission.
    • You must write some tests so that we can evaluate your ability to write tests.
    • How much of each type of testing should you do? We expect you to decide. You learned different types of testing and what they try to achieve. Based on that, you should decide how much of each type is required. Similarly, you can decide to what extent you want to automate tests, depending on the benefits and the effort required.
     

    Project Management → Revision Control →

    Forking Flow

    In the forking workflow, the 'official' version of the software is kept in a remote repo designated as the 'main repo'. All team members fork the main repo create pull requests from their fork to the main repo.

    To illustrate how the workflow goes, let’s assume Jean wants to fix a bug in the code. Here are the steps:

    1. Jean creates a separate branch in her local repo and fixes the bug in that branch.
    2. Jean pushes the branch to her fork.
    3. Jean creates a pull request from that branch in her fork to the main repo.
    4. Other members review Jean’s pull request.
    5. If reviewers suggested any changes, Jean updates the PR accordingly.
    6. When reviewers are satisfied with the PR, one of the members (usually the team lead or a designated 'maintainer' of the main repo) merges the PR, which brings Jean’s code to the main repo.
    7. Other members, realizing there is new code in the upstream repo, sync their forks with the new upstream repo (i.e. the main repo). This is done by pulling the new code to their own local repo and pushing the updated code to their own fork.

    Documentation:

    Recommended procedure for updating docs:

    1. Divide among yourselves who will update which parts of the document(s).
    2. Update the team repo by following the workflow mentioned above.

    Update the following pages in your project repo:

    • About Us page: This page is used for module admin purposes. Please follow the format closely or else our scripts will not be able to give credit for your work.
      • Replace info of SE-EDU developers with info of your team, including a suitable photo as described here.
      • Including the name/photo of the supervisor/lecturer is optional.
      • The photo of a team member should be doc/images/githbub_username_in_lower_case.png e.g. docs/images/damithc.png. If you photo is in jpg format, name the file as .png anyway.
      • Indicate the different roles played and responsibilities held by each team member. You can reassign these roles and responsibilities (as explained in Admin Project Scope) later in the project, if necessary.
     
    • The purpose of the profile photo is for the teaching team to identify you. Therefore, you should choose a recent individual photo showing your face clearly (i.e., not too small) -- somewhat similar to a passport photo. Some examples can be seen in the 'Teaching team' page. Given below are some examples of good and bad profile photos.

    • If you are uncomfortable posting your photo due to security reasons, you can post a lower resolution image so that it is hard for someone to misuse that image for fraudulent purposes. If you are concerned about privacy, you can request permission to omit your photo from the page by writing to prof.

     

    Roles indicate aspects you are in charge of and responsible for. E.g., if you are in charge of documentation, you are the person who should allocate which parts of the documentation is to be done by who, ensure the document is in right format, ensure consistency etc.

    This is a non-exhaustive list; you may define additional roles.

    • Team lead: Responsible for overall project coordination.
    • Documentation (short for ‘in charge of documentation’): Responsible for the quality of various project documents.
    • Testing: Ensures the testing of the project is done properly and on time.
    • Code quality: Looks after code quality, ensures adherence to coding standards, etc.
    • Deliverables and deadlines: Ensure project deliverables are done on time and in the right format.
    • Integration: In charge of versioning of the code, maintaining the code repository, integrating various parts of the software to create a whole.
    • Scheduling and tracking: In charge of defining, assigning, and tracking project tasks.
    • [Tool ABC] expert: e.g. Intellij expert, Git expert, etc. Helps other team member with matters related to the specific tool.
    • In charge of[Component XYZ]: e.g. In charge of Model, UI, Storage, etc. If you are in charge of a component, you are expected to know that component well, and review changes done to that component in v1.3-v1.4.

    Please make sure each of the important roles are assigned to one person in the team. It is OK to have a 'backup' for each role, but for each aspect there should be one person who is unequivocally the person responsible for it.

    • Contact Us Page: Update to match your product.

    • README.adoc page: Update it to match your project.

      • Add a UI mockup of your intended final product.
        Note that the image of the UI should be docs/images/Ui.png so that it can be downloaded by our scripts. Limit the file to contain one screenshot/mockup only and ensure the new image is roughly the same height x width proportions as the original one. Reason: when we compile these images from all teams into one page (example), yours should not look out of place.

      • The original README.adoc file (which doubles as the landing page of your project website) is written to read like the introduction to an SE learning/teaching resource. You should restructure this page to look like the home page of a real product (not a school project) targeting real users  e.g. remove references to addressbook-level3, Learning Outcomes etc. mention target users, add a marketing blurb etc. On a related note, also remove Learning Outcomes link and related pages.

      • Update the link of the Travis build status badge (Build Status) so that it reflects the build status of your team repo.
        For the other badges,

        • either set up the respective tool for your project (AB-4 Developer Guide has instructions on how to set up AppVeyor and Coveralls) and update the badges accordingly,
        • or remove the badge.
      • Acknowledge the original source of the code i.e. AddressBook-Level4 project created by SE-EDU initiative at https://github.com/se-edu/

    • User Guide: Start moving the content from your User Guide (draft created in previous weeks) into the User Guide page in your repository. If a feature is not implemented, mark it as 'Coming in v2.0' (example).

    • Developer Guide: Similar to the User Guide, start moving the content from your Developer Guide (draft created in previous weeks) into the Developer Guide page in your team repository.

    Product:

    • Each member can attempt to do a local-impact change to the code base.

      Objective: To familiarize yourself with at least one components of the product.

      Description: Divide the components among yourselves. Each member can do some small enhancements to their component(s) to learn the code of that component. Some suggested enhancements are given in the AddressBook-Level4 developer guide.

      Submission: Create PRs from your own fork to your team repo. Get it merged by following your team's workflow.

    Suggested tutorial questions

    Explain the associations, navigabilities, and multiplicities in the class diagram below:

    Suppose we wrote a program to follow the class structure given in this class diagram:

    Draw object diagrams to represent the object structures after each of these steps below. Assume that we are trying to minimize the number of total objects.

    i.e. apply step 1 → [diagram 1] → apply step 2 on diagram 1 → [diagram 2] and so on.

    1. There are no persons.

    2. Alfred is the Guardian of Bruce.

    3. Bruce's contact number is the same as Alfred's.

    4. Alfred is also the guardian of another person. That person lists Alfreds home address as his home address as well as office address.

    5. Alfred has a an office address at Wayne Industries building which is different from his home address (i.e. Bat Cave).

    After step 2, the diagram should be like this:

    Explain the meaning of various class diagram notations in the following class diagram:

    Consider the code below:

    public interface Billable {
        void bill();
    }
    
    public abstract class Item
             implements Billable {
        public abstract void print();
    }
    
    public class StockItem extends Item {
        private Review review;
        private String name;
    
        public StockItem(
            String name, Rating rating){
    
            this.name = name;
            this.review = new Review(rating);
        }
    
        @Override
        public void print() {
            //...
        }
    
        @Override
        public void bill() {
            //...
        }
    }
    
    public enum Rating {
        GOOD, OK, POOR
    }
    
    public class Review {
        private final Rating rating;
    
        public Review(Rating rating) {
            this.rating = rating;
        }
    }
    
    import java.util.List;
    
    public class Inventory {
        private List<Item> items;
    
        public int getItemCount(){
            return items.size();
        }
    
        public void generateBill(Billable b){
            // ...
        }
    
        public void add(Item s) {
            items.add(s);
        }
    }
    

    (a) Draw a class diagram to represent the code
    (b) Draw an object diagram to represent the situation where the inventory has one item with a name spanner and a review of POOR rating.

    See the chapter on Code Quality.

    Suggest ways to improve the quality of the code below.

    import java.io.FileNotFoundException;
    import java.util.*;
    
    public class CliApp {
    
        //...
        private static final String MESSAGE_COMMAND_HELP_PARAMETERS = "Parameters: %1$s";
        private static final String MESSAGE_COMMAND_HELP_EXAMPLE = "Example: %1$s";
        private static final String MESSAGE_DISPLAY_PERSON_DATA = "%1$s  Phone Number: %2$s  Email: %3$s";
        private static final String GOODBYE_MESSAGE = "Exiting Address Book... Good bye!";
        private static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format: %1$s";
        //...
    
        /**
         * List of all persons in the address book.
         */
        private static final ArrayList<String> person = new ArrayList<>();
    
    
        //...
    
        public static void main(String[] args) {
            String userCommand = "nothing"; boolean exit = false;
            if (args.length > 0) {
                showWelcomeMessage();
                processProgramArgs(args);
                loadDataFromStorage();
                while (!exit) {
                    System.out.print("Enter command: ");
                    userCommand = SCANNER.nextLine();
                    userCommand = userCommand.trim();
                    showToUser(userCommand);
                    String feedback = executeCommand(userCommand);
                    showResultToUser(feedback);
                }
            } else {
                showToUser("Incorrect usage!");
            }
        }
    
        private static void showResultToUser(String feedback) {
            switch (feedback) {
                case "0":
                    feedback = "Good (0)";
                    break;
                case "1":
                    feedback = "Better (1)";
                    break;
            }
            try {
                writeToFile(feedback);
            } catch (FileNotFoundException e) {
                //e.printStackTrace();
            }
        }
    
        private static void matcher(String s1, String s2) {
            // ...
        }
    
        /**
         * Show the {@code message} to the user
         */
        private static void showToUser(String message) {
            System.out.println(LINE_PREFIX + message.trim()); // add LINE_PREFIX in front
        }
    
    // ...
    
    }
    

    Admin Appendix B (Policies) → Policy on suggested length for submissions

    Policy on suggested length for submissions

    We don't usually give a strict page limit for documents such as User Guide and the Developer Guide. You need to decide yourself how long the document should be based on the purpose and the intended audience. You can determine the level of details required based on the samples we provide.

    Admin Appendix C (FAQs) → Why very narrow project scope?

    Why very narrow project scope?

    Defining your own unique project is more fun.

    But, wider scope → more diverse projects → harder for us to go deep into your project. The collective know-how we (i.e., students and the teaching team) have built up about SE issues related to the project become shallow and stretched too thinly. It also affects fairness of grading.

    That is why a strictly-defined project is more suitable for a first course in SE that focuses on nuts-and-bolts of SE. After learning those fundamentals, in higher level project modules you can focus more on the creative side of software projects without being dragged down by nuts-and-bolts SE issues (because you already know how to deal with them). However, we would like to allow some room for creativity too. That is why we let you build products that are slight variations of a given theme.

    Also note: The freedom to do 'anything' is not a necessary condition for creativity. Do not mistake being different for being creative. In fact, the more constrained you are, the more you need creativity to stand out.

    Admin Appendix C (FAQs) → Why project requirements are so vague?

    Why project requirements are so vague?

    "You tell me exactly what to do - I do that - you pay me (in grades)" is a model for contract work, not for learning. Being able to survive in imprecise, uncertain, volatile problem contexts is precisely what we are trying to teach you.

    For example, the best way to communicate something often depends on what is being communicated. That is why we don't specify the precise content for project documents. Instead, we aim to refine project documents iteratively. We believe the learning experience will be richer if we let you decide the best way to present your project information rather than just following our instructions blindly. For example, in real-life projects you are rarely told which diagrams to draw; that is a decision you have to make yourself.