Week 4 [Sep 3]
Todo
Admin info to read:
Policy on plagiarism
We encourage sharing, but you should share with everyone in the class, not just a selected group. That is,
- You are not allowed to share individual assignments with classmates directly.
- You are not allowed to share project-related things with other teams directly.
You can even reuse each other's work subject to the 'reuse policy' given below.
If you submit code (or adopt ideas) taken from elsewhere, you need to comply with our reuse policy.
Detection:
- Detecting plagiarism in code is quite easy. You are not fooling anyone by reordering code or renaming methods/variables.
- As all your work is publicly visible on GitHub, sooner or later somebody will notice the plagiarism.
Penalties:
- For submissions not affecting marks: We make a record of cases of plagiarism but we do not take further action. Such plagiarism does not disadvantage other students. Therefore, we prefer to spend all available resources on helping honest students to do better rather than to chase after dishonest students. If you think you gain something by plagiarizing, go ahead and do it. It's your choice and it's your loss.
- For the final project/exam: Any case of claiming others' work as yours will be reported to the university for disciplinary action.
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.
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:
Example of reusing a code snippet (with minor modifications)://@@author {yourGithubUsername}-reused //{Info about the source...} {Reused code (possibly with minor modifications) here ...} //@@author
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 emptyauthor
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 suffixunused
) e.g.
//@@author johndoe-unused method 1 ... method 2 ...
Please put a comment in the code to explain why it was not used.
- Create a folder called
-
If you reused code from elsewhere, mark such code as
//@@author {yourGithubUsername}-reused
(note the suffixreused
) 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://nus-cs2103-ay1819s1.github.io/cs2103-dashboard/#=undefined&search=githbub_username_in_lower_case
(replacegithbub_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. - Main feature implemented: A summary of the main feature (the so called major enhancement) you implemented
- Other contributions:
- Other minor enhancements you did which are not related to your main feature
- 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
- Code contributed: Give a link to your code on Project Code Dashboard, which should be
-
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, but ignore the following two lines in it.
- Minor enhancement: added a history command that allows the user to navigate to previous commands using up/down keys.
- Code contributed: [Functional code] [Test code] {give links to collated code files}
-
💡 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: If you have more content than the limit given below, shorten (or omit some content) so that you do not exceed the page limit. Having too much content in the PPP will be viewed unfavorably during grading. Note: the page limits given below 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.
Content Limit Overview + Summary of contributions 0.5-1 Contributions to the User Guide 1-3 Contributions to the Developer Guide 3-6 Total 5-10
-
Policy on help from outsiders
In general, you are not allowed to involve outsiders in your project except your team members and the teaching team. However, It is OK to give your product to others for the purpose of getting voluntary user feedback. It is also OK to learn from others as long as they don't do your project work themselves.
There is no midterm.
The final exam has two parts:
- Part 1: MCQ questions (1 hour, 20 marks)
- Part 2: Essay questions (1 hour, 20 marks)
Both papers will be given to you at the start but you need to answer Part 1 first (i.e. MCQ paper). It will be collected 1 hour after the exam start time (even if arrived late for the exam). You are free to start part 2 early if you finish Part 1 early.
Final Exam: Part 1 (MCQ)
Each MCQ question gives you a statement to evaluate.
An example statement
Testing is a Q&A activity
Unless stated otherwise, the meaning of answer options are
A: Agree. If the question has multiple statements, agree with all of them.
B: Disagree. If the question has multiple statements, disagree with at least one of them
C, D, E: Not used
Number of questions: 100
Note that you have slightly more than ½ minute for each question, which means you need to go through the questions fairly quickly.
Given the fast pace required by the paper, to be fair to all students, you will not be allowed to clarify doubts about questions (in Part 1) by talking to invigilators.
- If a question is not clear, you can circle the question number in the question paper and write your doubt in the question paper, near that question.
- If your doubt is justified (e.g. there is a typo in the question) or if many students found the question to be unclear, the examiner may decide to omit that question from grading.
Questions in Part 1 are confidential. You are not allowed to reveal Part 1 content to anyone after the exam. All pages of the assessment paper are to be returned at the end of the exam.
You will be given OCR forms (i.e., bubble sheets) to indicate your answers for Part 1. As each OCR form can accommodate only 50 answers, you will be given 2 OCR forms. Indicate your student number in both OCR forms.
To save space, we use the following notation in MCQ question. [x | y | z] means ‘x and z, but not y’
SE is [boring | useful | fun] means SE is not boring AND SE is useful AND SE is fun.
Consider the following statement:
- IDEs can help with [writing | debugging | testing] code.
The correct response for it is Disagree
because IDEs can help with all three of the given options, not just writing and testing.
Some questions will use underlines or highlighting to draw your attention to a specific part of the question. That is because those parts are highly relevant to the answer and we don’t want you to miss the relevance of that part.
Consider the statement below:
Technique ABC can be used to generate more test cases.
The word can is underlined because the decision you need to make is whether the ABC can or cannot be used to generate more test cases; the decision is not whether ABC can be used to generate more or better test cases.
Markers such as the one given below appears at left margin of the paper to indicate where the question corresponds to a new column in the OCR form. E.g. questions 11, 21, 31, etc. (a column has 10 questions). Such markers can help you to detect if you missed a question in the previous 10 questions. You can safely ignore those markers if you are not interested in making use of that additional hint.
Some questions have tags e.g., the question below has a tag JAVA
. These tags provide additional context about the question. In the example below, the tag indicates that the code given in the question is Java code.
The exam paper is open-book: you may bring any printed or written materials to the exam in hard copy format. However, given the fast pace required by Part 1, you will not have time left to refer notes during that part of the exam.
💡 Mark the OCR form as you go, rather than planning to transfer your answers to the OCR form near the end. Reason: Given there are 100 questions, it will be hard to estimate how much time you need to mass-transfer all answers to OCR forms.
💡 Write the answer in the exam paper as well when marking it in the OCR form. Reason: It will reduce the chance of missing a question. Furthermore, in case you missed a question, it will help you correct the OCR form quickly.
💡 We have tried to avoid deliberately misleading/tricky questions. If a question seems to take a very long time to figure out, you are probably over-thinking it.
You will be given a practice exam paper to familiarize yourself with this slightly unusual exam format.
Final Exam: Part 2 (Essay)
Unlike in part 1, you can ask invigilators for clarifications if you found a question to be unclear in part 2.
Yes, you may use pencils when answering part 2.
What if I don’t carry around a laptop?
If you do not have a laptop or prefer not to bring the laptop, it is up to you to show your work to the tutor in some way (e.g. by connecting to your home PC remotely), without requiring extra time/effort from the tutor or team members.
Reason: As you enjoy the benefits of not bring the laptop; you (not others) should bear the cost too.
Policy on publishing submissions
The source code are publicly available and are available for reuse by others without any restrictions.
Is publishing submissions unfair to the team? We don't think so. If you were the first to think of something your peers are willing to adopt later, that means you are already ahead of them and they are unlikely to earn more marks by adopting your ideas.
Outcomes
Project Management
W4.1
Can create PRs on GitHub
W4.1a
Can explain branching
Project Management → Revision Control →
Branching is the process of evolving multiple versions of the software in parallel. For example, one team member can create a new branch and add an experimental feature to it while the rest of the team keeps working on another branch. Branches can be given names e.g. master
, release
, dev
.
A branch can be merged into another branch. Merging usually result in a new commit that represents the changes done in the branch being merged.
Merge conflicts happen when you try to merge two branches that had changed the same part of the code and the RCS software cannot decide which changes to keep. In those cases we have to ‘resolve’ those conflicts manually.
In the context of RCS, what is the branching? What is the need for branching?.
In the context of RCS, what is the merging branches? How can it lead to merge conflicts?.
Evidence:
In the context of RCS, what is the branching? What is the need for branching?.
In the context of RCS, what is the merging branches? How can it lead to merge conflicts?.
W4.1b
Can use Git branching
Tools → Git and GitHub →
0. Observe that you are normally in the branch called master
. For this, you can take any repo you have on your computer (e.g. a clone of the samplerepo-things).
git status
on branch master
1. Start a branch named feature1
and switch to the new branch.
Click on the Branch
button on the main menu. In the next dialog, enter the branch name and click Create Branch
Note how the feature1
is indicated as the current branch.
You can use the branch
command to create a new branch and the checkout
command to switch to a specific branch.
git branch feature1
git checkout feature1
One-step shortcut to create a branch and switch to it at the same time:
git checkout –b feature1
2. Create some commits in the new branch. Just commit as per normal. Commits you add while on a certain branch will become part of that branch.
3. Switch to the master
branch. Note how the changes you did in the feature1
branch are no longer in the working directory.
Double-click the master
branch
git checkout master
4. Add a commit to the master branch. Let’s imagine it’s a bug fix.
5. Switch back to the feature1
branch (similar to step 3).
6. Merge the master
branch to the feature1
branch, giving an end-result like the below. Also note how Git has created a merge commit.
Right-click on the master
branch and choose merge master into the current branch
. Click OK
in the next dialog.
git merge master
Observe how the changes you did in the master
branch (i.e. the imaginary bug fix) is now available even when you are in the feature1
branch.
7. Add another commit to the feature1
branch.
8. Switch to the master
branch and add one more commit.
9. Merge feature1
to the master branch, giving and end-result like this:
Right-click on the feature1
branch and choose Merge...
.
git merge feature1
10. Create a new branch called add-countries
, switch to it, and add some commits to it (similar to steps 1-2 above). You should have something like this now:
11. Go back to the master
branch and merge the add-countries
branch onto the master
branch (similar to steps 8-9 above). While you might expect to see something like the below,
... you are likely to see something like this instead:
That is because Git does a fast forward merge if possible. Seeing that the master
branch has not changed since you started the add-countries
branch, Git has decided it is simpler to just put the commits of the add-countries
branch in front of the master
branch, without going into the trouble of creating an extra merge commit.
It is possible to force Git to create a merge commit even if fast forwarding is possible.
Tick the box shown below when you merge a branch:
Use the --no-ff
switch (short for no fast forward):
git merge --no-ff add-countries
Evidence:
Acceptable: Git branches you have created in any repo.
Suggested: Results of following the steps in the LO.
Submission: Show your branches during the tutorial.
W4.1c
Can create PRs on GitHub
Tools → Git and GitHub →
1. Fork the samplerepo-pr-practice onto your GitHub account. Clone it onto your computer.
2. Create a branch named add-intro
in your clone. Add a couple of commits which adds/modifies an Introduction section to the README.md
. Example:
# Introduction
Creating Pull Requsts (PRs) is needed when using RCS in a multi-person projects.
This repo can be used to practice creating PRs.
3. Push the add-intro
branch to your fork.
git push origin add-intro
4. Create a Pull Request from the add-intro
branch in your fork to the master
branch of the same fork (i.e. your-user-name/samplerepo-pr-practice
, not se-edu/samplerepo-pr-practice
), as described below.
4a. Go to the GitHub page of your fork (i.e. https://github.com/{your_username}/samplerepo-pr-practice
), click on the Pull Requests
tab, and then click on New Pull Request
button.
4b. Select base fork
and head fork
as follows:
base fork
: your own fork (i.e.{your user name}/samplerepo-pr-practice
, NOTse-edu/samplerepo-pr-practice
)head fork
: your own fork.
The base fork is where changes should be applied. The head fork contains the changes you would like to be applied.
4c. (1) Set the base branch to master
and head branch to add-intro
, (2) confirm the diff contains the changes you propose to merge in this PR (i.e. confirm that you did not accidentally include extra commits in the branch), and (3) click the Create pull request
button.
4d. (1) Set PR name, (2) set PR description, and (3) Click the Create pull request
button.
A common newbie mistake when creating branch-based PRs is to mix commits of one PR with another. To learn how to avoid that mistake, you are encouraged to continue and create another PR as explained below.
5. In your local repo, create a new branch add-summary
off the master
branch.
When creating the new branch, it is very important that you switch back to the master
branch first. If not, the new branch will be created off the current branch add-intro
. And that is how you end up having commits of the first PR in the second PR as well.
6. Add a commit in the add-summary
branch that adds a Summary section to the README.md
, in exactly the same place you added the Introduction section earlier.
7. Push the add-summary
to your fork and create a new PR similar to before.
Evidence:
Acceptable: PRs created in any repo.
Suggested: PRs created by following the steps in the LO.
Submission: Show your PRs during the tutorial.
Requirements
W4.2
Can explain requirements
W4.2a
Can explain requirements
Requirements → Requirements →
A software requirement specifies a need to be fulfilled by the software product.
A software project may be,
- a brown-field project i.e., develop a product to replace/update an existing software product
- a green-field project i.e., develop a totally new system with no precedent
In either case, requirements need to be gathered, analyzed, specified, and managed.
Requirements come from stakeholders.
Stakeholder: A party that is potentially affected by the software project. e.g. users, sponsors, developers, interest groups, government agencies, etc.
Identifying requirements is often not easy. For example, stakeholders may not be aware of their precise needs, may not know how to communicate their requirements correctly, may not be willing to spend effort in identifying requirements, etc.
W4.2b
Can explain non-functional requirements
Requirements → Requirements →
There are two kinds of requirements:
- Functional requirements specify what the system should do.
- Non-functional requirements specify the constraints under which system is developed and operated.
Some examples of non-functional requirement categories:
- Data requirements e.g. size,
volatility ,persistency etc., - Environment requirements e.g. technical environment in which system would operate or need to be compatible with.
- Accessibility, Capacity, Compliance with regulations, Documentation, Disaster recovery, Efficiency, Extensibility, Fault tolerance, Interoperability, Maintainability, Privacy, Portability, Quality, Reliability, Response time, Robustness, Scalability, Security, Stability, Testability, and more ...
- Business/domain rules: e.g. the size of the minefield cannot be smaller than five.
- Constraints: e.g. the system should be backward compatible with data produced by earlier versions of the system; system testers are available only during the last month of the project; the total project cost should not exceed $1.5 million.
- Technical requirements: e.g. the system should work on both 32-bit and 64-bit environments.
- Performance requirements: e.g. the system should respond within two seconds.
- Quality requirements: e.g. the system should be usable by a novice who has never carried out an online purchase.
- Process requirements: e.g. the project is expected to adhere to a schedule that delivers a feature set every one month.
- Notes about project scope: e.g. the product is not required to handle the printing of reports.
- Any other noteworthy points: e.g. the game should not use images deemed offensive to those injured in real mine clearing activities.
We may have to spend an extra effort in digging NFRs out as early as possible because,
- NFRs are easier to miss e.g., stakeholders tend to think of functional requirements first
- sometimes NFRs are critical to the success of the software. E.g. A web application that is too slow or that has low security is unlikely to succeed even if it has all the right functionality.
Given below are some requirements of TEAMMATES (an online peer evaluation system for education). Which one of these are non-functional requirements?
- a. The response to any use action should become visible within 5 seconds.
- b. The application admin should be able to view a log of user activities.
- c. The source code should be open source.
- d. A course should be able to have up to 2000 students.
- e. As a student user, I can view details of my team members so that I can know who they are.
- f. The user interface should be intuitive enough for users who are not IT-savvy.
- g. The product is offered as a free online service.
(a)(c)(d)(f)(g)
Explanation: (b) are (e) are functions available for a specific user types. Therefore, they are functional requirements. (a), (c), (d), (f) and (g) are either constraints on functionality or constraints on how the project is done, both of which are considered non-functional requirements.
W4.2c
Can explain prioritizing requirements
Requirements → Requirements →
Requirements can be prioritized based the importance and urgency, while keeping in mind the constraints of schedule, budget, staff resources, quality goals, and other constraints.
A common approach is to group requirements into priority categories. Note that all such scales are subjective, and stakeholders define the meaning of each level in the scale for the project at hand.
An example scheme for categorizing requirements:
Essential
: The product must have this requirement fulfilled or else it does not get user acceptanceTypical
: Most similar systems have this feature although the product can survive without it.Novel
: New features that could differentiate this product from the rest.
Other schemes:
High
,Medium
,Low
Must-have
,Nice-to-have
,Unlikely-to-have
Level 0
,Level 1
,Level 2
, ...
Some requirements can be discarded if they are considered ‘out of
The requirement given below is for a Calendar application. Stakeholder of the software (e.g. product designers) might decide the following requirement is not in the scope of the software.
The software records the actual time taken by each task and show the difference between the actual and scheduled time for the task.
W4.2d
Can explain quality of requirements
Requirements → Requirements →
Here are some characteristics of well-defined requirements
- Unambiguous
- Testable (verifiable)
- Clear (concise, terse, simple, precise)
- Correct
- Understandable
- Feasible (realistic, possible)
- Independent
-
Atomic - Necessary
- Implementation-free (i.e. abstract)
Besides these criteria for individual requirements, the set of requirements as a whole should be
- Consistent
- Non-redundant
- Complete
Peter Zielczynski, Requirements Management Using IBM Rational RequisitePro, IBM Press, 2008
W4.3
Can explain some techniques for gathering requirements
W4.3a
Can explain brainstorming
Requirements → Gathering Requirements →
Brainstorming: A group activity designed to generate a large number of diverse and creative ideas for the solution of a problem.
In a brainstorming session there are no "bad" ideas. The aim is to generate ideas; not to validate them. Brainstorming encourages you to "think outside the box" and put "crazy" ideas on the table without fear of rejection.
What is the key characteristic about brainstorming?
(b)
W4.3b
Can explain product surveys
Requirements → Gathering Requirements →
Studying existing products can unearth shortcomings of existing solutions that can be addressed by a new product. Product manuals and other forms of technical documentation of an existing system can be a good way to learn about how the existing solutions work.
When developing a game for a mobile device, a look at a similar PC game can give insight into the kind of features and interactions the mobile game can offer.
W4.3c
Can explain observation
Requirements → Gathering Requirements →
Observing users in their natural work environment can uncover product requirements. Usage data of an existing system can also be used to gather information about how an existing system is being used, which can help in building a better replacement e.g. to find the situations where the user makes mistakes when using the current system.
W4.3d
Can explain user surveys
W4.3e
Can explain interviews
Requirements → Gathering Requirements →
W4.3f
Can explain focus groups
Requirements → Gathering Requirements →
[source]
Focus groups are a kind of informal interview within an interactive group setting. A group of people (e.g. potential users, beta testers) are asked about their understanding of a specific issue, process, product, advertisement, etc.
W4.3g
Can explain prototyping
Requirements → Gathering Requirements →
Prototype: A prototype is a mock up, a scaled down version, or a partial system constructed
- to get users’ feedback.
- to validate a technical concept (a "proof-of-concept" prototype).
- to give a preview of what is to come, or to compare multiple alternatives on a small scale before committing fully to one alternative.
- for early field-testing under controlled conditions.
Prototyping can uncover requirements, in particular, those related to how users interact with the system. UI prototypes are often used in brainstorming sessions, or in meetings with the users to get quick feedback from them.
[source: http://balsamiq.com/products/mockups]
💡 Prototyping can be used for discovering as well as specifying requirements e.g. a UI prototype can serve as a specification of what to build.
W4.4
Can use some techniques for specifying requirements
Prose
W4.4a
Can explain prose
Requirements → Specifying Requirements → Prose →
A textual description (i.e. prose) can be used to describe requirements. Prose is especially useful when describing abstract ideas such as the vision of a product.
The product vision of the TEAMMATES Project given below is described using prose.
TEAMMATES aims to become the biggest student project in the world (biggest here refers to 'many contributors, many users, large code base, evolving over a long period'). Furthermore, it aims to serve as a training tool for Software Engineering students who want to learn SE skills in the context of a non-trivial real software product.
Avoid using lengthy prose to describe requirements; they can be hard to follow.
Feature Lists
W4.4b
Can explain feature list
Requirements → Specifying Requirements → Feature Lists →
Feature List: A list of features of a product grouped according to some criteria such as aspect, priority, order of delivery, etc.
A sample feature list from a simple Minesweeper game (only a brief description has been provided to save space):
- Basic play – Single player play.
- Difficulty levels
- Medium-levels
- Advanced levels
- Versus play – Two players can play against each other.
- Timer – Additional fixed time restriction on the player.
- ...
User Stories
W4.4c
Can write simple user stories
Requirements → Specifying Requirements → User Stories →
User story: User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. [Mike Cohn]
A common format for writing user stories is:
User story format: As a {user type/role} I can {function} so that {benefit}
Examples (from a Learning Management System):
- As a student, I can download files uploaded by lecturers, so that I can get my own copy of the files
- As a lecturer, I can create discussion forums, so that students can discuss things online
- As a tutor, I can print attendance sheets, so that I can take attendance during the class
We can write user stories on index cards or sticky notes, and arrange on walls or tables, to facilitate planning and discussion. Alternatively, we can use a software (e.g., GitHub Project Boards, Trello, Google Docs, ...) to manage user stories digitally.
[credit: https://www.flickr.com/photos/jakuza/with/2726048607/]
[credit: https://commons.wikimedia.org/wiki/File:User_Story_Map_in_Action.png]
- a. They are based on stories users tell about similar systems
- b. They are written from the user/customer perspective
- c. They are always written in some physical medium such as index cards or sticky notes
- a. Reason: Despite the name, user stories are not related to 'stories' about the software.
- b.
- c. Reason: It is possible to use software to record user stories. When the team members are not co-located this may be the only option.
Critique the following user story taken from a software project to build an e-commerce website.
As a developer, I want to use Python to implement the software, so that we can resue existing Python modules.
Refer to the definition of a user story.
User story: User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. [Mike Cohn]
This user story is not written from the perspective of the user/customer.
Bill wants you to build a Human Resource Management (HRM) system. He mentions that the system will help employees to view their own
Remember to follow the correct format when writing user stories.
User story format: As a {user type/role} I can {function} so that {benefit}
As an employee, I can view my leave balance, so that I can know how many leave days I have left.
Note: the {benefit}
part may vary as it is not specifically mentioned in the question.
Evidence:
Covered by:
W4.4d
Can write more detailed user stories
Requirements → Specifying Requirements → User Stories →
The {benefit}
can be omitted if it is obvious.
As a user, I can login to the system so that I can access my data
💡 It is recommended to confirm there is a concrete benefit even if you omit it from the user story. If not, you could end up adding features that have no real benefit.
You can add more characteristics to the {user role}
to provide more context to the user story.
- As a forgetful user, I can view a password hint, so that I can recall my password.
- As an expert user, I can tweak the underlying formatting tags of the document, so that I can format the document exactly as I need.
You can write user stories at various levels. High-level user stories, called epics (or themes) cover bigger functionality. You can then break down these epics to multiple user stories of normal size.
[Epic] As a lecturer, I can monitor student participation levels
- As a lecturer, I can view the forum post count of each student so that I can identify the activity level of students in the forum
- As a lecturer, I can view webcast view records of each student so that I can identify the students who did not view webcasts
- As a lecturer, I can view file download statistics of each student so that I can identify the students who do not download lecture materials
You can add conditions of satisfaction to a user story to specify things that need to be true for the user story implementation to be accepted as ‘done’.
- As a lecturer, I can view the forum post count of each student so that I can identify the activity level of students in the forum.
Conditions:
- Separate post count for each forum should be shown
- Total post count of a student should be shown
- The list should be sortable by student name and post count
Other useful info that can be added to a user story includes (but not limited to)
- Priority: how important the user story is
- Size: the estimated effort to implement the user story
- Urgency: how soon the feature is needed
User stories for a travel website (credit: Mike Cohen)
- As a registered user, I am required to log in so that I can access the system
- As a forgetful user, I can request a password reminder so that I can log in if I forget mine
- [Epic] As a user, I can cancel a reservation
- As a premium site member, I can cancel a reservation up to the last minute
- As a non-premium member, I can cancel up to 24 hours in advance
- As a member, I am emailed a confirmation of any cancelled reservation
- [Epic] As a frequent flyer, I want to book a trip
- As a frequent flyer, I want to book a trip using miles
- As a frequent flyer, I want to rebook a trip I take often
- As a frequent flyer, I want to request an upgrade
- As a frequent flyer, I want to see if my upgrade cleared
Choose the correct statements
- a. User stories are short and written in a formal notation.
- b. User stories is another name for use cases.
- c. User stories describes past experiences users had with similar systems. These are helpful in developing the new system.
- d. User stories are not detailed enough to tell us exact details of the product.
- a.
- b.
- c.
- d.
Explanation: User stories are short and written in natural language, NOT in a formal language. They are used for estimation and scheduling purposes but do not contain enough details to form a complete system specification.
W4.4e
Can use user stories to manage requirements of project
Requirements → Specifying Requirements → User Stories →
User stories capture user requirements in a way that is convenient for
[User stories] strongly shift the focus from writing about features to discussing them. In fact, these discussions are more important than whatever text is written. [Mike Cohn, MountainGoat Software 🔗]
User stories differ from
User stories can capture
Requirements → Requirements →
There are two kinds of requirements:
- Functional requirements specify what the system should do.
- Non-functional requirements specify the constraints under which system is developed and operated.
Some examples of non-functional requirement categories:
- Data requirements e.g. size,
volatility ,persistency etc., - Environment requirements e.g. technical environment in which system would operate or need to be compatible with.
- Accessibility, Capacity, Compliance with regulations, Documentation, Disaster recovery, Efficiency, Extensibility, Fault tolerance, Interoperability, Maintainability, Privacy, Portability, Quality, Reliability, Response time, Robustness, Scalability, Security, Stability, Testability, and more ...
- Business/domain rules: e.g. the size of the minefield cannot be smaller than five.
- Constraints: e.g. the system should be backward compatible with data produced by earlier versions of the system; system testers are available only during the last month of the project; the total project cost should not exceed $1.5 million.
- Technical requirements: e.g. the system should work on both 32-bit and 64-bit environments.
- Performance requirements: e.g. the system should respond within two seconds.
- Quality requirements: e.g. the system should be usable by a novice who has never carried out an online purchase.
- Process requirements: e.g. the project is expected to adhere to a schedule that delivers a feature set every one month.
- Notes about project scope: e.g. the product is not required to handle the printing of reports.
- Any other noteworthy points: e.g. the game should not use images deemed offensive to those injured in real mine clearing activities.
We may have to spend an extra effort in digging NFRs out as early as possible because,
- NFRs are easier to miss e.g., stakeholders tend to think of functional requirements first
- sometimes NFRs are critical to the success of the software. E.g. A web application that is too slow or that has low security is unlikely to succeed even if it has all the right functionality.
Given below are some requirements of TEAMMATES (an online peer evaluation system for education). Which one of these are non-functional requirements?
- a. The response to any use action should become visible within 5 seconds.
- b. The application admin should be able to view a log of user activities.
- c. The source code should be open source.
- d. A course should be able to have up to 2000 students.
- e. As a student user, I can view details of my team members so that I can know who they are.
- f. The user interface should be intuitive enough for users who are not IT-savvy.
- g. The product is offered as a free online service.
(a)(c)(d)(f)(g)
Explanation: (b) are (e) are functions available for a specific user types. Therefore, they are functional requirements. (a), (c), (d), (f) and (g) are either constraints on functionality or constraints on how the project is done, both of which are considered non-functional requirements.
An example of a NFR captured as a user story:
As a | I want to | so that |
---|---|---|
impatient user | to be able experience reasonable response time from the website while up to 1000 concurrent users are using it | I can use the app even when the traffic is at the maximum expected level |
Given their lightweight nature, user stories are quite handy for recording requirements during early stages of requirements gathering.
💡 Here are some tips for using user stories for early stages of requirement gathering:
- Define the target user:
Decide your target user's profile (e.g. a student, office worker, programmer, sales person) and work patterns (e.g. Does he work in groups or alone? Does he share his computer with others?). A clear understanding of the target user will help when deciding the importance of a user story. You can even give this user a name. e.g. Target user Jean is a university student studying in a non-IT field. She interacts with a lot of people due to her involvement in university clubs/societies. ... - Define the problem scope: Decide that exact problem you are going to solve for the target user. e.g. Help Jean keep track of all her school contacts
- Don't be too hasty to discard 'unusual' user stories:
Those might make your product unique and stand out from the rest, at least for the target users. - Don't go into too much details:
For example, consider this user story:As a user, I want to see a list of tasks that needs my attention most at the present time, so that I pay attention to them first.
When discussing this user story, don't worry about what tasks should be considered needs my attention most at the present time. Those details can be worked out later. - Don't be biased by preconceived product ideas:
When you are at the stage of identifying user needs, clear your mind of ideas you have about what your end product will look like. - Don't discuss implementation details or whether you are actually going to implement it:
When gathering requirements, your decision is whether the user's need is important enough for you to want to fulfil it. Implementation details can be discussed later. If a user story turns out to be too difficult to implement later, you can always omit it from the implementation plan.
While use cases can be recorded on
You can create issues for each of the user stories and use a GitHub Project Board to sort them into categories.
Example Project Board:
Example Issue to represent a user story:
A video on GitHub Project Boards:
Example Google Sheet for recording user stories:
Example Trello Board for recording user stories:
Extreme programming (XP) is a software development methodology which is intended to improve software quality and responsiveness to changing customer requirements. As a type of agile software development, it advocates frequent "releases" in short development cycles, which is intended to improve productivity and introduce checkpoints at which new customer requirements can be adopted. [wikipedia, 2017.05.01]
This page in their website explains the difference between user stories and traditional requirements.
One of the biggest misunderstandings with user stories is how they differ from traditional requirements specifications. The biggest difference is in the level of detail. User stories should only provide enough detail to make a reasonably low risk estimate of how long the story will take to implement. When the time comes to implement the story developers will go to the customer and receive a detailed description of the requirements face to face.
- This article by Mike Cohn from MountainGoatSoftware explains how to use user stories to capture NFRs.
Evidence:
Covered by the project.
Use Cases
W4.4f
Can explain use cases
Requirements → Specifying Requirements → Use Cases →
Use Case: A description of a set of sequences of actions, including variants, that a system performs to yield an observable result of value to an
Actor: An actor (in a use case) is a role played by a user. An actor can be a human or another system. Actors are not part of the system; they reside outside the system.
A use case describes an interaction between the user and the system for a specific functionality of the system.
- System:
ATM - Actor: Customer
- Use Case: Check account balance
- User inserts an ATM card
- ATM prompts for PIN
- User enters PIN
- ATM prompts for withdrawal amount
- User enters the amount
- ATM ejects the ATM card and issues cash
- User collects the card and the cash.
- System: A Learning Management System (LMS)
- Actor: Student
- Use Case: Upload file
- Student requests to upload file
- LMS requests for the file location
- Student specifies the file location
- LMS uploads the file
Unified Modeling Language (UML) is a graphical notation to describe various aspects of a software system. UML is the brainchild of three software modeling specialists James Rumbaugh, Grady Booch and Ivar Jacobson (also known as the Three Amigos). Each of them has developed their own notation for modeling software systems before joining force to create a unified modeling language (hence, the term ‘Unified’ in UML). UML is currently the de facto modeling notation used in the software industry.
Use cases capture the functional requirements of a system.
W4.4g
Can use use cases to list functional requirements of a simple system
Requirements → Specifying Requirements → Use Cases →
A use case is an interaction between a system and its actors.
Actors in Use Cases
Actor: An actor (in a use case) is a role played by a user. An actor can be a human or another system. Actors are not part of the system; they reside outside the system.
Some example actors for a Learning Management System
- Actors: Guest, Student, Staff, Admin,
ExamSys ,LibSys .
A use case can involve multiple actors.
- Software System: LearnSys
- Use case: UC01 conduct survey
- Actors: Staff, Student
An actor can be involved in many use cases.
- Software System: LearnSys
- Actor: Staff
- Use cases: UC01 conduct survey, UC02 Set Up Course Schedule, UC03 Email Class, ...
A single person/system can play many roles.
- Software System: LearnSys
- Person: a student
- Actors (or Roles): Student, Guest, Tutor
Many persons/systems can play a single role.
- Software System: LearnSys
- Actor(or role) : Student
- Persons that can play this role : undergraduate student, graduate student, a staff member doing a part-time course, exchange student
Use cases can be specified at various levels of detail.
Consider the three use cases given below. Clearly, (a) is at a higher level than (b) and (b) is at a higher level than (c).
- System: LearnSys
- Use cases:
a. Conduct a survey
b. Take the survey
c. Answer survey question
💡 While modeling user-system interactions,
- Start with high level use cases and progressively work toward lower level use cases.
- Be mindful at which level of details you are working on and not to mix use cases of different levels.
Consider a simple movie ticket vending machine application. Every week, the theatre staff will enter the weekly schedule as well as ticket price for each show. A customer sees the schedule and the ticket price displayed at the machine. There is a slot to insert money, a keypad to enter a code for a movie, a code for the show time, and the number of tickets. A display shows the customer's balance inside the machine. A customer may choose to cancel a transaction before pressing the “buy” button. Printed tickets can be collected from a slot at the bottom of the machine. The machine also displays messages such as "Please enter more money”, “Request fewer tickets" or "SOLD OUT!”. Finally, a "Return Change" button allows the customer to get back his unspent money.
Draw a use case diagram for the above requirements.
Note that most of the details in the description are better given as part of the use case description rather than as low-level use cases in the diagram.
A software house wishes to automate its Quality Assurance division.
The system is to be used by Testers, Programmers and System Administrators. Only an administrator can create new users and assign tasks to programmers. Any tester can create a bug report, as well as set the status of a bug report as ‘closed’. Only a programmer can set the state of a bug report to ‘fixed’, but a programmer cannot set the status of a bug report to ‘closed’. Each tester is assigned just one task at a time. A task involves testing of a particular component for a particular customer. Tester must document the bugs they find. Each bug is given a unique identifier. Other information recorded about the bug is component id, severity, date and time reported, programmer who is assigned to fix it, date fixed, date retested and date closed. The system keeps track of which bugs are assigned to which programmer at any given time. It should be able to generate reports on the number of bugs found, fixed and closed e.g. number of bugs per component and per customer; number of bugs found by a particular tester ; number of bugs awaiting to be fixed; number of bugs awaiting to be retested; number of bugs awaiting to be assigned to programmers etc.
Develop a use case diagram to capture their requirements given below.
Explanation: The given description contains information not relevant to use case modeling. Furthermore, the description is not enough to complete the use case diagram All these are realities of real projects. However, the process of trying to create this use case diagram prompts us to investigate issues such as:
- Is ‘edit bug report’ a use case or editing the bug report is covered by other use cases such as those for setting the status of bug reports? If it is indeed a separate use case, who are the actors of that use case?
- Does ‘assign task’ simply means ‘assign bug report’ or is there any other type of tasks?
- There was some mention about Customers and Components. Does the system have to support use cases for creating and maintaining details about those entities? For example, should we have a ‘create customer record’ use case?
- Which actors can perform the ‘generate report’ use case? Are reports generated automatically by the system at a specific time or generated ‘on demand’ when users request to view them? Do we have to treat different types of reports as different use cases (in case some types of reports are restricted to some types of users)? The above diagram assumes (just for illustration) that the report is generated on demand and only the system admin can generate any report.
W4.4h
Can specify details of a use case in a structured format
Requirements → Specifying Requirements → Use Cases →
Writing use case steps
The main body of the use case is the sequence of steps that describes the interaction between the system and the actors. Each step is given as a simple statement describing who does what.
An example of the main body of a use case.
- Student requests to upload file
- LMS requests for the file location
- Student specifies the file location
- LMS uploads the file
A use case describes only the externally visible behavior, not internal details, of a system i.e. should not mention give details that are not part of the interaction between the user and the system.
This example use case step refers to behaviors not externally visible .
- LMS saves the file into the cache and indicates success.
A step gives the intention of the actor (not the mechanics). That means UI details are usually omitted. The idea is to leave as much flexibility to the UI designer as possible. That is, the use case specification should be as general as possible (less specific) about the UI.
The first example below is not a good use case step because contains UI-specific details. The second one is better because it omits UI-specific details.
Bad : User right-clicks the text box and chooses ‘clear’
Good : User clears the input
A use case description can show loops too.
An example of how you can show a loop:
Software System: Square game
Use case:
- A Player starts the game.
- SquareGame asks for player names.
- Each Player enters his own name.
- SquareGame shows the order of play.
- SquareGame prompts for the current Player to throw die.
- Current Player adjusts the throw speed.
- Current Player triggers the die throw.
- Square Game shows the face value of the die.
- Square Game moves the Player's piece accordingly.
Steps 5-9 are repeated for each Player, and for as many rounds as required until a Player reaches the 100th square. - Square Game shows the Winner.
Use case ends.
The Main Success Scenario (MSS) describes the most straightforward interaction for a given use case, which assumes that nothing goes wrong. This is also called the Basic Course of Action or the Main Flow of Events of a use case.
- System: Online Banking System (OBS)
- Use case: UC23 - Transfer Money
- Actor: User
- MSS:
- User chooses to transfer money.
- OBS requests for details of the transfer.
- User enters the requested details.
- OBS requests for confirmation.
- OBS transfers the money and displays the new account balance.
- Use case ends.
Note how the MSS assumes that all entered details are correct and ignores problems such as timeouts, network outages etc. Fro example, MSS does not tell us what happens if the user enters an incorrect data.
Extensions are "add-on"s to the MSS that describe exceptional/alternative flow of events. They describe variations of the scenario that can happen if certain things are not as expected by the MSS. Extensions appear below the MSS.
This example adds some extensions to the use case in the previous example.
- System: Online Banking System (OBS)
- Use case: UC23 - Transfer Money
- Actor: User
- MSS:
- User chooses to transfer money.
- OBS requests for details of the transfer.
- User enters the requested details.
- OBS requests for confirmation.
- OBS transfers the money and displays the new account balance.
- Use case ends.
- Extensions:
- 3a. OBS detects an error in the entered data.
- 3a1. OBS requests for the correct data.
- 3a2. User enters new data.
- Steps 3a1-3a2 are repeated until the data entered are correct.
- Use case resumes from step 4.
- 3b. User requests to effect the transfer in a future date.
- 3b1. OBS requests for confirmation.
- 3b2. User confirms future transfer.
- Use case ends.
- *a. At any time, User chooses to cancel the transfer.
- *a1. OBS requests to confirm the cancellation.
- *a2. User confirms the cancellation.
- Use case ends.
- *b. At any time, 120 seconds lapse without any input from the User.
- *b1. OBS cancels the transfer.
- *b2. OBS informs the User of the cancellation.
- Use case ends.
- 3a. OBS detects an error in the entered data.
Note that the numbering style is not a universal rule but a widely used convention. Based on that convention,
- either of the extensions marked
3a.
and3b.
can happen just after step3
of the MSS. - the extension marked as
*a.
can happen at any step (hence, the*
).
When separating extensions from the MSS, keep in mind that the MSS should be self-contained. That is, the MSS should give us a complete usage scenario.
Also note that it is not useful to mention events such as power failures or system crashes as extensions because the system cannot function beyond such catastrophic failures.
In use case diagrams you can use the <<extend>>
arrows to show extensions. Note the direction of the arrow is from the extension to the use case it extends and the arrow uses a dashed line.
A use case can include another use case. Underlined text is commonly used to show an inclusion of a use case.
This use case includes two other use cases, one in step 1 and one in step 2.
- Software System: LearnSys
- Use case: UC01 - Conduct Survey
- Actors: Staff, Student
- MSS:
- Staff creates the survey (UC44).
- Student completes the survey (UC50).
- Staff views the survey results.
Use case ends.
Inclusions are useful,
- when you don't want to clutter a use case with too many low-level steps.
- when a set of steps is repeated in multiple use cases.
We use a dotted arrow and a <<include>>
annotation to show use case inclusions in a use case diagram. Note how the arrow direction is different from the <<extend>>
arrows.
Preconditions specify the specific state we expect the system to be in before the use case starts.
- Software System: Online Banking System
- Use case: UC23 - Transfer Money
- Actor: User
- Preconditions: User is logged in.
- MSS:
- User chooses to transfer money.
- OBS requests for details for the transfer.
- ...
Guarantees specify what the use case promises to give us at the end of its operation.
- Software System: Online Banking System
- Use case: UC23 - Transfer Money
- Actor: User
- Preconditions: User is logged in.
- Guarantees:
- Money will be deducted from the source account only if the transfer to the destination account is successful
- The transfer will not result in the account balance going below the minimum balance required.
- MSS:
- User chooses to transfer money.
- OBS requests for details for the transfer.
- ...
Complete the following use case (MSS, extensions, etc.). Note that you should not blindly follow how the existing
- System: EZ-Link machine
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- System: EZ-Link machine (those found at MRTs)
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- Preconditions: All hardware in working order.
- Guarantees: MSS → the card will be topped-up.
- MSS:
- User places the card on the reader.
- System displays card details and prompts for desired action.
- User selects top-up.
- System requests for top-up details (amount, payment option, receipt required?).
- User enters details.
- System processes cash payment (UC02) or NETS payment (UC03).
- System updates the card value.
- System indicates transaction as completed.
- If requested in step 5, system prints receipt.
- User removes the card.
- Use case ends.
- Extensions:
- *a. User removed card or other hardware error detected.
- *a1. System indicates the transaction has been aborted.
- Use case ends.
- *a. User removed card or other hardware error detected.
Notes:
- We assume that the only way to cancel a transaction is by removing the card.
- By not breaking step 4 into further steps, we avoid committing to a particular mechanism to enter data. For example, we are free to accept all data in one screen.
- In step 5, we assume that the input mechanism does not allow any incorrect data.
- System: EZ-Link machine
- Use case: UC03 process NETS payment
- Actor: EZ-Link card user
- Preconditions: A transaction requiring payment is underway.
- Guarantees: MSS → Transaction amount is transferred from user account to EZ-Link company account.
- MSS:
- System requests to insert ATM card.
- User inserts the ATM card.
- System requests for PIN.
- User enters PIN.
- System reports success.
- Use case ends.
- Extensions:
- 2a. Unacceptable ATM card (damaged or inserted wrong side up).
- ...
- 4a. Wrong PIN.
- ...
- 4b. Insufficient funds.
- ...
- *a. Connection to the NETS gateway is disrupted.
- ...
- 2a. Unacceptable ATM card (damaged or inserted wrong side up).
Note: UC02 can be written along similar lines.
Complete the following use case (MSS, extensions, etc.).
- System: LearnSys (an online Learning Management System)
- Use case: UC01 reply to post in the forum
- Actor: Student
- System: LearnSys
- Use case: UC01 reply to post in the forum
- Actor: Student
- Preconditions: Student is logged in and has permission to post in the forum. The post to which the Student replies already exists.
- MSS:
- Student chooses to reply to an existing post.
- LearnSys requests the user to enter post details.
- Student enters post details.
- Student submits the post.
- LearnSys displays the post.
- Use case ends.
- Extensions:
- *a. Internet connection goes down.
- ...
- *b. LearnSys times out
- ...
- 3a. Student chooses to ‘preview’ the post.
- 3a1. LearnSys shows a preview.
- 3a2. User chooses to go back to editing.
- Use case resumes at step 3.
- 3b. Student chooses to attach picture/file
- ...
- 3c. Student chooses to save the post as a draft.
- 3c1. LearnSys confirms draft has been saved.
- Use case ends.
- 3d. Student chooses to abort the operation.
- ...
- 4a. The post being replied to is deleted by the owner while the reply is being entered.
- ...
- 4b. Unacceptable data entered.
- ...
- *a. Internet connection goes down.
Which of these cannot appear as part of a use case description?
- a. Use case identifier
- b. Preconditions
- c. Guarantees
- d. References to another use case
- e. Main Success Scenario
- f. Performance requirements
- g. Extensions
- h. Inclusions
(f)
Explanation: Performance requirements are non-functional requirements. They are not captured in use cases.
Identify problems with this use case description.
- System: EZ-Link machine (those found at MRTs)
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- Preconditions: All hardware in working order.
- Guarantees: If MSS completes at least until step 7, the card will be topped-up.
- MSS:
- User places the card on the reader.
- System displays card details and prompts for desired action.
- User selects top-up.
- System requests for top-up details (amount, payment option, receipt required?).
- User enters details.
- System processes cash payment (UC02) or NETS payment (UC03).
- System updates the card value.
- System indicates transaction as completed.
- If requested in step 5, system prints receipt.
- User removes the card.
- Use case ends.
- Extensions:
- *a. User removed card or other hardware error detected.
- *a1. System indicates the transaction has been aborted.
- Use case ends.
- *a. User removed card or other hardware error detected.
- a. It does not consider ‘system crash’ scenario.
- b. It does not contain enough UI details.
- c. The extension given is in fact an inclusion.
- d. No post conditions are given.
- e. ‘Use case ends’ is duplicated.
None.
Explanation: Catastrophic failures such as ‘system crash’ need not be included in a use case. A use case is not supposed to contain UI details. Post conditions are optional. It is not a problem to have multiple exit points for a use case.
Evidence:
Covered by:
W4.4i
Can optimize the use of use cases
Requirements → Specifying Requirements → Use Cases →
You can use actor generalization in use case diagrams using a symbol similar to that of UML notation for inheritance.
In this example, actor Blogger
can do all the use cases the actor Guest
can do, as a result of the actor generalization relationship given in the diagram.
💡 Do not over-complicate use case diagrams by trying to include everything possible. A use case diagram is a brief summary of the use cases that is used as a starting point. Details of the use cases can be given in the use case descriptions.
Some include ‘System’ as an actor to indicate that something is done by the system itself without being initiated by a user or an external system.
The diagram below can be used to indicate that the system generates daily reports at midnight.
However, others argue that only use cases providing value to an external user/system should be shown in the use case diagram. For example, they argue that ‘view daily report’ should be the use case and generate daily report
is not to be shown in the use case diagram because it is simply something the system has to do to support the view daily report
use case.
We recommend that you follow the latter view (i.e. not to use System as a user). Limit use cases for modeling behaviors that involve an external actor.
UML is not very specific about the text contents of a use case. Hence, there are many styles for writing use cases. For example, the steps can be written as a continuous paragraph. Use cases should be easy to read. Note that there is no strict rule about writing all details of all steps or a need to use all the elements of a use case.
There are some advantages of documenting system requirements as use cases:
- Because they use a simple notation and plain English descriptions, they are easy for users to understand and give feedback.
- They decouple user intention from mechanism (note that use cases should not include UI-specific details), allowing the system designers more freedom to optimize how a functionality is provided to a user.
- Identifying all possible extensions encourages us to consider all situations that a software product might face during its operation.
- Separating typical scenarios from special cases encourages us to optimize the typical scenarios.
One of the main disadvantages of use cases is that they are not good for capturing requirements that does not involve a user interacting with the system. Hence, they should not be used as the sole means to specify requirements.
What are the advantages of using use cases (the textual form) for requirements modelling?
- a. They can be fairly detailed but still natural enough for users for users to understand and give feedback.
- b. The UI-independent nature of use case specification allows the system designers more freedom to decide how a functionality is provided to a user.
- c. Extensions encourage us to consider all situations a software product might face during its operations.
- d. They encourage us to identify and optimize the typical scenario of usage over exceptional usage scenarios.
(a) (b) (c) (d)
Which of these are correct?
- a. Use case are not very suitable for capturing non-functional requirements.
- b. Use case diagrams are less detailed than textual use cases.
- c. Use cases are better than user stories.
- d. Use cases can be expressed at different levels of abstraction.
(a)(b)(d)
Explanation: It is not correct to say one format is better than the other. It depends on the context.
Glossary
W4.4j
Can explain glossary
Requirements → Specifying Requirements → Glossary →
Glossary: A glossary serves to ensure that all stakeholders have a common understanding of the noteworthy terms, abbreviation, acronyms etc.
Here is a partial glossary from a variant of the Snakes and Ladders game:
- Conditional square: A square that specifies a specific face value which a player has to throw before his/her piece can leave the square.
- Normal square: a normal square does not have any conditions, snakes, or ladders in it.
Supplementary Requirements
W4.4k
Can explain supplementary requirements
Requirements → Specifying Requirements → Supplementary Requirements →
A supplementary requirements section can be used to capture requirements that do not fit elsewhere. Typically, this is where most
Requirements → Requirements →
There are two kinds of requirements:
- Functional requirements specify what the system should do.
- Non-functional requirements specify the constraints under which system is developed and operated.
Some examples of non-functional requirement categories:
- Data requirements e.g. size,
volatility ,persistency etc., - Environment requirements e.g. technical environment in which system would operate or need to be compatible with.
- Accessibility, Capacity, Compliance with regulations, Documentation, Disaster recovery, Efficiency, Extensibility, Fault tolerance, Interoperability, Maintainability, Privacy, Portability, Quality, Reliability, Response time, Robustness, Scalability, Security, Stability, Testability, and more ...
- Business/domain rules: e.g. the size of the minefield cannot be smaller than five.
- Constraints: e.g. the system should be backward compatible with data produced by earlier versions of the system; system testers are available only during the last month of the project; the total project cost should not exceed $1.5 million.
- Technical requirements: e.g. the system should work on both 32-bit and 64-bit environments.
- Performance requirements: e.g. the system should respond within two seconds.
- Quality requirements: e.g. the system should be usable by a novice who has never carried out an online purchase.
- Process requirements: e.g. the project is expected to adhere to a schedule that delivers a feature set every one month.
- Notes about project scope: e.g. the product is not required to handle the printing of reports.
- Any other noteworthy points: e.g. the game should not use images deemed offensive to those injured in real mine clearing activities.
We may have to spend an extra effort in digging NFRs out as early as possible because,
- NFRs are easier to miss e.g., stakeholders tend to think of functional requirements first
- sometimes NFRs are critical to the success of the software. E.g. A web application that is too slow or that has low security is unlikely to succeed even if it has all the right functionality.
Given below are some requirements of TEAMMATES (an online peer evaluation system for education). Which one of these are non-functional requirements?
- a. The response to any use action should become visible within 5 seconds.
- b. The application admin should be able to view a log of user activities.
- c. The source code should be open source.
- d. A course should be able to have up to 2000 students.
- e. As a student user, I can view details of my team members so that I can know who they are.
- f. The user interface should be intuitive enough for users who are not IT-savvy.
- g. The product is offered as a free online service.
(a)(c)(d)(f)(g)
Explanation: (b) are (e) are functions available for a specific user types. Therefore, they are functional requirements. (a), (c), (d), (f) and (g) are either constraints on functionality or constraints on how the project is done, both of which are considered non-functional requirements.
OOP
W4.5
Can explain basic OOP concepts
W4.5a
Can describe OOP at a higher level :
Paradigms → Object Oriented Programming → Introduction →
Object-Oriented Programming (OOP) is a programming paradigm. A programming paradigm guides programmers to analyze programming problems, and structure programming solutions, in a specific way.
Programming languages have traditionally divided the world into two parts—data and operations on data. Data is static and immutable, except as the operations may change it. The procedures and functions that operate on data have no lasting state of their own; they’re useful only in their ability to affect data.
This division is, of course, grounded in the way computers work, so it’s not one that you can easily ignore or push aside. Like the equally pervasive distinctions between matter and energy and between nouns and verbs, it forms the background against which we work. At some point, all programmers—even object-oriented programmers—must lay out the data structures that their programs will use and define the functions that will act on the data.
With a procedural programming language like C, that’s about all there is to it. The language may offer various kinds of support for organizing data and functions, but it won’t divide the world any differently. Functions and data structures are the basic elements of design.
Object-oriented programming doesn’t so much dispute this view of the world as restructure it at a higher level. It groups operations and data into modular units called objects and lets you combine objects into structured networks to form a complete program. In an object-oriented programming language, objects and object interactions are the basic elements of design.
Some other examples of programming paradigms are:
Paradigm | Programming Languages |
---|---|
Procedural Programming paradigm | C |
Functional Programming paradigm | F#, Haskel, Scala |
Logic Programming paradigm | Prolog |
Some programming languages support multiple paradigms.
Java is primarily an OOP language but it supports limited forms of functional programming and it can be used to (although not recommended) write procedural code. e.g. se-edu/addressbook-level1
JavaScript and Python support functional, procedural, and OOP programming.
A) Choose the correct statements
- a. OO is a programming paradigm
- b. OO guides us in how to structure the solution
- c. OO is mainly an abstraction mechanism
- d. OO is a programming language
- e. OO is modeled after how the objects in real world work
B) Choose the correct statements
- a. Java and C++ are OO languages
- b. C language follows the Functional Programming paradigm
- c. Java can be used to write procedural code
- d. Prolog follows the Logic Programming paradigm
A) (a)(b)(c)(e)
Explanation: While many languages support the OO paradigm, OO is not a language itself.
B) Choose the correct statement
(a)(b)(c)(d)
Explanation: C follows the procedural paradigm. Yes, we can write procedural code using OO languages e.g., AddressBook-level1.
OO is a higher level mechanism than the procedural paradigm.
True.
Explanation: Procedural languages work at simple data structures (e.g., integers, arrays) and functions level. Because an object is an abstraction over data+related functions, OO works at a higher level.
W4.5b
Can describe how OOP relates to the real world :
Paradigms → Object Oriented Programming → Objects →
Every object has both state (data) and behavior (operations on data). In that, they’re not much different from ordinary physical objects. It’s easy to see how a mechanical device, such as a pocket watch or a piano, embodies both state and behavior. But almost anything that’s designed to do a job does, too. Even simple things with no moving parts such as an ordinary bottle combine state (how full the bottle is, whether or not it’s open, how warm its contents are) with behavior (the ability to dispense its contents at various flow rates, to be opened or closed, to withstand high or low temperatures).
It’s this resemblance to real things that gives objects much of their power and appeal. They can not only model components of real systems, but equally as well fulfill assigned roles as components in software systems.
Object Oriented Programming (OOP) views the world as a network of interacting objects.
A real world scenario viewed as a network of interacting objects:
You are asked to find out the average age of a group of people Adam, Beth, Charlie, and Daisy. You take a piece of paper and pen, go to each person, ask for their age, and note it down. After collecting the age of all four, you enter it into a calculator to find the total. And then, use the same calculator to divide the total by four, to get the average age. This can be viewed as the objects You
, Pen
, Paper
, Calculator
, Adam
, Beth
, Charlie
, and Daisy
interacting to accomplish the end result of calculating the average age of the four persons. These objects can be considered as connected in a certain network of certain structure.
OOP solutions try to create a similar object network inside the computer’s memory – a sort of a virtual simulation of the corresponding real world scenario – so that a similar result can be achieved programmatically.
OOP does not demand that the virtual world object network follow the real world exactly.
Our previous example can be tweaked a bit as follows:
- Use an object called
Main
to represent your role in the scenario. - As there is no physical writing involved, we can replace the
Pen
andPaper
with an object calledAgeList
that is able to keep a list of ages.
Every object has both state (data) and behavior (operations on data).
Object | Real World? | Virtual World? | Example of State (i.e. Data) | Examples of Behavior (i.e. Operations) |
---|---|---|---|---|
Adam | Name, Date of Birth | Calculate age based on birthday | ||
Pen | - | Ink color, Amount of ink remaining | Write | |
AgeList | - | Recorded ages | Give the number of entries, Accept an entry to record | |
Calculator | Numbers already entered | Calculate the sum, divide | ||
You/Main | Average age, Sum of ages | Use other objects to calculate |
Every object has an interface and an implementation.
Every real world object has:
- an interface that other objects can interact with
- an implementation that supports the interface but may not be accessible to the other object
The interface and implementation of some real-world objects in our example:
- Calculator: the buttons and the display are part of the interface; circuits are part of the implementation.
- Adam: In the context of our 'calculate average age' example, the interface of Adam consists of requests that adam will respond to, e.g. "Give age to the nearest year, as at Jan 1st of this year" "State your name"; the implementation includes the mental calculation Adam uses to calculate the age which is not visible to other objects.
Similarly, every object in the virtual world has an interface and an implementation.
The interface and implementation of some virtual-world objects in our example:
Adam
: the interface might have a methodgetAge(Date asAt)
; the implementation of that method is not visible to other objects.
Objects interact by sending messages.
Both real world and virtual world object interactions can be viewed as objects sending message to each other. The message can result in the sender object receiving a response and/or the receiving object’s state being changed. Furthermore, the result can vary based on which object received the message, even if the message is identical (see rows 1 and 2 in the example below).
Examples:
World | Sender | Receiver | Message | Response | State Change |
---|---|---|---|---|---|
Real | You | Adam | "What is your name?" | "Adam" | - |
Real | as above | Beth | as above | "Beth" | - |
Real | You | Pen | Put nib on paper and apply pressure | Makes a mark on your paper | Ink level goes down |
Virtual | Main | Calculator (current total is 50) | add(int i): int i = 23 | 73 | total = total + 23 |
Consider the following real-world scenario.
Tom read a Software Engineering textbook (he has been assigned to read the book) and highlighted some of the text in it.
Explain the following statements about OOP using the above scenario as an example.
- Object Oriented Programming (OOP) views the world as a network of interacting objects.
- Every object has both state (data) and behavior (operations on data).
- Every object has an interface and an implementation.
- Objects interact by sending messages.
- OOP does not demand that the virtual world object network follow the real world exactly.
[1] Object Oriented Programming (OOP) views the world as a network of interacting objects.
Interacting objects in the scenario: Tom
, SE Textbook
(Book
for short), Text
, (possibly) Highlighter
💡 objects usually match nouns in the description
[2]Every object has both state (data) and behavior (operations on data).
Object | Examples of state | Examples of behavior |
---|---|---|
Tom |
memory of the text read | read |
Book |
title | show text |
Text |
font size | get highlighted |
[3] Every object has an interface and an implementation.
- Interface of an object consists of how other objects interact with it i.e., what other objects can do to that object
- Implementation consist of internals of the object that facilitate the interactions but not visible to other objects.
Object | Examples of interface | Examples of implementation |
---|---|---|
Tom |
receive reading assignment | understand/memorize the text read, remember the reading assignment |
Book |
show text, turn page | how pages are bound to the spine |
Text |
read | how characters/words are connected together or fixed to the book |
[4] Objects interact by sending messages.
Examples:
Tom
sends messageturn page
to theBook
Tom
sends messageshow text
to theBook
. When theBook
shows theText
,Tom
sends the messageread
to theText
which returns the text content toTom
.Tom
sends messagehighlight
to theHighlighter
while specifying whichText
to highlight. Then theHighlighter
sends the messagehighlight
to the specifiedText
.
[5] OOP does not demand that the virtual world object network follow the real world exactly.
Examples:
- A virtual world simulation of the above scenario can omit the
Highlighter
object. Instead, we can teachText
to highlight themselves when requested.
Evidence:
Consider the following real-world scenario.
Tom read a Software Engineering textbook (he has been assigned to read the book) and highlighted some of the text in it.
Explain the following statements about OOP using the above scenario as an example.
- Object Oriented Programming (OOP) views the world as a network of interacting objects.
- Every object has both state (data) and behavior (operations on data).
- Every object has an interface and an implementation.
- Objects interact by sending messages.
- OOP does not demand that the virtual world object network follow the real world exactly.
[1] Object Oriented Programming (OOP) views the world as a network of interacting objects.
Interacting objects in the scenario: Tom
, SE Textbook
(Book
for short), Text
, (possibly) Highlighter
💡 objects usually match nouns in the description
[2]Every object has both state (data) and behavior (operations on data).
Object | Examples of state | Examples of behavior |
---|---|---|
Tom |
memory of the text read | read |
Book |
title | show text |
Text |
font size | get highlighted |
[3] Every object has an interface and an implementation.
- Interface of an object consists of how other objects interact with it i.e., what other objects can do to that object
- Implementation consist of internals of the object that facilitate the interactions but not visible to other objects.
Object | Examples of interface | Examples of implementation |
---|---|---|
Tom |
receive reading assignment | understand/memorize the text read, remember the reading assignment |
Book |
show text, turn page | how pages are bound to the spine |
Text |
read | how characters/words are connected together or fixed to the book |
[4] Objects interact by sending messages.
Examples:
Tom
sends messageturn page
to theBook
Tom
sends messageshow text
to theBook
. When theBook
shows theText
,Tom
sends the messageread
to theText
which returns the text content toTom
.Tom
sends messagehighlight
to theHighlighter
while specifying whichText
to highlight. Then theHighlighter
sends the messagehighlight
to the specifiedText
.
[5] OOP does not demand that the virtual world object network follow the real world exactly.
Examples:
- A virtual world simulation of the above scenario can omit the
Highlighter
object. Instead, we can teachText
to highlight themselves when requested.
W4.5c
Can explain the relationship between classes and objects :
Paradigms → Object Oriented Programming → Classes →
Writing an OOP program is essentially writing instructions that the computer uses to,
- create the virtual world of object network, and
- provide it the inputs to produce the outcome we want.
A class contains instructions for creating a specific kind of objects. It turns out sometimes multiple objects have the same behavior because they are of the same kind. Instructions for creating a one kind (or ‘class’) of objects can be done once and that same instructions can be used to
Classes and objects in an example scenario
Consider the example of writing an OOP program to calculate the average age of Adam, Beth, Charlie, and Daisy.
Instructions for creating objects Adam
, Beth
, Charlie
, and Daisy
will be very similar because they are all of the same kind : they all represent ‘persons’ with the same interface, the same kind of data (i.e. name
, DoB
, etc.), and the same kind of behavior (i.e. getAge(Date)
, getName()
, etc.). Therefore, we can have a class called Person
containing instructions on how to create Person
objects and use that class to instantiate objects Adam
, Beth
, Charlie
, and Daisy
.
Similarly, we need classes AgeList
, Calculator
, and Main
classes to instantiate one each of AgeList
, Calculator
, and Main
objects.
Class | Objects |
---|---|
Person |
objects representing Adam, Beth, Charlie, Daisy |
AgeList |
an object to represent the age list |
Calculator |
an object to do the calculations |
Main |
an object to represent you who manages the whole operation |
Consider the following scenario. If you were to simulate this in an OOP program, what are the classes and the objects you would use?
Class | Objects |
---|---|
Customer |
john |
Book |
LoTR , GoT |
Cheque |
checqueJohnGave |
Cashier |
peter |
Assume you are writing a CLI program called CityConnect
for storing and querying distances between cities. The behavior is as follows:
Welcome to CityConnect!
Enter command: addroute Clementi BuonaVista 12
Route from Clementi to BuonaVista with distance 12km added
Enter command: getdistance Clementi BuonaVista
Distance from Clementi to BuonaVista is 12
Enter command: getdistance Clementi JurongWest
No route exists from Clementi to JurongWest!
Enter command: addroute Clementi JurongWest 24
Route from Clementi to JurongWest with distance 24km added
Enter command: getdistance Clementi JurongWest
Distance from Clementi to JurongWest is 24
Enter command: exit
What classes would you have in your code if you write your program based on the OOP paradigm?
One class you can have is Route
Evidence:
Consider the following scenario. If you were to simulate this in an OOP program, what are the classes and the objects you would use?
Class | Objects |
---|---|
Customer |
john |
Book |
LoTR , GoT |
Cheque |
checqueJohnGave |
Cashier |
peter |
W4.5d
Can explain the abstraction aspect of OOP :
Paradigms → Object Oriented Programming → Objects →
The concept of Objects in OOP is an
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.
We can deal with a Person
object that represents the person Adam and query the object for Adam's age instead of dealing with details such as Adam’s date of birth (DoB), in what format the DoB is stored, the algorithm used to calculate the age from the DoB, etc.
W4.5e
Can explain the encapsulation aspect of OOP :
Paradigms → Object Oriented Programming → Objects →
Encapsulation protects an implementation from unintended actions and from inadvertent access.
-- Object-Oriented Programming with Objective-C, Apple
An object is an encapsulation of some data and related behavior in two aspects:
1. The packaging aspect: An object packages data and related behavior together into one self-contained unit.
2. The information hiding aspect: The data in an object is hidden from the outside world and are only accessible using the object's interface.
Choose the correct statements
- a. An object is an encapsulation because it packages data and behavior into one bundle.
- b. An object is an encapsulation because it lets us think in terms of higher level concepts such as Students rather than student-related functions and data separately.
Don't confuse encapsulation with abstraction.
Choose the correct statement
(a)
Explanation: The second statement should be: An object is an abstraction encapsulation because it lets ...
W4.6
Can use Java enumerations
W4.6a
Can explain the meaning of enumerations :
Paradigms → Object Oriented Programming → Classes →
An Enumeration is a fixed set of values that can be considered as a data type. An enumeration is often useful when using a regular data type such as int
or String
would allow invalid values to be assigned to a variable. You are recommended to enumeration types any time you need to represent a fixed set of constants.
Suppose you want a variable to store the priority of something. There are only three priority levels: high, medium, and low. You can declare the variable as of type int
and use only values 2
, 1
, and 0
to indication the three priority levels. However, this opens the possibility of an invalid values such as 9
to be assigned to it. But if you define an enumeration type called Priority
that has three values HIGH
, MEDIUM
, LOW
only, a variable of type Priority
will never be assigned an invalid value because the compiler is able to catch such an error.
Priority
: HIGH
, MEDIUM
, LOW
Evidence:
Show (in UML notation) an enumeration called WeekDay
to use when the value can only be Monday
... Friday
.
W4.6b
Can use Java enumerations :
C++ to Java → Miscellaneous Topics →
You can define an enum type by using the enum
keyword. Because they are constants, the names of an enum type's fields are in uppercase letters e.g., FLAG_SUCCESS
.
Defining an enumeration to represent days of a week (code to be put in the Day.java
file):
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Some examples of using the Day
enumeration defined above:
Day today = Day.MONDAY;
Day[] holidays = new Day[]{Day.SATURDAY, Day.SUNDAY};
switch (today) {
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend");
break;
default:
System.out.println("It's a week day");
}
Note that while enumerations are usually a simple set of fixed values, Java enumerations can have behaviors too, as explained in this tutorial from -- Java Tutorial
Define an enumeration named Priority
. Add the missing describe
method to the code below so that it produces the output given.
public class Main {
// Add your method here
public static void main(String[] args) {
describe("Red", Priority.HIGH);
describe("Orange", Priority.MEDIUM);
describe("Blue", Priority.MEDIUM);
describe("Green", Priority.LOW);
}
}
Red indicates high priority
Orange indicates medium priority
Blue indicates medium priority
Green indicates low priority
Use a switch
statement to select between possible values for Priority
.
public static void describe(String color, Priority p) {
switch (p) {
case LOW:
System.out.println(color + " indicates low priority");
break;
// ...
}
}
Code for the enumeration is given below:
public enum Priority {
HIGH, MEDIUM, LOW
}
Evidence:
null
W4.7
Can implement class-level members
W4.7a
Can explain class-level members :
Paradigms → Object Oriented Programming → Classes →
While all objects of a class has the same attributes, each object has its own copy of the attribute value.
All Person
objects have the Name
attribute but the value of that attribute varies between Person
objects.
However, some attributes are not suitable to be maintained by individual objects. Instead, they should be maintained centrally, shared by all objects of the class. They are like ‘global variables’ but attached to a specific class. Such variables whose value is shared by all instances of a class are called class-level attributes.
The attribute totalPersons
should be maintained centrally and shared by all Person
objects rather than copied at each Person
object.
Similarly, when a normal method is being called, a message is being sent to the receiving object and the result may depend on the receiving object.
Sending the getName()
message to Adam
object results in the response "Adam"
while sending the same message to the Beth
object gets the response "Beth"
.
However, there can be methods related to a specific class but not suitable for sending message to a specific object of that class. Such methods that are called using the class instead of a specific instance are called class-level methods.
The method getTotalPersons()
is not suitable to send to a specific Person
object because a specific object of the Person
class should not know about the total number of Person
objects.
Class-level attributes and methods are collectively called class-level members (also called static members sometimes because some programming languages use the keyword static
to identify class-level members). They are to be accessed using the class name rather than an instance of the class.
Which of these are suitable as class-level variables?
- a. system: multi-player Pac Man game, Class:
Player
, variable:totalScore
- b. system: eLearning system, class:
Course
, variable:totalStudents
- c. system: ToDo manager, class:
Task
, variable:totalPendingTasks
- d. system: any, class:
ArrayList
, variable:total
(i.e., total items in a givenArrayList
object)
(c)
Explanation: totalPendingTasks
should not be managed by individual Task
objects and therefore suitable to be maintained as a class-level variable. The other variables should be managed at instance level as their value varies from instance to instance. e.g., totalStudents
for one Course
object will differ from totalStudents
of another.
W4.8
Can implement inheritance
W4.8a
Can explain the meaning of inheritance :
Paradigms → Object Oriented Programming → Inheritance →
The OOP concept Inheritance allows you to define a new class based on an existing class.
For example, you can use inheritance to define an EvaluationReport
class based on an existing Report
class so that the EvaluationReport
class does not have to duplicate code that is already implemented in the Report
class. The EvaluationReport
can inherit the wordCount
attribute and the print()
method from the base class Report
.
- Other names for Base class: Parent class, Super class
- Other names for Derived class: Child class, Sub class, Extended class
A superclass is said to be more general than the subclass. Conversely, a subclass is said to be more specialized than the superclass.
Applying inheritance on a group of similar classes can result in the common parts among classes being extracted into more general classes.
Man
and Woman
behaves the same way for certain things. However, the two classes cannot be simply replaced with a more general class Person
because of the need to distinguish between Man
and Woman
for certain other things. A solution is to add the Person
class as a superclass (to contain the code common to men and woment) and let Man
and Woman
inherit from Person
class.
Inheritance implies the derived class can be considered as a sub-type of the base class (and the base class is a super-type of the derived class), resulting in an is a relationship.
Inheritance does not necessarily mean a sub-type relationship exists. However, the two often go hand-in-hand. For simplicity, at this point let us assume inheritance implies a sub-type relationship.
To continue the previous example,
Woman
is aPerson
Man
is aPerson
Inheritance relationships through a chain of classes can result in inheritance hierarchies (aka inheritance trees).
Two inheritance hierarchies/trees are given below. Note that the triangle points to the parent class. Observe how the Parrot
is a Bird
as well as it is an Animal
.
Multiple Inheritance is when a class inherits directly from multiple classes. Multiple inheritance among classes is allowed in some languages (e.g., Python, C++) but not in other languages (e.g., Java, C#).
The Honey
class inherits from the Food
class and the Medicine
class because honey can be consumed as a food as well as a medicine (in some oriental medicine practices). Similarly, a Car
is an Vehicle
, an Asset
and a Liability
.
Which of these are correct?
- a. Superclass is more general than the subclass.
- b. Child class is more specialized than the parent class.
- c. A class can inherit behavior from its ancestor classes (ancestor classes = classes above it in the inheritance hierarchy).
- d. Code reuse can be one benefit of inheritance.
- e. A change to the superclass will not affect its subclasses.
(a) (b) (c) (d)
Explanation: (e) is incorrect. Because subclasses inherit behavior from the superclass, any changes to the superclass could affect subclasses.
W4.9
Can use basic OOP techniques in Java
Please refer to the relevant sections of the C++ to Java chapter of the Textbook for help on using Java.
Implementation
W4.10
Can do exception handling
W4.10a
Can explain error handling :
Implementation → Error Handling → Introduction →
Well-written applications include error-handling code that allows them to recover gracefully from unexpected errors. When an error occurs, the application may need to request user intervention, or it may be able to recover on its own. In extreme cases, the application may log the user off or shut down the system. --Microsoft
W4.10b
Can explain exceptions :
Implementation → Error Handling → Exceptions →
Exceptions are used to deal with 'unusual' but not entirely unexpected situations that the program might encounter at run time.
Exception:
The term exception is shorthand for the phrase "exceptional event." An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. –- Java Tutorial (Oracle Inc.)
Examples:
- A network connection encounters a timeout due to a slow server.
- The code tries to read a file from the hard disk but the file is corrupted and cannot be read.
W4.10c
Can explain Java Exceptions :
C++ to Java → Exceptions →
Given below is an extract from the -- Java Tutorial, with some adaptations.
There are three basic categories of exceptions In Java:
- Checked exceptions: exceptional conditions that a well-written application should anticipate and recover from. All exceptions are checked exceptions, except for
Error
,RuntimeException
, and their subclasses.
Suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader
object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException
. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.
- Errors: exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. Errors are those exceptions indicated by
Error
and its subclasses.
Suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError
. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.
- Runtime exceptions: conditions that are internal to the application, and that the application usually cannot anticipate or recover from. Runtime exceptions are those indicated by
RuntimeException
and its subclasses. These usually indicate programming bugs, such as logic errors or improper use of an API.
Consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException
. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.
Errors and runtime exceptions are collectively known as unchecked exceptions.
W4.10d
Can explain how exception handling is done typically :
Implementation → Error Handling → Exceptions →
Most languages allow code that encountered an "exceptional" situation to encapsulate details of the situation in an Exception object and throw/raise that object so that another piece of code can catch it and deal with it. This is especially useful when the code that encountered the unusual situation does not know how to deal with it.
The extract below from the -- Java Tutorial (with slight adaptations) explains how exceptions are typically handled.
When an error occurs at some point in the execution, the code being executed creates an exception object and hands it off to the runtime system. The exception object contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it in the
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the program terminates.
Advantages of exception handling in this way:
- The ability to propagate error information through the call stack.
- The separation of code that deals with 'unusual' situations from the code that does the 'usual' work.
Which are benefits of exceptions?
- a. Exceptions allow us to separate normal code from error handling code.
- b. Exceptions can prevent problems that happen in the environment.
- c. Exceptions allow us to handle in one location an error raised in another location.
(a) (c)
Explanation: Exceptions cannot prevent problems in the environment. They can only be used to handle and recover from such problems.
Evidence:
Acceptable: Some code you wrote that involves exception handling.
Suggested: Do the exercise in addressbook-level2: LO-Exceptions.
W4.10e
Can use Java Exceptions :
C++ to Java → Exceptions →
The content below uses extracts from the -- Java Tutorial, with some adaptations.
A program can catch exceptions by using a combination of the try
, catch
blocks.
- The
try
block identifies a block of code in which an exception can occur. - The
catch
block identifies a block of code, known as an exception handler, that can handle a particular type of exception.
The writeList()
method below calls a method process()
that can cause two type of exceptions. It uses a try-catch construct to deal with each exception.
public void writeList() {
print("starting method");
try {
print("starting process");
process();
print("finishing process");
} catch (IndexOutOfBoundsException e) {
print("caught IOOBE");
} catch (IOException e) {
print("caught IOE");
}
print("finishing method");
}
Some possible outputs:
No exceptions | IOException |
IndexOutOfBoundsException |
---|---|---|
starting method starting process finishing process finishing method |
starting method starting process caught IOE finishing method |
starting method starting process caught IOOBE finishing method |
You can use a finally
block to specify code that is guaranteed to execute with or without the exception. This is the right place to close files, recover resources, and otherwise clean up after the code enclosed in the try
block.
The writeList()
method below has a finally
block:
public void writeList() {
print("starting method");
try {
print("starting process");
process();
print("finishing process");
} catch (IndexOutOfBoundsException e) {
print("caught IOOBE");
} catch (IOException e) {
print("caught IOE");
} finally {
// clean up
print("cleaning up");
}
print("finishing method");
}
Some possible outputs:
No exceptions | IOException |
IndexOutOfBoundsException |
---|---|---|
starting method starting process finishing process cleaning up finishing method |
starting method starting process caught IOE cleaning up finishing method |
starting method starting process caught IOOBE cleaning up finishing method |
-
The
try
statement should contain at least onecatch
block or a finally block and may have multiplecatch
blocks. -
The class of the exception object indicates the type of exception thrown. The exception object can contain further information about the error, including an error message.
You can use the throw
statement to throw an exception. The throw statement requires a
Here's an example of a throw
statement.
if (size == 0) {
throw new EmptyStackException();
}
In Java, Checked exceptions are subject to the Catch or Specify Requirement: code that might throw checked exceptions must be enclosed by either of the following:
- A
try
statement that catches the exception. Thetry
must provide a handler for the exception. - A method that specifies that it can throw the exception. The method must provide a
throws
clause that lists the exception.
Unchecked exceptions are not required to follow to the Catch or Specify Requirement but you can apply the requirement to them too.
Here's an example of a method specifying that it throws certain checked exceptions:
public void writeList() throws IOException, IndexOutOfBoundsException {
print("starting method");
process();
print("finishing method");
}
Some possible outputs:
No exceptions | IOException |
IndexOutOfBoundsException |
---|---|---|
starting method finishing method |
starting method |
starting method |
Java comes with a collection of built-in exception classes that you can use. When they are not enough, it is possible to create your own exception classes.
The Main
class below parses a string descriptor of a rectangle of the format "WIDTHxHEIGHT"
e.g., "3x4"
and prints the area of the rectangle.
public class Main {
public static void printArea(String descriptor){
//TODO: modify the code below
System.out.println(descriptor + "=" + calculateArea(descriptor));
}
private static int calculateArea(String descriptor) {
//TODO: modify the code below
String[] dimensions = descriptor.split("x");
return Integer.parseInt(dimensions[0]) * Integer.parseInt(dimensions[1]);
}
public static void main(String[] args) {
printArea("3x4");
printArea("5x5");
}
}
3x4=12
5x5=25
-
Update the code of
printArea
to print an error message ifWIDTH
and/orHEIGHT
are not numbers e.g.,"Ax4"
💡calculateArea
will throw the unchecked exceptionNumberFormatException
if the code tries to parse a non-number to an integer. -
Update the code of
printArea
to print an error message if the descriptor is missingWIDTH
and/orHEIGHT
e.g.,"x4"
💡calculateArea
will throw the unchecked exceptionIndexOutOfBoundsException
if one or both dimensions are missing. -
Update the code of
calculateArea
to throw the checked exceptionIllegalShapeException
if there are more than 2 dimensions e.g.,"5x4x3"
and update theprintArea
to print an error message for those cases. Here is the code for theIllegalShapeException.java
public class IllegalShapeException extends Exception {
//no other code needed
}
Here is the expected behavior after you have done the above changes:
public class Main {
//...
public static void main(String[] args) {
printArea("3x4");
printArea("3xy");
printArea("3x");
printArea("3");
printArea("3x4x5");
}
}
3x4=12
WIDTH or HEIGHT is not a number: 3xy
WIDTH or HEIGHT is missing: 3x
WIDTH or HEIGHT is missing: 3
Too many dimensions: 3x4x5
public class Main {
public static void printArea(String descriptor){
try {
System.out.println(descriptor + "=" + calculateArea(descriptor));
} catch (NumberFormatException e) {
System.out.println("WIDTH or HEIGHT is not a number: " + descriptor);
} // add more catch blocks here
}
private static int calculateArea(String descriptor) throws IllegalShapeException {
String[] dimensions = descriptor.split("x");
//throw IllegalShapeException here if dimensions.length > 2
return Integer.parseInt(dimensions[0]) * Integer.parseInt(dimensions[1]);
}
}
This exercise continues from the TaskManager Level 1-2
exercises quoted above.
Enhance the TaskManager to print an error message if a command is missing parts. Use exceptions so that error detection and printing of error message happen at different places of code and the error information is passed between the two places using an Exception object.
Here is an example output:
Welcome to TaskManager-Level3!
Your task? todo
Error: Empty description for TODO
Your task? todo read book
Tasks in the list: 1
Your task? print
Tasks:
[1] description: read book
is done? No
Your task?
Suggested approach:
- Create a
TaskManagerException
class that inherits theException
class. Override the constructor that takes aString
parameter so that you can specify the error information when you create aTaskManagerException
object. - Throw a new
TaskManagerException
object when you detect some necessary information is missing in the command. - Catch that exception somewhere else and print the message inside the exception object.
public class TaskManagerException extends Exception{
public TaskManagerException(String message) {
super(message);
}
}
public static void main(String[] args) {
// ...
while (!isExit) {
try {
line = getInput();
String command = line.split(" ")[0];
switch (command) {
case "todo":
addTodo(line);
break;
// ...
}
} catch (TaskManagerException e) {
printError(e.getMessage());
}
}
// ...
}
private static void addTodo(String line) throws TaskManagerException {
String description = line.substring("todo".length()).trim();
if (description.isEmpty()){
throw new TaskManagerException("Empty description for TODO");
}
// ...
}
W4.10f
Can avoid using exceptions to control normal workflow :
Quality Assurance
W4.11
Can use simple JUnit tests
W4.11a
Can explain developer testing
W4.11b
Can explain the need for early developer testing
Quality Assurance → Testing → Developer Testing →
Delaying testing until the full product is complete has a number of disadvantages:
- Locating the cause of such a test case failure is difficult due to a large search space; in a large system, the search space could be millions of lines of code, written by hundreds of developers! The failure may also be due to multiple inter-related bugs.
- Fixing a bug found during such testing could result in major rework, especially if the bug originated during the design or during requirements specification i.e. a faulty design or faulty requirements.
- One bug might 'hide' other bugs, which could emerge only after the first bug is fixed.
- The delivery may have to be delayed if too many bugs were found during testing.
Therefore, it is better to do early testing, as hinted by the popular rule of thumb given below, also illustrated by the graph below it.
The earlier a bug is found, the easier and cheaper to have it fixed.
Such early testing of partially developed software is usually, and by necessity, done by the developers themselves i.e. developer testing.
Discuss pros and cons of developers testing their own code.
Pros:
- Can be done early (the earlier we find a bug, the cheaper it is to fix).
- Can be done at lower levels, for examples, at operation and class level (testers usually test the system at UI level).
- It is possible to do more thorough testing because developers know the expected external behavior as well as the internal structure of the component.
- It forces developers to take responsibility for their own work (they cannot claim that "testing is the job of the testers").
Cons:
- A developer may subconsciously test only situations that he knows to work (i.e. test it too 'gently').
- A developer may be blind to his own mistakes (if he did not consider a certain combination of input while writing code, it is possible for him to miss it again during testing).
- A developer may have misunderstood what the SUT is supposed to do in the first place.
- A developer may lack the testing expertise.
The cost of fixing a bug goes down as we reach the product release.
False. The cost goes up over time.
Explain why early testing by developers is important.
Evidence:
Explain why early testing by developers is important.
W4.11c
Can explain test drivers
Quality Assurance → Testing → Test Automation →
A test driver is the code that ‘drives’ the
PayrollTest
‘drives’ the PayRoll
class by sending it test inputs and verifies if the output is as expected.
public class PayrollTestDriver {
public static void main(String[] args) throws Exception {
//test setup
Payroll p = new Payroll();
//test case 1
p.setEmployees(new String[]{"E001", "E002"});
// automatically verify the response
if (p.totalSalary() != 6400) {
throw new Error("case 1 failed ");
}
//test case 2
p.setEmployees(new String[]{"E001"});
if (p.totalSalary() != 2300) {
throw new Error("case 2 failed ");
}
//more tests...
System.out.println("All tests passed");
}
}
W4.11d
Can explain test automation tools
Quality Assurance → Testing → Test Automation →
JUnit is a tool for automated testing of Java programs. Similar tools are available for other languages and for automating different types of testing.
This an automated test for a Payroll
class, written using JUnit libraries.
@Test
public void testTotalSalary(){
Payroll p = new Payroll();
//test case 1
p.setEmployees(new String[]{"E001", "E002"});
assertEquals(6400, p.totalSalary());
//test case 2
p.setEmployees(new String[]{"E001"});
assertEquals(2300, p.totalSalary());
//more tests...
}
Most modern IDEs has integrated support for testing tools. The figure below shows the JUnit output when running some JUnit tests using the Eclipse IDE.
W4.11e
Can use simple JUnit tests
Tools → JUnit →
When writing JUnit tests for a class Foo
, the common practice is to create a FooTest
class, which will contain various test methods.
Suppose we want to write tests for the IntPair
class below.
public class IntPair {
int first;
int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public int intDivision() throws Exception {
if (second == 0){
throw new Exception("Divisor is zero");
}
return first/second;
}
@Override
public String toString() {
return first + "," + second;
}
}
Here's a IntPairTest
class to match.
import org.junit.Test;
import org.junit.Assert;
public class IntPairTest {
@Test
public void testStringConversion() {
Assert.assertEquals("4,7", new IntPair(4, 7).toString());
}
@Test
public void intDivision_nonZeroDivisor_success() throws Exception {
Assert.assertEquals(2, new IntPair(4, 2).intDivision());
Assert.assertEquals(0, new IntPair(1, 2).intDivision());
Assert.assertEquals(0, new IntPair(0, 5).intDivision());
}
@Test
public void intDivision_zeroDivisor_exceptionThrown() {
try {
Assert.assertEquals(0, new IntPair(1, 0).intDivision());
Assert.fail(); // the test should not reach this line
} catch (Exception e) {
Assert.assertEquals("Divisor is zero", e.getMessage());
}
}
}
Notes:
- Each test method is marked with a
@Test
annotation. - Tests use
Assert.assertEquals(expected, actual)
methods to compare the expected output with the actual output. If they do not match, the test will fail. JUnit comes with other similar methods such asAssert.assertNull
andAssert.assertTrue
. - Java code normally use camelCase for method names e.g.,
testStringConversion
but when writing test methods, sometimes another convention is used:whatIsBeingTested_descriptionOfTestInputs_expectedOutcome
e.g.,intDivision_zeroDivisor_exceptionThrown
- There are several ways to verify the code throws the correct exception. The third test method in the example above shows one of the simpler methods. If the exception is thrown, it will be caught and further verified inside the
catch
block. But if it is not thrown as expected, the test will reachAssert.fail()
line and will fail as a result. - The easiest way to run JUnit tests is to do it via the IDE. For example, in Intellij you can right-click the folder containing test classes and choose 'Run all tests...'
- Optionally, you can use static imports to avoid having to specify
Assert.
everywhere.import static org.junit.Assert.assertEquals; //... @Test public void testStringConversion() { assertEquals("4,7", new IntPair(4, 7).toString()); }
JUnit 4 with IntelliJ: A quick introduction -- by DrBFraser
- JUnit cookbook - a short tutorial from JUnit creators
- JUnit tutorial - a more detailed tutorial from a developer Lars Vogel
- How to test private methods in Java? [ short answer ] [ long answer ]
Evidence:
Acceptable: Have written JUnit tests in some project.
Suggested:
- Fork Addressbook-Level2 onto your GitHub account
- Clone the fork to your computer
- Set up the project by following its Developer Guide
- Run the JUnit tests that came with the project
- Do the exercise in [Addressbook-Level2: LO-JUnit] but read the submission instructions (given below) first.
Submission: Create a PR against Addressbook-Level2. Try to make a clean PR (i.e. free of unrelated code modifications).
🅿️ Project
W4.12
Can define requirements of a product
Covered by the below. Try to do at least step 1 before coming to the tutorial.
Tutorial 4
At this point we would like to ensure that you are able to create branch-based PRs without accidentally mixing commits between PRs (a common mistake)
Therefore, we strongly encourage you to achieve the W4.1 Can create PRs on GitHub
before coming to the tutorial.
- As before, demo/discuss evidence of achieving LOs as directed by the tutor.
W4.1a
Can explain branching
Project Management → Revision Control →
Branching is the process of evolving multiple versions of the software in parallel. For example, one team member can create a new branch and add an experimental feature to it while the rest of the team keeps working on another branch. Branches can be given names e.g. master
, release
, dev
.
A branch can be merged into another branch. Merging usually result in a new commit that represents the changes done in the branch being merged.
Merge conflicts happen when you try to merge two branches that had changed the same part of the code and the RCS software cannot decide which changes to keep. In those cases we have to ‘resolve’ those conflicts manually.
In the context of RCS, what is the branching? What is the need for branching?.
In the context of RCS, what is the merging branches? How can it lead to merge conflicts?.
Evidence:
In the context of RCS, what is the branching? What is the need for branching?.
In the context of RCS, what is the merging branches? How can it lead to merge conflicts?.
W4.1b
Can use Git branching
Tools → Git and GitHub →
0. Observe that you are normally in the branch called master
. For this, you can take any repo you have on your computer (e.g. a clone of the samplerepo-things).
git status
on branch master
1. Start a branch named feature1
and switch to the new branch.
Click on the Branch
button on the main menu. In the next dialog, enter the branch name and click Create Branch
Note how the feature1
is indicated as the current branch.
You can use the branch
command to create a new branch and the checkout
command to switch to a specific branch.
git branch feature1
git checkout feature1
One-step shortcut to create a branch and switch to it at the same time:
git checkout –b feature1
2. Create some commits in the new branch. Just commit as per normal. Commits you add while on a certain branch will become part of that branch.
3. Switch to the master
branch. Note how the changes you did in the feature1
branch are no longer in the working directory.
Double-click the master
branch
git checkout master
4. Add a commit to the master branch. Let’s imagine it’s a bug fix.
5. Switch back to the feature1
branch (similar to step 3).
6. Merge the master
branch to the feature1
branch, giving an end-result like the below. Also note how Git has created a merge commit.
Right-click on the master
branch and choose merge master into the current branch
. Click OK
in the next dialog.
git merge master
Observe how the changes you did in the master
branch (i.e. the imaginary bug fix) is now available even when you are in the feature1
branch.
7. Add another commit to the feature1
branch.
8. Switch to the master
branch and add one more commit.
9. Merge feature1
to the master branch, giving and end-result like this:
Right-click on the feature1
branch and choose Merge...
.
git merge feature1
10. Create a new branch called add-countries
, switch to it, and add some commits to it (similar to steps 1-2 above). You should have something like this now:
11. Go back to the master
branch and merge the add-countries
branch onto the master
branch (similar to steps 8-9 above). While you might expect to see something like the below,
... you are likely to see something like this instead:
That is because Git does a fast forward merge if possible. Seeing that the master
branch has not changed since you started the add-countries
branch, Git has decided it is simpler to just put the commits of the add-countries
branch in front of the master
branch, without going into the trouble of creating an extra merge commit.
It is possible to force Git to create a merge commit even if fast forwarding is possible.
Tick the box shown below when you merge a branch:
Use the --no-ff
switch (short for no fast forward):
git merge --no-ff add-countries
Evidence:
Acceptable: Git branches you have created in any repo.
Suggested: Results of following the steps in the LO.
Submission: Show your branches during the tutorial.
W4.1c
Can create PRs on GitHub
Tools → Git and GitHub →
1. Fork the samplerepo-pr-practice onto your GitHub account. Clone it onto your computer.
2. Create a branch named add-intro
in your clone. Add a couple of commits which adds/modifies an Introduction section to the README.md
. Example:
# Introduction
Creating Pull Requsts (PRs) is needed when using RCS in a multi-person projects.
This repo can be used to practice creating PRs.
3. Push the add-intro
branch to your fork.
git push origin add-intro
4. Create a Pull Request from the add-intro
branch in your fork to the master
branch of the same fork (i.e. your-user-name/samplerepo-pr-practice
, not se-edu/samplerepo-pr-practice
), as described below.
4a. Go to the GitHub page of your fork (i.e. https://github.com/{your_username}/samplerepo-pr-practice
), click on the Pull Requests
tab, and then click on New Pull Request
button.
4b. Select base fork
and head fork
as follows:
base fork
: your own fork (i.e.{your user name}/samplerepo-pr-practice
, NOTse-edu/samplerepo-pr-practice
)head fork
: your own fork.
The base fork is where changes should be applied. The head fork contains the changes you would like to be applied.
4c. (1) Set the base branch to master
and head branch to add-intro
, (2) confirm the diff contains the changes you propose to merge in this PR (i.e. confirm that you did not accidentally include extra commits in the branch), and (3) click the Create pull request
button.
4d. (1) Set PR name, (2) set PR description, and (3) Click the Create pull request
button.
A common newbie mistake when creating branch-based PRs is to mix commits of one PR with another. To learn how to avoid that mistake, you are encouraged to continue and create another PR as explained below.
5. In your local repo, create a new branch add-summary
off the master
branch.
When creating the new branch, it is very important that you switch back to the master
branch first. If not, the new branch will be created off the current branch add-intro
. And that is how you end up having commits of the first PR in the second PR as well.
6. Add a commit in the add-summary
branch that adds a Summary section to the README.md
, in exactly the same place you added the Introduction section earlier.
7. Push the add-summary
to your fork and create a new PR similar to before.
Evidence:
Acceptable: PRs created in any repo.
Suggested: PRs created by following the steps in the LO.
Submission: Show your PRs during the tutorial.
W4.4c
Can write simple user stories
Requirements → Specifying Requirements → User Stories →
User story: User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. [Mike Cohn]
A common format for writing user stories is:
User story format: As a {user type/role} I can {function} so that {benefit}
Examples (from a Learning Management System):
- As a student, I can download files uploaded by lecturers, so that I can get my own copy of the files
- As a lecturer, I can create discussion forums, so that students can discuss things online
- As a tutor, I can print attendance sheets, so that I can take attendance during the class
We can write user stories on index cards or sticky notes, and arrange on walls or tables, to facilitate planning and discussion. Alternatively, we can use a software (e.g., GitHub Project Boards, Trello, Google Docs, ...) to manage user stories digitally.
[credit: https://www.flickr.com/photos/jakuza/with/2726048607/]
[credit: https://commons.wikimedia.org/wiki/File:User_Story_Map_in_Action.png]
- a. They are based on stories users tell about similar systems
- b. They are written from the user/customer perspective
- c. They are always written in some physical medium such as index cards or sticky notes
- a. Reason: Despite the name, user stories are not related to 'stories' about the software.
- b.
- c. Reason: It is possible to use software to record user stories. When the team members are not co-located this may be the only option.
Critique the following user story taken from a software project to build an e-commerce website.
As a developer, I want to use Python to implement the software, so that we can resue existing Python modules.
Refer to the definition of a user story.
User story: User stories are short, simple descriptions of a feature told from the perspective of the person who desires the new capability, usually a user or customer of the system. [Mike Cohn]
This user story is not written from the perspective of the user/customer.
Bill wants you to build a Human Resource Management (HRM) system. He mentions that the system will help employees to view their own
Remember to follow the correct format when writing user stories.
User story format: As a {user type/role} I can {function} so that {benefit}
As an employee, I can view my leave balance, so that I can know how many leave days I have left.
Note: the {benefit}
part may vary as it is not specifically mentioned in the question.
Evidence:
Covered by:
W4.4e
Can use user stories to manage requirements of project
Requirements → Specifying Requirements → User Stories →
User stories capture user requirements in a way that is convenient for
[User stories] strongly shift the focus from writing about features to discussing them. In fact, these discussions are more important than whatever text is written. [Mike Cohn, MountainGoat Software 🔗]
User stories differ from
User stories can capture
Requirements → Requirements →
There are two kinds of requirements:
- Functional requirements specify what the system should do.
- Non-functional requirements specify the constraints under which system is developed and operated.
Some examples of non-functional requirement categories:
- Data requirements e.g. size,
volatility ,persistency etc., - Environment requirements e.g. technical environment in which system would operate or need to be compatible with.
- Accessibility, Capacity, Compliance with regulations, Documentation, Disaster recovery, Efficiency, Extensibility, Fault tolerance, Interoperability, Maintainability, Privacy, Portability, Quality, Reliability, Response time, Robustness, Scalability, Security, Stability, Testability, and more ...
- Business/domain rules: e.g. the size of the minefield cannot be smaller than five.
- Constraints: e.g. the system should be backward compatible with data produced by earlier versions of the system; system testers are available only during the last month of the project; the total project cost should not exceed $1.5 million.
- Technical requirements: e.g. the system should work on both 32-bit and 64-bit environments.
- Performance requirements: e.g. the system should respond within two seconds.
- Quality requirements: e.g. the system should be usable by a novice who has never carried out an online purchase.
- Process requirements: e.g. the project is expected to adhere to a schedule that delivers a feature set every one month.
- Notes about project scope: e.g. the product is not required to handle the printing of reports.
- Any other noteworthy points: e.g. the game should not use images deemed offensive to those injured in real mine clearing activities.
We may have to spend an extra effort in digging NFRs out as early as possible because,
- NFRs are easier to miss e.g., stakeholders tend to think of functional requirements first
- sometimes NFRs are critical to the success of the software. E.g. A web application that is too slow or that has low security is unlikely to succeed even if it has all the right functionality.
Given below are some requirements of TEAMMATES (an online peer evaluation system for education). Which one of these are non-functional requirements?
- a. The response to any use action should become visible within 5 seconds.
- b. The application admin should be able to view a log of user activities.
- c. The source code should be open source.
- d. A course should be able to have up to 2000 students.
- e. As a student user, I can view details of my team members so that I can know who they are.
- f. The user interface should be intuitive enough for users who are not IT-savvy.
- g. The product is offered as a free online service.
(a)(c)(d)(f)(g)
Explanation: (b) are (e) are functions available for a specific user types. Therefore, they are functional requirements. (a), (c), (d), (f) and (g) are either constraints on functionality or constraints on how the project is done, both of which are considered non-functional requirements.
An example of a NFR captured as a user story:
As a | I want to | so that |
---|---|---|
impatient user | to be able experience reasonable response time from the website while up to 1000 concurrent users are using it | I can use the app even when the traffic is at the maximum expected level |
Given their lightweight nature, user stories are quite handy for recording requirements during early stages of requirements gathering.
💡 Here are some tips for using user stories for early stages of requirement gathering:
- Define the target user:
Decide your target user's profile (e.g. a student, office worker, programmer, sales person) and work patterns (e.g. Does he work in groups or alone? Does he share his computer with others?). A clear understanding of the target user will help when deciding the importance of a user story. You can even give this user a name. e.g. Target user Jean is a university student studying in a non-IT field. She interacts with a lot of people due to her involvement in university clubs/societies. ... - Define the problem scope: Decide that exact problem you are going to solve for the target user. e.g. Help Jean keep track of all her school contacts
- Don't be too hasty to discard 'unusual' user stories:
Those might make your product unique and stand out from the rest, at least for the target users. - Don't go into too much details:
For example, consider this user story:As a user, I want to see a list of tasks that needs my attention most at the present time, so that I pay attention to them first.
When discussing this user story, don't worry about what tasks should be considered needs my attention most at the present time. Those details can be worked out later. - Don't be biased by preconceived product ideas:
When you are at the stage of identifying user needs, clear your mind of ideas you have about what your end product will look like. - Don't discuss implementation details or whether you are actually going to implement it:
When gathering requirements, your decision is whether the user's need is important enough for you to want to fulfil it. Implementation details can be discussed later. If a user story turns out to be too difficult to implement later, you can always omit it from the implementation plan.
While use cases can be recorded on
You can create issues for each of the user stories and use a GitHub Project Board to sort them into categories.
Example Project Board:
Example Issue to represent a user story:
A video on GitHub Project Boards:
Example Google Sheet for recording user stories:
Example Trello Board for recording user stories:
Extreme programming (XP) is a software development methodology which is intended to improve software quality and responsiveness to changing customer requirements. As a type of agile software development, it advocates frequent "releases" in short development cycles, which is intended to improve productivity and introduce checkpoints at which new customer requirements can be adopted. [wikipedia, 2017.05.01]
This page in their website explains the difference between user stories and traditional requirements.
One of the biggest misunderstandings with user stories is how they differ from traditional requirements specifications. The biggest difference is in the level of detail. User stories should only provide enough detail to make a reasonably low risk estimate of how long the story will take to implement. When the time comes to implement the story developers will go to the customer and receive a detailed description of the requirements face to face.
- This article by Mike Cohn from MountainGoatSoftware explains how to use user stories to capture NFRs.
Evidence:
Covered by the project.
W4.4h
Can specify details of a use case in a structured format
Requirements → Specifying Requirements → Use Cases →
Writing use case steps
The main body of the use case is the sequence of steps that describes the interaction between the system and the actors. Each step is given as a simple statement describing who does what.
An example of the main body of a use case.
- Student requests to upload file
- LMS requests for the file location
- Student specifies the file location
- LMS uploads the file
A use case describes only the externally visible behavior, not internal details, of a system i.e. should not mention give details that are not part of the interaction between the user and the system.
This example use case step refers to behaviors not externally visible .
- LMS saves the file into the cache and indicates success.
A step gives the intention of the actor (not the mechanics). That means UI details are usually omitted. The idea is to leave as much flexibility to the UI designer as possible. That is, the use case specification should be as general as possible (less specific) about the UI.
The first example below is not a good use case step because contains UI-specific details. The second one is better because it omits UI-specific details.
Bad : User right-clicks the text box and chooses ‘clear’
Good : User clears the input
A use case description can show loops too.
An example of how you can show a loop:
Software System: Square game
Use case:
- A Player starts the game.
- SquareGame asks for player names.
- Each Player enters his own name.
- SquareGame shows the order of play.
- SquareGame prompts for the current Player to throw die.
- Current Player adjusts the throw speed.
- Current Player triggers the die throw.
- Square Game shows the face value of the die.
- Square Game moves the Player's piece accordingly.
Steps 5-9 are repeated for each Player, and for as many rounds as required until a Player reaches the 100th square. - Square Game shows the Winner.
Use case ends.
The Main Success Scenario (MSS) describes the most straightforward interaction for a given use case, which assumes that nothing goes wrong. This is also called the Basic Course of Action or the Main Flow of Events of a use case.
- System: Online Banking System (OBS)
- Use case: UC23 - Transfer Money
- Actor: User
- MSS:
- User chooses to transfer money.
- OBS requests for details of the transfer.
- User enters the requested details.
- OBS requests for confirmation.
- OBS transfers the money and displays the new account balance.
- Use case ends.
Note how the MSS assumes that all entered details are correct and ignores problems such as timeouts, network outages etc. Fro example, MSS does not tell us what happens if the user enters an incorrect data.
Extensions are "add-on"s to the MSS that describe exceptional/alternative flow of events. They describe variations of the scenario that can happen if certain things are not as expected by the MSS. Extensions appear below the MSS.
This example adds some extensions to the use case in the previous example.
- System: Online Banking System (OBS)
- Use case: UC23 - Transfer Money
- Actor: User
- MSS:
- User chooses to transfer money.
- OBS requests for details of the transfer.
- User enters the requested details.
- OBS requests for confirmation.
- OBS transfers the money and displays the new account balance.
- Use case ends.
- Extensions:
- 3a. OBS detects an error in the entered data.
- 3a1. OBS requests for the correct data.
- 3a2. User enters new data.
- Steps 3a1-3a2 are repeated until the data entered are correct.
- Use case resumes from step 4.
- 3b. User requests to effect the transfer in a future date.
- 3b1. OBS requests for confirmation.
- 3b2. User confirms future transfer.
- Use case ends.
- *a. At any time, User chooses to cancel the transfer.
- *a1. OBS requests to confirm the cancellation.
- *a2. User confirms the cancellation.
- Use case ends.
- *b. At any time, 120 seconds lapse without any input from the User.
- *b1. OBS cancels the transfer.
- *b2. OBS informs the User of the cancellation.
- Use case ends.
- 3a. OBS detects an error in the entered data.
Note that the numbering style is not a universal rule but a widely used convention. Based on that convention,
- either of the extensions marked
3a.
and3b.
can happen just after step3
of the MSS. - the extension marked as
*a.
can happen at any step (hence, the*
).
When separating extensions from the MSS, keep in mind that the MSS should be self-contained. That is, the MSS should give us a complete usage scenario.
Also note that it is not useful to mention events such as power failures or system crashes as extensions because the system cannot function beyond such catastrophic failures.
In use case diagrams you can use the <<extend>>
arrows to show extensions. Note the direction of the arrow is from the extension to the use case it extends and the arrow uses a dashed line.
A use case can include another use case. Underlined text is commonly used to show an inclusion of a use case.
This use case includes two other use cases, one in step 1 and one in step 2.
- Software System: LearnSys
- Use case: UC01 - Conduct Survey
- Actors: Staff, Student
- MSS:
- Staff creates the survey (UC44).
- Student completes the survey (UC50).
- Staff views the survey results.
Use case ends.
Inclusions are useful,
- when you don't want to clutter a use case with too many low-level steps.
- when a set of steps is repeated in multiple use cases.
We use a dotted arrow and a <<include>>
annotation to show use case inclusions in a use case diagram. Note how the arrow direction is different from the <<extend>>
arrows.
Preconditions specify the specific state we expect the system to be in before the use case starts.
- Software System: Online Banking System
- Use case: UC23 - Transfer Money
- Actor: User
- Preconditions: User is logged in.
- MSS:
- User chooses to transfer money.
- OBS requests for details for the transfer.
- ...
Guarantees specify what the use case promises to give us at the end of its operation.
- Software System: Online Banking System
- Use case: UC23 - Transfer Money
- Actor: User
- Preconditions: User is logged in.
- Guarantees:
- Money will be deducted from the source account only if the transfer to the destination account is successful
- The transfer will not result in the account balance going below the minimum balance required.
- MSS:
- User chooses to transfer money.
- OBS requests for details for the transfer.
- ...
Complete the following use case (MSS, extensions, etc.). Note that you should not blindly follow how the existing
- System: EZ-Link machine
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- System: EZ-Link machine (those found at MRTs)
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- Preconditions: All hardware in working order.
- Guarantees: MSS → the card will be topped-up.
- MSS:
- User places the card on the reader.
- System displays card details and prompts for desired action.
- User selects top-up.
- System requests for top-up details (amount, payment option, receipt required?).
- User enters details.
- System processes cash payment (UC02) or NETS payment (UC03).
- System updates the card value.
- System indicates transaction as completed.
- If requested in step 5, system prints receipt.
- User removes the card.
- Use case ends.
- Extensions:
- *a. User removed card or other hardware error detected.
- *a1. System indicates the transaction has been aborted.
- Use case ends.
- *a. User removed card or other hardware error detected.
Notes:
- We assume that the only way to cancel a transaction is by removing the card.
- By not breaking step 4 into further steps, we avoid committing to a particular mechanism to enter data. For example, we are free to accept all data in one screen.
- In step 5, we assume that the input mechanism does not allow any incorrect data.
- System: EZ-Link machine
- Use case: UC03 process NETS payment
- Actor: EZ-Link card user
- Preconditions: A transaction requiring payment is underway.
- Guarantees: MSS → Transaction amount is transferred from user account to EZ-Link company account.
- MSS:
- System requests to insert ATM card.
- User inserts the ATM card.
- System requests for PIN.
- User enters PIN.
- System reports success.
- Use case ends.
- Extensions:
- 2a. Unacceptable ATM card (damaged or inserted wrong side up).
- ...
- 4a. Wrong PIN.
- ...
- 4b. Insufficient funds.
- ...
- *a. Connection to the NETS gateway is disrupted.
- ...
- 2a. Unacceptable ATM card (damaged or inserted wrong side up).
Note: UC02 can be written along similar lines.
Complete the following use case (MSS, extensions, etc.).
- System: LearnSys (an online Learning Management System)
- Use case: UC01 reply to post in the forum
- Actor: Student
- System: LearnSys
- Use case: UC01 reply to post in the forum
- Actor: Student
- Preconditions: Student is logged in and has permission to post in the forum. The post to which the Student replies already exists.
- MSS:
- Student chooses to reply to an existing post.
- LearnSys requests the user to enter post details.
- Student enters post details.
- Student submits the post.
- LearnSys displays the post.
- Use case ends.
- Extensions:
- *a. Internet connection goes down.
- ...
- *b. LearnSys times out
- ...
- 3a. Student chooses to ‘preview’ the post.
- 3a1. LearnSys shows a preview.
- 3a2. User chooses to go back to editing.
- Use case resumes at step 3.
- 3b. Student chooses to attach picture/file
- ...
- 3c. Student chooses to save the post as a draft.
- 3c1. LearnSys confirms draft has been saved.
- Use case ends.
- 3d. Student chooses to abort the operation.
- ...
- 4a. The post being replied to is deleted by the owner while the reply is being entered.
- ...
- 4b. Unacceptable data entered.
- ...
- *a. Internet connection goes down.
Which of these cannot appear as part of a use case description?
- a. Use case identifier
- b. Preconditions
- c. Guarantees
- d. References to another use case
- e. Main Success Scenario
- f. Performance requirements
- g. Extensions
- h. Inclusions
(f)
Explanation: Performance requirements are non-functional requirements. They are not captured in use cases.
Identify problems with this use case description.
- System: EZ-Link machine (those found at MRTs)
- Use case: UC2 top-up EZ-Link card
- Actor: EZ-Link card user
- Preconditions: All hardware in working order.
- Guarantees: If MSS completes at least until step 7, the card will be topped-up.
- MSS:
- User places the card on the reader.
- System displays card details and prompts for desired action.
- User selects top-up.
- System requests for top-up details (amount, payment option, receipt required?).
- User enters details.
- System processes cash payment (UC02) or NETS payment (UC03).
- System updates the card value.
- System indicates transaction as completed.
- If requested in step 5, system prints receipt.
- User removes the card.
- Use case ends.
- Extensions:
- *a. User removed card or other hardware error detected.
- *a1. System indicates the transaction has been aborted.
- Use case ends.
- *a. User removed card or other hardware error detected.
- a. It does not consider ‘system crash’ scenario.
- b. It does not contain enough UI details.
- c. The extension given is in fact an inclusion.
- d. No post conditions are given.
- e. ‘Use case ends’ is duplicated.
None.
Explanation: Catastrophic failures such as ‘system crash’ need not be included in a use case. A use case is not supposed to contain UI details. Post conditions are optional. It is not a problem to have multiple exit points for a use case.
Evidence:
Covered by:
W4.5b
Can describe how OOP relates to the real world :
Paradigms → Object Oriented Programming → Objects →
Every object has both state (data) and behavior (operations on data). In that, they’re not much different from ordinary physical objects. It’s easy to see how a mechanical device, such as a pocket watch or a piano, embodies both state and behavior. But almost anything that’s designed to do a job does, too. Even simple things with no moving parts such as an ordinary bottle combine state (how full the bottle is, whether or not it’s open, how warm its contents are) with behavior (the ability to dispense its contents at various flow rates, to be opened or closed, to withstand high or low temperatures).
It’s this resemblance to real things that gives objects much of their power and appeal. They can not only model components of real systems, but equally as well fulfill assigned roles as components in software systems.
Object Oriented Programming (OOP) views the world as a network of interacting objects.
A real world scenario viewed as a network of interacting objects:
You are asked to find out the average age of a group of people Adam, Beth, Charlie, and Daisy. You take a piece of paper and pen, go to each person, ask for their age, and note it down. After collecting the age of all four, you enter it into a calculator to find the total. And then, use the same calculator to divide the total by four, to get the average age. This can be viewed as the objects You
, Pen
, Paper
, Calculator
, Adam
, Beth
, Charlie
, and Daisy
interacting to accomplish the end result of calculating the average age of the four persons. These objects can be considered as connected in a certain network of certain structure.
OOP solutions try to create a similar object network inside the computer’s memory – a sort of a virtual simulation of the corresponding real world scenario – so that a similar result can be achieved programmatically.
OOP does not demand that the virtual world object network follow the real world exactly.
Our previous example can be tweaked a bit as follows:
- Use an object called
Main
to represent your role in the scenario. - As there is no physical writing involved, we can replace the
Pen
andPaper
with an object calledAgeList
that is able to keep a list of ages.
Every object has both state (data) and behavior (operations on data).
Object | Real World? | Virtual World? | Example of State (i.e. Data) | Examples of Behavior (i.e. Operations) |
---|---|---|---|---|
Adam | Name, Date of Birth | Calculate age based on birthday | ||
Pen | - | Ink color, Amount of ink remaining | Write | |
AgeList | - | Recorded ages | Give the number of entries, Accept an entry to record | |
Calculator | Numbers already entered | Calculate the sum, divide | ||
You/Main | Average age, Sum of ages | Use other objects to calculate |
Every object has an interface and an implementation.
Every real world object has:
- an interface that other objects can interact with
- an implementation that supports the interface but may not be accessible to the other object
The interface and implementation of some real-world objects in our example:
- Calculator: the buttons and the display are part of the interface; circuits are part of the implementation.
- Adam: In the context of our 'calculate average age' example, the interface of Adam consists of requests that adam will respond to, e.g. "Give age to the nearest year, as at Jan 1st of this year" "State your name"; the implementation includes the mental calculation Adam uses to calculate the age which is not visible to other objects.
Similarly, every object in the virtual world has an interface and an implementation.
The interface and implementation of some virtual-world objects in our example:
Adam
: the interface might have a methodgetAge(Date asAt)
; the implementation of that method is not visible to other objects.
Objects interact by sending messages.
Both real world and virtual world object interactions can be viewed as objects sending message to each other. The message can result in the sender object receiving a response and/or the receiving object’s state being changed. Furthermore, the result can vary based on which object received the message, even if the message is identical (see rows 1 and 2 in the example below).
Examples:
World | Sender | Receiver | Message | Response | State Change |
---|---|---|---|---|---|
Real | You | Adam | "What is your name?" | "Adam" | - |
Real | as above | Beth | as above | "Beth" | - |
Real | You | Pen | Put nib on paper and apply pressure | Makes a mark on your paper | Ink level goes down |
Virtual | Main | Calculator (current total is 50) | add(int i): int i = 23 | 73 | total = total + 23 |
Consider the following real-world scenario.
Tom read a Software Engineering textbook (he has been assigned to read the book) and highlighted some of the text in it.
Explain the following statements about OOP using the above scenario as an example.
- Object Oriented Programming (OOP) views the world as a network of interacting objects.
- Every object has both state (data) and behavior (operations on data).
- Every object has an interface and an implementation.
- Objects interact by sending messages.
- OOP does not demand that the virtual world object network follow the real world exactly.
[1] Object Oriented Programming (OOP) views the world as a network of interacting objects.
Interacting objects in the scenario: Tom
, SE Textbook
(Book
for short), Text
, (possibly) Highlighter
💡 objects usually match nouns in the description
[2]Every object has both state (data) and behavior (operations on data).
Object | Examples of state | Examples of behavior |
---|---|---|
Tom |
memory of the text read | read |
Book |
title | show text |
Text |
font size | get highlighted |
[3] Every object has an interface and an implementation.
- Interface of an object consists of how other objects interact with it i.e., what other objects can do to that object
- Implementation consist of internals of the object that facilitate the interactions but not visible to other objects.
Object | Examples of interface | Examples of implementation |
---|---|---|
Tom |
receive reading assignment | understand/memorize the text read, remember the reading assignment |
Book |
show text, turn page | how pages are bound to the spine |
Text |
read | how characters/words are connected together or fixed to the book |
[4] Objects interact by sending messages.
Examples:
Tom
sends messageturn page
to theBook
Tom
sends messageshow text
to theBook
. When theBook
shows theText
,Tom
sends the messageread
to theText
which returns the text content toTom
.Tom
sends messagehighlight
to theHighlighter
while specifying whichText
to highlight. Then theHighlighter
sends the messagehighlight
to the specifiedText
.
[5] OOP does not demand that the virtual world object network follow the real world exactly.
Examples:
- A virtual world simulation of the above scenario can omit the
Highlighter
object. Instead, we can teachText
to highlight themselves when requested.
Evidence:
Consider the following real-world scenario.
Tom read a Software Engineering textbook (he has been assigned to read the book) and highlighted some of the text in it.
Explain the following statements about OOP using the above scenario as an example.
- Object Oriented Programming (OOP) views the world as a network of interacting objects.
- Every object has both state (data) and behavior (operations on data).
- Every object has an interface and an implementation.
- Objects interact by sending messages.
- OOP does not demand that the virtual world object network follow the real world exactly.
[1] Object Oriented Programming (OOP) views the world as a network of interacting objects.
Interacting objects in the scenario: Tom
, SE Textbook
(Book
for short), Text
, (possibly) Highlighter
💡 objects usually match nouns in the description
[2]Every object has both state (data) and behavior (operations on data).
Object | Examples of state | Examples of behavior |
---|---|---|
Tom |
memory of the text read | read |
Book |
title | show text |
Text |
font size | get highlighted |
[3] Every object has an interface and an implementation.
- Interface of an object consists of how other objects interact with it i.e., what other objects can do to that object
- Implementation consist of internals of the object that facilitate the interactions but not visible to other objects.
Object | Examples of interface | Examples of implementation |
---|---|---|
Tom |
receive reading assignment | understand/memorize the text read, remember the reading assignment |
Book |
show text, turn page | how pages are bound to the spine |
Text |
read | how characters/words are connected together or fixed to the book |
[4] Objects interact by sending messages.
Examples:
Tom
sends messageturn page
to theBook
Tom
sends messageshow text
to theBook
. When theBook
shows theText
,Tom
sends the messageread
to theText
which returns the text content toTom
.Tom
sends messagehighlight
to theHighlighter
while specifying whichText
to highlight. Then theHighlighter
sends the messagehighlight
to the specifiedText
.
[5] OOP does not demand that the virtual world object network follow the real world exactly.
Examples:
- A virtual world simulation of the above scenario can omit the
Highlighter
object. Instead, we can teachText
to highlight themselves when requested.
W4.5c
Can explain the relationship between classes and objects :
Paradigms → Object Oriented Programming → Classes →
Writing an OOP program is essentially writing instructions that the computer uses to,
- create the virtual world of object network, and
- provide it the inputs to produce the outcome we want.
A class contains instructions for creating a specific kind of objects. It turns out sometimes multiple objects have the same behavior because they are of the same kind. Instructions for creating a one kind (or ‘class’) of objects can be done once and that same instructions can be used to
Classes and objects in an example scenario
Consider the example of writing an OOP program to calculate the average age of Adam, Beth, Charlie, and Daisy.
Instructions for creating objects Adam
, Beth
, Charlie
, and Daisy
will be very similar because they are all of the same kind : they all represent ‘persons’ with the same interface, the same kind of data (i.e. name
, DoB
, etc.), and the same kind of behavior (i.e. getAge(Date)
, getName()
, etc.). Therefore, we can have a class called Person
containing instructions on how to create Person
objects and use that class to instantiate objects Adam
, Beth
, Charlie
, and Daisy
.
Similarly, we need classes AgeList
, Calculator
, and Main
classes to instantiate one each of AgeList
, Calculator
, and Main
objects.
Class | Objects |
---|---|
Person |
objects representing Adam, Beth, Charlie, Daisy |
AgeList |
an object to represent the age list |
Calculator |
an object to do the calculations |
Main |
an object to represent you who manages the whole operation |
Consider the following scenario. If you were to simulate this in an OOP program, what are the classes and the objects you would use?
Class | Objects |
---|---|
Customer |
john |
Book |
LoTR , GoT |
Cheque |
checqueJohnGave |
Cashier |
peter |
Assume you are writing a CLI program called CityConnect
for storing and querying distances between cities. The behavior is as follows:
Welcome to CityConnect!
Enter command: addroute Clementi BuonaVista 12
Route from Clementi to BuonaVista with distance 12km added
Enter command: getdistance Clementi BuonaVista
Distance from Clementi to BuonaVista is 12
Enter command: getdistance Clementi JurongWest
No route exists from Clementi to JurongWest!
Enter command: addroute Clementi JurongWest 24
Route from Clementi to JurongWest with distance 24km added
Enter command: getdistance Clementi JurongWest
Distance from Clementi to JurongWest is 24
Enter command: exit
What classes would you have in your code if you write your program based on the OOP paradigm?
One class you can have is Route
Evidence:
Consider the following scenario. If you were to simulate this in an OOP program, what are the classes and the objects you would use?
Class | Objects |
---|---|
Customer |
john |
Book |
LoTR , GoT |
Cheque |
checqueJohnGave |
Cashier |
peter |
W4.6a
Can explain the meaning of enumerations :
Paradigms → Object Oriented Programming → Classes →
An Enumeration is a fixed set of values that can be considered as a data type. An enumeration is often useful when using a regular data type such as int
or String
would allow invalid values to be assigned to a variable. You are recommended to enumeration types any time you need to represent a fixed set of constants.
Suppose you want a variable to store the priority of something. There are only three priority levels: high, medium, and low. You can declare the variable as of type int
and use only values 2
, 1
, and 0
to indication the three priority levels. However, this opens the possibility of an invalid values such as 9
to be assigned to it. But if you define an enumeration type called Priority
that has three values HIGH
, MEDIUM
, LOW
only, a variable of type Priority
will never be assigned an invalid value because the compiler is able to catch such an error.
Priority
: HIGH
, MEDIUM
, LOW
Evidence:
Show (in UML notation) an enumeration called WeekDay
to use when the value can only be Monday
... Friday
.
W4.6b
Can use Java enumerations :
C++ to Java → Miscellaneous Topics →
You can define an enum type by using the enum
keyword. Because they are constants, the names of an enum type's fields are in uppercase letters e.g., FLAG_SUCCESS
.
Defining an enumeration to represent days of a week (code to be put in the Day.java
file):
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Some examples of using the Day
enumeration defined above:
Day today = Day.MONDAY;
Day[] holidays = new Day[]{Day.SATURDAY, Day.SUNDAY};
switch (today) {
case SATURDAY:
case SUNDAY:
System.out.println("It's the weekend");
break;
default:
System.out.println("It's a week day");
}
Note that while enumerations are usually a simple set of fixed values, Java enumerations can have behaviors too, as explained in this tutorial from -- Java Tutorial
Define an enumeration named Priority
. Add the missing describe
method to the code below so that it produces the output given.
public class Main {
// Add your method here
public static void main(String[] args) {
describe("Red", Priority.HIGH);
describe("Orange", Priority.MEDIUM);
describe("Blue", Priority.MEDIUM);
describe("Green", Priority.LOW);
}
}
Red indicates high priority
Orange indicates medium priority
Blue indicates medium priority
Green indicates low priority
Use a switch
statement to select between possible values for Priority
.
public static void describe(String color, Priority p) {
switch (p) {
case LOW:
System.out.println(color + " indicates low priority");
break;
// ...
}
}
Code for the enumeration is given below:
public enum Priority {
HIGH, MEDIUM, LOW
}
Evidence:
null
W4.9
Can use basic OOP techniques in Java
Please refer to the relevant sections of the C++ to Java chapter of the Textbook for help on using Java.
W4.10d
Can explain how exception handling is done typically :
Implementation → Error Handling → Exceptions →
Most languages allow code that encountered an "exceptional" situation to encapsulate details of the situation in an Exception object and throw/raise that object so that another piece of code can catch it and deal with it. This is especially useful when the code that encountered the unusual situation does not know how to deal with it.
The extract below from the -- Java Tutorial (with slight adaptations) explains how exceptions are typically handled.
When an error occurs at some point in the execution, the code being executed creates an exception object and hands it off to the runtime system. The exception object contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
After a method throws an exception, the runtime system attempts to find something to handle it in the
The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the program terminates.
Advantages of exception handling in this way:
- The ability to propagate error information through the call stack.
- The separation of code that deals with 'unusual' situations from the code that does the 'usual' work.
Which are benefits of exceptions?
- a. Exceptions allow us to separate normal code from error handling code.
- b. Exceptions can prevent problems that happen in the environment.
- c. Exceptions allow us to handle in one location an error raised in another location.
(a) (c)
Explanation: Exceptions cannot prevent problems in the environment. They can only be used to handle and recover from such problems.
Evidence:
Acceptable: Some code you wrote that involves exception handling.
Suggested: Do the exercise in addressbook-level2: LO-Exceptions.
W4.11b
Can explain the need for early developer testing
Quality Assurance → Testing → Developer Testing →
Delaying testing until the full product is complete has a number of disadvantages:
- Locating the cause of such a test case failure is difficult due to a large search space; in a large system, the search space could be millions of lines of code, written by hundreds of developers! The failure may also be due to multiple inter-related bugs.
- Fixing a bug found during such testing could result in major rework, especially if the bug originated during the design or during requirements specification i.e. a faulty design or faulty requirements.
- One bug might 'hide' other bugs, which could emerge only after the first bug is fixed.
- The delivery may have to be delayed if too many bugs were found during testing.
Therefore, it is better to do early testing, as hinted by the popular rule of thumb given below, also illustrated by the graph below it.
The earlier a bug is found, the easier and cheaper to have it fixed.
Such early testing of partially developed software is usually, and by necessity, done by the developers themselves i.e. developer testing.
Discuss pros and cons of developers testing their own code.
Pros:
- Can be done early (the earlier we find a bug, the cheaper it is to fix).
- Can be done at lower levels, for examples, at operation and class level (testers usually test the system at UI level).
- It is possible to do more thorough testing because developers know the expected external behavior as well as the internal structure of the component.
- It forces developers to take responsibility for their own work (they cannot claim that "testing is the job of the testers").
Cons:
- A developer may subconsciously test only situations that he knows to work (i.e. test it too 'gently').
- A developer may be blind to his own mistakes (if he did not consider a certain combination of input while writing code, it is possible for him to miss it again during testing).
- A developer may have misunderstood what the SUT is supposed to do in the first place.
- A developer may lack the testing expertise.
The cost of fixing a bug goes down as we reach the product release.
False. The cost goes up over time.
Explain why early testing by developers is important.
Evidence:
Explain why early testing by developers is important.
W4.11e
Can use simple JUnit tests
Tools → JUnit →
When writing JUnit tests for a class Foo
, the common practice is to create a FooTest
class, which will contain various test methods.
Suppose we want to write tests for the IntPair
class below.
public class IntPair {
int first;
int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public int intDivision() throws Exception {
if (second == 0){
throw new Exception("Divisor is zero");
}
return first/second;
}
@Override
public String toString() {
return first + "," + second;
}
}
Here's a IntPairTest
class to match.
import org.junit.Test;
import org.junit.Assert;
public class IntPairTest {
@Test
public void testStringConversion() {
Assert.assertEquals("4,7", new IntPair(4, 7).toString());
}
@Test
public void intDivision_nonZeroDivisor_success() throws Exception {
Assert.assertEquals(2, new IntPair(4, 2).intDivision());
Assert.assertEquals(0, new IntPair(1, 2).intDivision());
Assert.assertEquals(0, new IntPair(0, 5).intDivision());
}
@Test
public void intDivision_zeroDivisor_exceptionThrown() {
try {
Assert.assertEquals(0, new IntPair(1, 0).intDivision());
Assert.fail(); // the test should not reach this line
} catch (Exception e) {
Assert.assertEquals("Divisor is zero", e.getMessage());
}
}
}
Notes:
- Each test method is marked with a
@Test
annotation. - Tests use
Assert.assertEquals(expected, actual)
methods to compare the expected output with the actual output. If they do not match, the test will fail. JUnit comes with other similar methods such asAssert.assertNull
andAssert.assertTrue
. - Java code normally use camelCase for method names e.g.,
testStringConversion
but when writing test methods, sometimes another convention is used:whatIsBeingTested_descriptionOfTestInputs_expectedOutcome
e.g.,intDivision_zeroDivisor_exceptionThrown
- There are several ways to verify the code throws the correct exception. The third test method in the example above shows one of the simpler methods. If the exception is thrown, it will be caught and further verified inside the
catch
block. But if it is not thrown as expected, the test will reachAssert.fail()
line and will fail as a result. - The easiest way to run JUnit tests is to do it via the IDE. For example, in Intellij you can right-click the folder containing test classes and choose 'Run all tests...'
- Optionally, you can use static imports to avoid having to specify
Assert.
everywhere.import static org.junit.Assert.assertEquals; //... @Test public void testStringConversion() { assertEquals("4,7", new IntPair(4, 7).toString()); }
JUnit 4 with IntelliJ: A quick introduction -- by DrBFraser
- JUnit cookbook - a short tutorial from JUnit creators
- JUnit tutorial - a more detailed tutorial from a developer Lars Vogel
- How to test private methods in Java? [ short answer ] [ long answer ]
Evidence:
Acceptable: Have written JUnit tests in some project.
Suggested:
- Fork Addressbook-Level2 onto your GitHub account
- Clone the fork to your computer
- Set up the project by following its Developer Guide
- Run the JUnit tests that came with the project
- Do the exercise in [Addressbook-Level2: LO-JUnit] but read the submission instructions (given below) first.
Submission: Create a PR against Addressbook-Level2. Try to make a clean PR (i.e. free of unrelated code modifications).
W4.12
Can define requirements of a product
Covered by the below. Try to do at least step 1 before coming to the tutorial.
Lecture 4
Questions to discuss during the lecture:
Imagine you are building an online system called TeamFormer. A brief description of it is given below.
TeamFormer is a system for helping CS2103/T students during team forming period. It lets students record who is in which team. Students can use the system to find teams short of members and students looking for teams, easing the team forming process. Note that the system is not meant as a platform for students to communicate with each other to find team members. Students are supposed to talk to each other and form teams outside the system, as they do now. TeamFormer simply helps students to see the team forming status of the class (e.g., who has teams and who doesn’t) and record their own team after forming a team. It is also meant to ease the team-forming-related workload of instructors.
(a) Specify the vision, scope, user types, and the workflow of TeamFormer.
(b) Specify requirements of TeamFormer as a list of User Stories.