CS2103 Software Engineering

Workflows

  1. Checkout PR in local repo: To fetch PR commits for testing, use

    git fetch upstream pull/{{ $PULL_REQ_NUMBER }}/head:{{ $BRANCHNAME }}
    git checkout {{ $BRANCHNAME }}
    
    // alternatively
    git fetch upstream pull/{{ $PULL_REQ_NUMBER }}/head && git checkout FETCH_HEAD
    
  2. Create and switch to branch: git switch -c {{ $BRANCH_NAME }}

  3. Check pretty-print git history: git log --all --decorate --oneline --graph

  4. Add new upstream and pull from master branch:

    git remote add upstream https://github.com/{{ $OWNER_REPO_PATH }}.git
    git pull upstream master
    
  5. Push new branch: git push origin {{ $BRANCH_NAME }}. If intending to update branch, can set the upstream of the branch a bit more permanently by adding the --set-upstream flag.

  6. Sync branches with remotes: git remote --all --prune

Week 11

Architectural styles

n-tier style

Higher layers make use of services provided by lower layers. Lower layers are independent of higher layers, i.e. multi-layered, layered.

../../_images/20210314_nTierExamples.png

Client-server style

Used commonly in distributed applications.

../../_images/20210314_clientServerExamples.png

Event-driven style

Controls flow by detecting events from event emitters and communicating those events to interested event consumers.

../../_images/20210314_eventDriven.png

Transaction-processing style

Divides workload of system into a number of transactions which are given to a dispatcher that handles task queueing, ordering, undo, etc.

../../_images/20210314_transactionProcessing.png

Service-oriented architecture style

Building applications by combining functionalities packaged as programmatically accessible services, for better interoperability between distributed services.

Other styles

  • Pipes and filters pattern
  • Broker pattern
  • Peer-to-Peer pattern
  • Message-driven processing

Combining test cases

Essentially to make it more efficient. Some strategies to combing test inputs:

  • All combinations: Test case for each unique combination of test inputs
  • At least once: Test cases must include each test input at least once
  • All pairs: For any given input pairs, all combinations are tested.

Based on heuristic that bug is rarely the result of more than two interacting factors. - Random strategy - Heuristic: Each valid input at least once in positive test cases - Heuristic: No more than one invalid input in negative test cases

Quality assurance

  • Validation: Are the requirements correct?
  • Verification: Are the requirements implemented correctly?
    • Formal verification: Using mathematical techniques to prove the correctness of a program. More commonly used in safety-critical systems where the absence of errors needs to be proven.

Reuse

Reusing tried-and-tested components to enhance robustness of software system, while reducing manpower and time requirement, but there are costs associated with code reuse.

  • Libraries: collection of modular code that is general to be used by other programs. Typically involves: (1) reading documentation, (2) check license, (3) download and make accessible, (4) call library API.
  • APIs: specifies interface through which other programs / clients can interact with a software component.
  • Frameworks: resuable implementation of software (or part thereof) that provide generic functionality that can be selectively customized to produce a specific application.
  • Platforms: runtime environment for applications
  • Cloud computing: delivery of computing as a service over a network

Note that libraries are meant to be used ‘as is’, while frameworks are designed to be customized and extended. Your code calls library code, framework code calls your code (inversion of control).

../../_images/20210314_cloud.png

Other UML models

Communication diagram

Like sequence diagrams, but emphasizes data links between participants.

../../_images/20210314_communicationDiagram.png

State machine

../../_images/20210314_stateMachine.png

Deployment diagrams

System’s physical layout, revealing which pieces of software run on which pieces of hardware.

../../_images/20210314_deploymentDiagram.png

Component diagrams

Show how a system is divided into components and how they are connected to each other through interfaces.

../../_images/20210314_componentDiagram.png

Package diagram

Shows packages and their dependencies. A package is a grouping construct for grouping UML elements (e.g. classes, use cases).

../../_images/20210314_packageDiagram.png

Composite structure diagram

Hierarchically decomposes a class into its internal structure.

../../_images/20210314_compositeStructureDiagram.png

Timing diagram

Focuses on timing constraints.

../../_images/20210314_timingDiagram.png

Interaction overview diagram

Combination of activity diagrams and sequence diagrams.

../../_images/20210314_interactionOverviewDiagram.png

Week 10

Design patterns

An elegant reusable solution to a commonly recurring problem within a given context in software design. Can be described using:

  • Context, Problem, Solution
  • (Optionals) Anti-patterns, Consequences, Others (e.g. examples, known uses)

Singleton

  • Context: Certain classes should have no more than one instance
  • Problem: A class can be instantiated multiple times by invoking constructor
  • Solution: Make constructor of singleton private and provide a public class level method to access the single instance.
class Logic {
    private static Logic logic = null;
    private Logic() {}
    public static Logic getInstance() {
        if (logic == null) {
            logic = new Logic();
        }
        return logic;
    }
}
  • Evaluation: Easy to apply and effective. Singleton acts like global variable that increases coupling. Difficult to replace with stubs (static methods cannot be overridden). Singletons carry data between tests.

Façade

  • Context: Components need to access functionality deep inside other components
  • Problem: Access to component should be allowed without exposing internals
  • Solution: Include a “facade” class that mediates accesses to components.
../../_images/20210314_textStorage.png

Command pattern

  • Context: System is required to execute multiple commands doing different tasks
  • Problem: Preferable that code executes commands without knowledge of command type, e.g. CommandQueue that queues and executes commands without knowledge of what each command does.
  • Solution: A general Command object that can be extended using polymorphism.
../../_images/20210314_clientInvoker.png

Abstraction occurrence

  • Context: Group of similar entities share copies of the similar data
  • Problem: Representing the entities as a single class results in data duplication which can lead to inconsistencies
  • Anti-pattern: Create a class for each object with same data hardcoded as class variables. Problematic because new classes need to be created for each object.
  • Solution: Let entity be represented by two objects instead of one, which information segregated: <<Abstraction>> 1 <----> * <<Occurrence>>
../../_images/20210314_bookTitleBookCopy.png

MVC pattern

  • Context: Most applications support storage, display information, and changing stored information based on external inputs
  • Problem: High coupling from interlinked features
  • Solution: Decouple data, presentation and control logic into three different components, i.e. Model, View, Controller.
../../_images/20210314_MVC.png

Observer pattern

  • Context: Objects are interested in being notified when change happens to another object
  • Problem: ‘Observed’ object does not want to be coupled to ‘observing’ objects
  • Solution: Force communication through an interface known to both objects
../../_images/20210314_observableInterfaceDiagram.png
class StudentList {
    public void addUi(Observer o) {
        observerList.add(o);
    }
    public void notifyUis() {
        for (Observer o: observerList) {
            o.update();
        }
    }
}

class StudentListUi implements Observer {
    @Override
    public void update() {
        ...
    }
}

// Code execution

StudentList studentList = new StudentList();
StudentListUi listUi = new StudentListUi();
StudentStatsUi statsUi = new StudentStatsUi();
studentList.addUi(listUi);  // subscribe to changes
studentList.addUi(statsUi);

...

studentList.notifyUis();  // when StudentList is updated

Other design patterns

The most famous source of design patterns is the "Design Patterns" book
which contains 23 design patterns divided into three categories:

- Creational: About object creation. They separate the operation of an
  application from how its objects are created, e.g.
  Abstract Factory, Builder, Factory Method, Prototype, Singleton
- Structural: About the composition of objects into larger structures while
  catering for future extension in structure, e.g.
  Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy
- Behavioral: Defining how objects interact and how responsibility is
  distributed among them, e.g.
  Chain of Responsibility, Command, Interpreter, Template Method, Iterator,
  Mediator, Memento, Observer, State, Strategy, Visitor

Defensive programming

“Design by contract” by Bertrand Meyer, to allow language to enforce contracts. This is basically the mantra: “If you leave room for things to go wrong, they will go wrong.” or Murphy’s law in short. Has its associated costs, e.g. more runtime assertions.

class Main {
    Config config;

    Config getConfig() {
        return config.copy();  // defensive programming,
                               // prevents config modification
    }
}

Another involves maintaining referential integrity, i.e. check if objects meet the preconditions before applying operation.

Design by contract is a language feature that assumes the caller of the method to be responsible for ensuring preconditions are met.

Enforce associations

class Account {
    Guarantor guarantor;

    void setGuarantor(Guarantor g) {
        if (g == null) {
            stopSystemWithMessage("Multiplicity violated - null guarantor")
        }
        guarantor = g;
    }
}

Enforce 1-to-1 association

class Laptop {
    private Keyboard keyboard;

    public Laptop() {
        keyboard = new Keyboard();
    }
}

Designing test cases

  • Testing should be effective (finds high percentage of bugs) and efficient (has high success rate in finding bugs).

  • Can be positive (produce expected behaviour) or negative (produce errors).

  • Can test based on use cases.

  • Three types:

    • Black box (specification-based): Test cases based on SUT’s specified external behavior
    • White box (Implementation-based): Test cases based on SUT’s implementation
    • Gray box: Test cases use some important information about implementation

Equivalence partitioning

Grouping test inputs that are likely to be processed in the same way. Similar to finding corner cases and including them in testing. Need to consider all participants, e.g. target object of method call, input parameters, other objects accessed.

The following specification: isValidFlag(String s): Boolean: Returns true if s is one of [“F”, “T”, “D”], false otherwise. Comparison is case-insensitive.

Yields the equivalence partitions: ["F"] ["T"] ["D"] ["f","t","d"] [any other string] [null]

Boundary value analysis

Oh so this is the one… Boundary Value Analysis (BVA) is a heuristic based on observation that bugs often result from incorrect handling of boundaries of EPs. Typically (1) at boundary, (2) just below boundary, (3) just above boundary.

Week 9

OOPD

Class diagrams can be used to model actual objects in problem domain, known as Object-oriented domain models (OODMs) / conceptual class diagram. OODM represents class structues and do not show methods and navigability.

../../_images/20210313_OOPDeg.png

Class diagrams represent the solution domain instead.

Activity diagram

../../_images/20210313_activitydiagram.png

Additional annotations:

../../_images/20210313_rake.png ../../_images/20210313_swimlane.png

Some activity diagram exercises.

A pretty good exercise on modeling.

Principles

  • Separation of concerns
    • Separating code into distinct sections addressing individual concerns, e.g. feature, aspect, entity, to reduce functional overlaps and ripple effects during changes.
    • Used in n-tier architecture
    • Leads to higher cohesion and lower coupling
  • Single responsibility
    • Class should have one and only one reason to change.
  • Liskov substitution
    • Derived classes must be substitutable for their base classes, i.e. subclass must not be more restrictive than behaviour of superclass.
  • Open-closed principle
    • Module open for extension but closed for modification.
    • Separate specification from implementation.
  • Law of Demeter
    • Object should have limited knowledge of other objects
    • Principle of least knowledge
    • OK: void foo() { Bar b = new Bar(); b.doSmth(); }
    • NOT OK: void foo(Bar b) { Goo g = b.getGoo(); g.doSmth(); }
  • Interface segregation principle
    • Client should not be forced to depend on methods it does not use
  • Dependency inversion
    • High-level and low-level modules should not depend on each other, but on abstractions.
    • Abstractions should not depend on details, but the other way around.
  • SOLID (SRP, OCP, LSP, ISP, DIP)
  • YAGNI (Ya Ain’t Gonna Need It)
  • DRY (Don’t Repeat Yourself)
  • Brook’s Law (adding more manpower to a late project makes it later)

Software Development Lifecycle (SDLC)

  • Waterfall / sequential
  • Iterative (depth vs breadth first)
  • Agile approach
    • User requirements prioritized and clarified regularly
    • Rough project plan and high level design
    • Complete transparency and responsibility sharing within team
    • Includes XP (extreme programming) and Scrum
  • Scrum
    • Process skeleton with sets of practices and predefined roles:
      • Scrum Master: Maintains processes
      • Product Owner: Represents stakeholders
      • Team: Cross-functional group doing analysis, design, impl., testing, etc.
    • Iterations known as Sprints, timeboxed to constant length, preceded by planning meeting to identify tasks, followed by review meeting.
    • Product backlog – (Product Owner) – (Team) –> Sprint backlog
    • Colocation of all team members
    • Prioritize response to emerging requirements.
    • Daily Scrum:
      • Not issue resolution, which is taken offline
      • What did you do yesterday?
      • What will you do today?
      • Are there any impediments in your way?
    • Good intro video
  • XP
    • Communication, simple clean design, feedback through testing.
    • Heavy emphasis on teamwork across different stakeholders.
    • Guide to extreme programming
  • Unified process
    • Divided into cross-disciplinary iterations.
../../_images/20210313_UP.png
  • CMMI (determine process maturity level of organization)
../../_images/20210313_CMMI.png

Documentation

../../_images/20210313_documentation.png

Documentation should be comprehensible.

  • Diagrams
  • Examples
  • Simple explanations
  • Rid of statements with no value
  • Not a good idea to have separate sections for each artifact, e.g. use case, sequence diagrams, activity diagrams. Include diagrams for explanations.
  • Top-down approach better than bottom-up.
  • Should be minimal but sufficient (e.g. for developers, use code to complement)
  • For similar documentation, describe similarities / differences.

Week 8

Do these UML exercises.

  • Constraints can be given inside a note, within curly braces.
  • Static method calls use <<class>> :Person syntax in UML sequence diagrams
../../_images/20210308_staticMethodCall.png

Quiz practice. Since too big, adding as urls to answers 1 and 2 instead.

  • Integration testing: Test whether two different parts of software work together as expected.
  • System testing: Done by QA team, testing system specification, including NFRs, such as performance, load, security, portability, usability, etc.
  • Acceptance testing: Done by team representing the customer, on deployment environment, and done against requirements specification. More positive test cases.
  • Alpha/Beta testing: Alpha testing -> Performed by users under controlled conditions set by software development team. Beta testing -> Performed by subset of users in natural work setting.
  • Exploratory (reactive) testing: Devise test cases on-the-fly, based on past experience or observations of past test cases. Best to use together with scripted testing.
  • Dependency testing: Extension of unit tests to introduce stubs to isolate SUT from dependencies.

Test coverage

  • Function / method coverage: Based on functions executed
  • Statement coverage: Based on lines of code
  • Decision / branch coverage: Based on decision points, e.g. if-else
  • Condition coverage: Based on boolean expression, e.g. true-false
  • Path coverage: Based on possible paths through code, most extensive
  • Entry / exit coverage: Based on calls to and exits from operations in SUT

Lots of other things to do in software engineering:

../../_images/20210308_moreThanCode.png

Week 7

Expected workflow

  1. Record tasks as issues (user stories, other tasks)
  2. Assign relevant issues to members, respective to create pull requests
  3. Forking workflow: Fork / Pull, Clone, Push
  4. Resolution of merge conflicts should be done by branch maintainer

Specifying requirements

A use case is a description of a set of action sequences that a system performs to yield an observable result of value to an actor. An actor is a role played by a user or another outside system.

Use cases capture functional requirements, and should only reflect externally visible behavior / actor intent.

Main Success Scenario (MSS) is illustrated, with additional extensions.

Feel free to ignore extensions.

../../_images/20210223_usecase_extension.png

Other use cases can be referenced:

../../_images/20210223_usecase_inclusion.png

Preconditions specify the state of the system is in before use case starts. Guarantees specify what the use case promises to yield at the end of operation.

Generalization of actors. Some actors can also be systems to indicate automated actions.

../../_images/20210223_usecase_actorGeneralisation.png

One of the main disadvantages of use cases is that they are not good for capturing requirements that do not involve a user interacting with the system.

Design

External design vs internal design. Multi-level design either in top-down, bottom-up or mixed.

Agile design can be contrasted with full upfront design, evolving to fulfill new requirements and take advantage of new technologies as appropriate. Often requires doing some initial architectural modeling at the start.

Fundamentals

Abstraction:

  • Data abstraction: Abstract away lower level data items
  • Control abstraction: Abstract away details of actual control flow

Coupling:

  • Measure of degree of dependence
  • High coupling -> harder maintenance, integration and testing and reuse.
  • Types of coupling:
    • Content coupling: one module modifies or relies on the internal workings of another module
    • Common/Global coupling: two modules share the same global data
    • Control coupling: one module controlling the flow of another, by passing it information on what to do
    • Data coupling: one module sharing data with another module
    • External coupling: two modules share an externally imposed convention e.g., data formats, communication protocols, device interfaces.
    • Subclass coupling: a class inherits from another class. Note that a child class is coupled to the parent class but not the other way around.
    • Temporal coupling: two actions are bundled together just because they happen to occur at the same time e.g. extracting a contiguous block of code as a method although the code block contains statements unrelated to each other

Cohesion:

  • Measure of how strongly-related and focused the various responsibilities of a component are.
  • A highly-cohesive component keeps related functionalities together while keeping out all other unrelated things.

Other IDE functions

  • Hide windows: Ctrl-Shift-F12
  • Move line: Shift-Alt-Arrows
  • Move cursors: Shift-Alt-Click
  • Parameter info: Ctrl-P

Integration methods

  • Late, big-bang
  • Early, incremental
    1. Top-down integration: Requires stubs
    2. Bottom-up integration: Requires drivers
    3. Sandwich integration: Mix of both.

Project planning

  1. Milestones
  2. Issue trackers
  3. Buffers
  4. Work breakdown structure
  5. Gantt chart
  6. Program Evaluation Review Technique (PERT)
../../_images/20210223_wbs.png ../../_images/20210223_gantt.png ../../_images/20210223_pert.jpg

Team structure

  • Egoless
  • Chief programmer
  • Strict hierarchy

Types of repo

  • Centralized RCS
  • Distributed / decentralized RCS
    • Centralized workflow
    • Branching workflow (+ branches)
    • Forking workflow (+ forks)
../../_images/20210223_121428_forking.png

Week 6:

Sequence diagrams

../../_images/20210210_sdinteractionfragment.png
  • Activation bar determines duration the instance is in control.
  • Entities are the actors on the top of the diagram.
  • Alternative paths can be neither activated, but cannot be simultaneously activated.

Creation:

../../_images/20210210_objectcreation.png

Deletion:

../../_images/20210210_objectdeletion.png

Self-invocation:

../../_images/20210210_selfinvoke1.png ../../_images/20210210_selfinvoke2.png

Optional paths:

../../_images/20210210_optionalpath.png

Reference frames: To shift sequence diagram to another location

../../_images/20210210_ref1.png ../../_images/20210210_ref2.png

Parallel paths:

../../_images/20210210_parallelpaths.png

Architecture diagrams are created by software architect. Typically require multi-level for bigger projects.

Debugging with IntelliJ IDEA

  • Can set breakpoint
  • Can set conditional breakpoint as well(!)

Code navigation shortcuts:

  • Find class Ctrl-N
  • Find file Ctrl-Shift-N
  • Find symbol Ctrl-Alt-Shift-N
  • Quick doc Ctrl-Q
  • Quick impl Ctrl-Shift-I
  • Go to decl Ctrl-B
  • Go back/forward Ctrl-Alt-<-/->
  • Search shortcuts Ctrl-Shift-A

Quick resume talk:

../../_images/20210210_192537.png ../../_images/20210210_192758.png

Week 5: Requirements

Non-functional requirements are important to specify. Good if we start off with that early as well. Examples of NFRs:

  • Data requirements e.g. size, volatility, persistency etc.,
  • Environment requirements e.g. technical environment in which the system would operate in or needs 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…

Requirements must be made:

  • Unambiguous
  • Testable (verifiable)
  • Clear (concise, terse, simple, precise)
  • Correct
  • Understandable
  • Feasible (realistic, possible)
  • Independent
  • Atomic
  • Necessary
  • Implementation-free (i.e. abstract)
  • Consistent as a whole

Can prioritize requirements using schemes, e.g. Essential, Typical, Novel.

Requirement gathering can be done in one of many ways:

  1. Brainstorming
  2. Product surveys
  3. Observation
  4. User surveys
  5. Interviews
  6. Focus groups
  7. Prototyping

Requirements can be specified as:

  • Prose
  • Feature lists
  • User stories
  • Glossary
  • Supplementary requirements

One possible exercise to develop user stories:

  1. Define target user as persona
  2. Define problem scope
  3. List scenarios that form a narrative, e.g. by situation, context, familiarity
  4. List user stories that support scenarios

Refactoring repository: https://refactoring.com/catalog/

Assertions can be used, but must be enabled using java --enableassertions MyProgram

Week 4: UML models

Model

Representation of something. Provides a simpler view of complex entity by capturing only a selected aspect, i.e. abstraction.

  1. Analyze complex entity
  2. Communication information among stakeholders
  3. Blueprint for software

Some thoughts on Model-driven development (MDD).

../../_images/20210201_203307.png

OO structure

  • Class diagram model class structures (but not behaviour)
../../_images/20210201_213345.png
  • Object diagram model object structures, i.e. instances
../../_images/20210201_213350.png

Class diagram

Access modifiers: + public, - private, # protected, ~ package-private. Underlines indicate class fields.

Person
+ name: String
- age: Integer
# children: Person[]
- totalPeople : Integer
+ getTotal(): Integer
+ getName(): String
~ setAge(n: Integer)
# getChildren(): Person[]

Generic classes are denoted with overlay of parameter type on top right corner of class name.

Object diagram

John:Person
name = “L. John”
age = 24

Attribute (compartment) can be omitted if not relevant to task at hand.

Multiplicities are omitted.

Inheritance diagram

../../_images/20210201_215524.png

Enumerations

<<enumeration>>
Weekday
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY

Abstract classes

{abstract}
Staff
name
salary
adjustedSalary(): int {abstract}

Can be denoted using italics as well.

Interface

A behaviour-specification.

../../_images/20210201_221328.png

UML notes

UML notes augment diagrams with additional information.

../../_images/20210201_215047.png

Association

Connections between objects/classes are termed ‘associations’, denoted using a solid line between classes, or as an attribute of the form: name: type [multiplicity] = default value

../../_images/20210201_215252.png

Associations have additional decorations:

  1. Association labels
../../_images/20210201_212454.png
  1. Association role labels: usually has correspondence with variable name
../../_images/20210201_212553.png
  1. Association multiplicity
  • 0..1 optional associations: object or null
  • 1 compulsory associations: not null
  • * association: 0 or more
  • m..n association: between m to n
  • Bi-directional association: matching variables in both classes
  • 1-to-many association: use arrays
../../_images/20210201_213109.png
  1. Association navigability

In the example below, Logic is aware of Minefield, but not the other way around, i.e. Minefield does not contain Logic objects/class.

../../_images/20210201_213203.png

Composition

A composition is an association representing a strong whole-part relationship that has no cyclical links, i.e. the part cannot exist with the whole, on a conceptual level. Need to keep track of composition relationship in order to ensure proper clean up.

../../_images/20210201_215822.png

Aggregation

Represents a container-contained relationship, where contained object can exist even after container is deleted, e.g. a leader in a team.

../../_images/20210201_220427.png

Dependency

One class depending on another which has no direct association. Typically appears as a method parameter.

../../_images/20210201_220658.png

Association class

An association class can store additional information about an association. No fixed implementation, typically with endpoints as variables.

../../_images/20210201_221630.png

Week 2

Software development cycles / Process models

The sequential/waterfall model is as follows:

  1. Specify requirements
  2. Design product
  3. Implement
  4. Test
  5. Deploy

There is also an iterative approach, divided into iterations instead of phases:

  1. Development
  2. Get feedback

Problem with waterfall approach, difficult to determine time taken for each phase. But there are also downsides to iterative approach, i.e. overhead from redesigning features, unclear progress towards end product.

Waterfall is used if requirements are well-understood, fixed and predictable. Iterative for fuzzy and evolving requirements.

iP = iterative, breadth-first