Info

  • no recordings
  • flipped classroom (new this year)
  • grade
    • of project grade: final presntation
  • project:
    • 4-6 persons
    • multiplayer game
    • C++ with cmake, with GUI, built for linux (Ubuntu)
    • sockpp + GoogleTest + wxWidgets (all optional)
    • grading+deadlines -> https://lec.inf.ethz.ch/se/2026/site/project/#grading
      • SE: Team Registration (@2026-09-20)
      • SE: Requirements Specification (@2026-10-09)
      • SE: Software Design (@2026-10-23)
      • SE: Testing (@2026-12-04)
      • SE: Implementation (@2026-12-13)
      • SE: Final Presentation (@2026-12-16)
  • exercises: luca.conconi@gmail.com

Exam Software Engineering

90min, no aids; accounts for 50% of the final grade

Exercises

-> HS2026_tasks

tools:

Vorlesung

timestamp 2026-09-25

Requirement Engineering

defining and documenting system/software requirements

requirements says what a system must do, but not how it should do it

  • Functional requirements: What the system should do: the functions it offers and the way it interacts with its environment.
  • Nonfunctional requirements: The qualities and constraints: how fast, how reliable, how secure, under which standards.

Video week3, 2

  • “The system shall be usable by elderly people.”

ambiguous, better: font size should be large (>20pt) and >80% of people over 70y should be able to order a product in 10min

  • “The product shall be error-free.”

not realistic, not verifiable; better: the system needs to pass all predefined tests (?)

  • “The system shall provide real-time response.”

ambiguous, better: the system should load new results in <20ms


Use case

  • Entire user goal with main andexceptional path
  • Written up front; more formal/heavier.
  • Can directly be validated with theuser

User story

  • Small, iteration‑sized slice.
  • Placeholder for conversation;refined with acceptance criteria and examples
  • Can be validated once acceptance criteria are added

Requirements should describe what the system does, not how it does it, so deferring the architecture is the correct thing to do at this stage.

-> instead of “client”/“server”, write “system” if the actor who does it is not important

Modelling

building an abstraction (simplifications) of reality

  • means for dealing with complexity by disregarding some details

in this course, we use UML

  • classes/object diagrams: link
  • sequences/state diagrams: link
    • Actors and objects are drawn as columns. Each column is headed by the name of the object, using the name : Class notation known from object diagrams: :Terminal is an (anonymous) object of class Terminal. Unlike in object diagrams, the name is not underlined (older UML versions did underline it, so you will still see this in many books). Actors, i.e. humans or external systems, are drawn as stick figures.
    • Lifelines are drawn as dashed vertical lines below each object. They represent the existence of the object over time.
    • Time runs from top to bottom. A message further down happens later.
    • Messages are drawn as arrows from the sender to the receiver, labelled with the name of the message (typically an operation of the receiver) and its arguments.
    • Activations are drawn as narrow rectangles on the lifeline. They indicate the period during which an object is active, i.e. is executing an operation, for example in response to a message.

underspecification

  • ability to postpone decisions that do not need to be taken immediately

timestamp 2026-10-08

https://practicalalloy.github.io/chapters/structural-modeling/index.html -> introduction to Alloy

Assertion and counterexample in alloy (note that this minimal example only shows about of the features introduced in that chapter)

abstract sig Role {}
one sig Doctor, Nurse extends Role {}
 
abstract sig Action {}
one sig ViewRecord, Prescribe extends Action {}
 
sig User {
  role: one Role,
  can: set Action
}
 
-- Rules: what each role is allowed to do
fact permissions {
  all u : User | u.role = Doctor implies u.can = ViewRecord + Prescribe
  all u : User | u.role = Nurse  implies u.can = ViewRecord
}
 
-- Assertion: only doctors can prescribe
assert only_doctors_prescribe {
  all u : User | Prescribe in u.can implies u.role = Doctor
}
 
-- Alloy searches for a counter-example within 10 users
check only_doctors_prescribe for 3
 
-- If we try to add a new role without updating the rules, assertion fails
-- because Interns can Prescribe
one sig Intern extends Role {}
TermPlain meaningContemporary equivalent
SignatureA named set (sig User {})Class
AtomOne element of a signature (User0)Object / Instance
FieldA relation between signatures (role: one Role)Attribute
RelationA set of tuples — everything in Alloy is oneTable / Dictionary
TupleOne row in a relation ((User0, Doctor))Row / Record / Entry
InstanceOne concrete world the Analyzer generatesSnapshot / Test fixture
FactConstraint assumed always trueInvariant / Constraint / Validation rule
AssertProperty you claim follows from your facts
CounterexampleInstance satisfying facts but breaking an assertion

To guide your reading, the following questions might be helpful:

Say you have defined a signature in your Alloy model. What does the signature correspond to in an instance generated by the Alloy Analyzer? -> class

What does the Alloy Analyzer allow you to do? -> Allows modelling of systems and checking properties of these models

What is the difference between declaring a signature with extends and with in? What does abstract add?

  • extends -> child class (subtype)
  • in -> inset/subset
ExtendsIn
Examplesig Laptop, Desktop extends Computer (A computer cannot be both).sig MultiCore, TouchScreen in Computer (A computer can be both).

The keywords one, some, lone and set appear in several places: in front of signatures, in field declarations, and in formulas. What do they mean in each of these places? in front:

  • one restricts the signature to have exactly one atom
  • some at least one atom
  • lone at most one atom

field declarations:

  • one exactly one target atom per source
  • some at least one target atom per source
  • lone at most one atom per source

formulas (cardinality checks on a relation/set):

  • one checks the set has exactly one tuple
  • some checks the set is non-empty
  • lone checks the set has at most one tuple
  • no checks the set is empty (this one only appears in formulas, not the others)

What are the numbers following the run command (e.g. run example {} for 4 but 2 Entry, exactly 3 Name)? specifies scope of analysis

  • limit for every top-level signature is set to 4
  • only 2 entries
  • exactly 3 names

What do fields allow you to do? What does a field declaration correspond to in an instance?

relation between signatures (attribute of a relation)

What does the . (dot join) operator do? If name is a field, what do e.name and name.n denote?

Navigates through a relation. e.name = “the name of entry e” (forward: source -> target). name.n = “the entries that have name n” (backward: target -> source) (AI)

What is a fact and when do you specify a fact?

constraint always assumed to be true

fact permissions {
  all u : User | u.role = Nurse  implies u.can = ViewRecord
}

What is an assert and how is it different from a fact?

A property you claim follows from your facts, but don’t assume. A fact is never questioned, the Analyzer builds it in. An assert is actively challenged: the Analyzer tries to find an instance that satisfies all facts but breaks the assert. (AI)

What does check do? What is the difference from run?

check tries to find a counterexample to an assertion. run tries to find any instance satisfying the model

If check finds no counterexample, does this prove that the assertion is true? What are pred and fun used for?

Reusable building blocks. pred -> named reusable formula (bool function) you can invoke inside facts, asserts or run commands. fun is a named reusable expression that returns a relation

It just proves that there is no counterexample within the given scope - in our case three people


object diagrams - snapshot of objects existing at a single time

  • does not show operations (& attribute values)
  • no multiplicity in links

state diagram - lifetime of single (or multiple) objects (not static!)

  • unspecification possible do in SDS
  • in code: events can become member functions
  • do not describe how components of system interact with each other

sequence diagrams

  • describe interactions in system
  • has activation bar when object is active
  • do not forget “destroy” at end of lifelines, if possible
  • [alt, opt, loop, par]

class diagram

  • multiplicity

  • composition: parent: black rhombus
    • cannot exist independently
    • cannot be shared
  • inheritance: empty triangle
    • shows from child->parent (“the wrong way around”!)

tricks: todo

Decomposition and Modularity

timestamp 2026-10-25

Decomposition (divide and conquer) for large software to manage complexity

  • Advantages: separation of concerns, parallel development, independent testing and analysis, independent change, and code reuse.
  • Granularity Trade-off: too coarse leaves parts too complex, too fine increases dependencies. hierarchical decomposition manages this at each level.

Modularity: self-contained, reusable units of code existing at multiple levels, from individual functions to entire systems. Architecture defines module structure, while design defines internal module workings.

  • Coupling: Measures the degree of interdependence between modules. Low coupling is critical so modules can be developed, tested, changed, and reused in isolation.
  • Cohesion: Measures the degree to which elements inside a module belong together. High cohesion is desired.

goal -> low coupling, high cohesion

Design pattern: general, reusable solution to a commonly occurring design problem

  • often used to reduce coupling

see facade , design pattern catalogue

Patterns vs. idioms:

  • Design pattern: reusable, general solution shape to a recurring design problem; roles/responsibilities; transferable within a paradigm.
  • Idiom: low-level, language-specific solution; depends on language features and does not transfer well.

Data Coupling

needed when modules share state/data; naively sharing mutable data intordices maintanance, consistency, safery issues

Approach 1: Restricting Access (Encapsulation)

  • exposing internal data creates maintenance (other code relies on internal representation), synchronization and concurrency problems

-> use narrow public interfaces (getters, setters) with pre- and post-conditions -> single owner for mutable sub-objects (copy & move instead of aliasing)

class Coordinate {
    // private representation prevents direct access and exposure
    double radius, angle;
public:
    // getters and setters enforce invariants and hide internal changes
    double get_x() { return cos(angle) * radius; }
    void set_radius(double r) {
        if (r >= 0) radius = r;
    }
};

Approach 2: Making Shared Data Immutable

  • eliminates issues related to mutation, invariants, synchronization, and side effects by ensuring shared data never changes after creation.
class Coordinate {
    // const members make shared data immutable and safe from side effects
    const double x, y;
public:
    Coordinate(double x_val, double y_val) : x(x_val), y(y_val) {}
    double get_x() const { return x; }
};
 

Approach 3: Avoiding Shared Data (Pipes and Filters)

  • Pipes and Filters Architecture: Eliminates shared state entirely through structured data flow
  • Components: Filters read, compute, and write data, while pipes (asynchronous FIFO streams) carry data between filters
#include <vector>
 
// pipes and filters avoid shared state entirely by passing transformed data streams
auto filter_data(const std::vector<int>& input) {
    std::vector<int> output;
    for (int val : input) {
        if (val > 0) output.push_back(val * 2);
    }
    return output;
}
 

Procedural coupling

modules interact through direct functions/method calls

- Code Reuse: A caller depends entirely on the presence of the callee, making independent compilation, testing, and reuse difficult. - Code Evolution: Modifying or removing a callee’s signature forces changes across all dependent callers. - Code Understanding: Extensive direct calling produces dense, tangled dependency graphs that obscure system behavior and increase the risk of unintended side effects.

mitigation strategies

  • relocate data processing/reasoning into module where relevant data lives
  • layered Architecture strict downwards dependency rule, each layer depends only on the one immediately below (e.g. presentation tier -> logic tier -> data tier)
  • Observer pattern: dynamic runtime registration instead of static, compile-time one. Components trigger notifications without needing to know the specific types or number of responding components
  • Model-View-Controller (MCV): Separates core data and functionality (Model), user interfaces (View), and input/modification handling (Controller), utilizing observer-based change notifications to keep multiple views synchronized.

-> all patterns introduce indirection; tracing execution flow becomes more difficult!

timestamp 2026-10-28

Tip: Leave stuttering out for the first few traces -> forces changes in the traces, makes finding interesting traces easier

Question

Is it possible to turn of stuttering for the first few steps?

Question

Is all disj b,c : Book the same as all b,c : Book | b != c =>

Question

Code expert: traffic light: stuttering is needed, but with it, the traces are boring

Question

Code expert: song: simplifying int, why?

Tip: Statistically, the longest answer is the correct one

Tip: for dynamic models, convert facts to preds and then check that they hold -> much cleaner

timestamp 2026-11-04

Class Coupling

OO coupling (types, inheritance, object cration) introduces problems

  • solution: abstraction, aggregation, externalisation
  1. Coupling via types
    • Problem: A class that directly names a concrete type (like vector<int>) becomes locked to it, preventing reuse with other compatible structures (like list<int> or streams).
    • Solution: Depend on abstract interfaces, iterators, or templates instead of concrete implementations.
// tightly coupled to vector
class Printer {
    std::vector<int> data;
};
 
// decoupled using templates
template <typename Container>
class Printer {
    Container data;
};
  1. Coupling via inheritance
    • Problem: Fragile base class: subclasses are tightly bound to superclass. If it changes, they make break
    • Solution: aggregation (members instead of extending inheritance) + explicit delegation
class CountingSet {
    MySet mySet; // aggregate instead of inherit
    int count = 0;
public:
    bool add(const std::string& elem) {
        count++;
        return mySet.add(elem); // explicit delegation
    }
};
  1. Coupling via object creation
    • Problem: Direct instantiation (e.g., auto db = MongoDB(...)) makes code hard to test in isolation and impossible to reuse with alternative components.
    • Solution: Externalise object creation by passing dependencies in via constructors, abstract factories, or dependency injection frameworks.
class App {
    Database& db;
public:
    // externalise creation via constructor injection
    App(Database& database) : db(database) {}
};

Parameterisation

Adaptation designs code to absorb change rather than breaking by it.

  • solution: parameterise values, types, data structures, and algorithms
  1. What can be made generic
    • Problem: Hard-coded choices (fixed values, types, containers, or operations) limit reuse and rigidity against change.
    • Solution: Use templates, iterators, abstract bases, and callables to let clients influence behaviour.
// generic accumulation over any iterator, type, and operation
template<typename InputIt, typename T, typename BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op);

Specialisation & the Visitor Pattern

Specialisation customises behaviour via subclasses; the Visitor pattern solves the expression problem trade-off between adding data variants vs. operations.

  • solution: dynamic method binding or Visitor pattern
  1. Dynamic method binding
    • Problem: Adding new operations is hard because it touches every existing subclass.
    • Solution: Use virtual methods on subclasses when new data variants (cases) are added often.
class Exp {
	public:
	virtual double eval() const = 0;
};
class Literal : public Exp {
	double val;
public:
	double eval() const override { return val; }
};
  1. The Visitor pattern
    • Problem: Standard inheritance makes adding new operations expensive as code scales.
    • Solution: Use double dispatch (accept + visit) to make adding new operations easy at the cost of making new data variants hard.
class Exp {
public:
	virtual void accept(Visitor& v) = 0;
};
class Visitor {
public:
	virtual void visitLiteral(Literal* e) = 0;
	virtual void visitAddition(Addition* e) = 0;
};

todo the visitor pattern needs practice

Design patterns

1. Creational

abstract factory interface for creating a family of related objects; client never names concrete classes.

struct GUIFactory { virtual Button* makeButton() = 0; virtual Checkbox* makeCheckbox() = 0; };
struct WinFactory : GUIFactory { Button* makeButton() override { return new WinButton; } /*...*/ };
// client only uses GUIFactory&, gets consistent Win/Mac widget families

singleton guarantee exactly one instance with a global access point

class Logger {
  Logger() = default;
 public:
  static Logger& instance() { static Logger l; return l; }
  void log(const std::string& s);
};
// Logger::instance().log("hi"); -> one shared logger, lazy-initialised

2. Structural

adapter wrap an incompatible interface to fit the one the client expects.

struct JsonProvider { virtual std::string json() = 0; };
class XmlToJsonAdapter : public JsonProvider {
  XmlLib& lib;                                // existing, incompatible
 public:
  std::string json() override { return convert(lib.xml()); }
};

decorator wrap an object with the same interface to add behaviour at runtime.

struct Stream { virtual void write(const std::string&) = 0; };
class Buffered : public Stream { Stream& inner; /* flush on size */ };
class Encrypted : public Stream { Stream& inner; /* encrypt first */ };
// Encrypted(Buffered(FileStream)) -> compose behaviour without subclass explosion

3. Behavioural

Observer subject notifies a dynamic list of observers without knowing their types.

struct Observer { virtual void update() = 0; };
class Button { std::vector<Observer*> obs;
 public: void attach(Observer* o){obs.push_back(o);}
         void click(){ for (auto o:obs) o->update(); } };

Strategy swap an algorithm behind a common interface, chosen at runtime.

struct SortStrategy { virtual void sort(std::vector<int>&) = 0; };
class Sorter { SortStrategy& s; public: void run(std::vector<int>& v){ s.sort(v); } };
// Sorter{QuickSort{}} vs Sorter{BubbleSort{}} -> algorithm varies, Sorter unchanged

Template method base class fixes the algorithm skeleton, subclasses override steps -> see Parameterisation

class Game {
 public:
  void run() { init(); play(); end(); }      // fixed skeleton
 protected:
  virtual void init() = 0; virtual void play() = 0; virtual void end() = 0;
};
class Chess : public Game { void play() override { /* chess moves */ } /*...*/ };
// Game::run() is reused; only the steps vary

for each API, ask three questions in order:

  1. What does the class take in its constructor / method signature? (a same-interface object → decorator; a different interface → adapter; a behaviour object → strategy)
  2. How do clients obtain an instance? (getX() static accessor → singleton; a factory method returning siblings → abstract factory)
  3. Who calls whom? (base class calls subclass hooks → template method; subject calls a registered list → observer)

Documentation

timestamp 2026-11-07 mostly-ai !

Why document?

Design decisions and stable guarantees can’t be reliably recovered from code; document them as spec and for maintenance.

What to document

Document essential, stable properties: what clients may rely on, not how it’s achieved.

AudienceQuestionDocument
ClientsHow do I use it?Parameters, implicit state, results, effects, invariants
MaintainersHow does it work, how may I change it?Internals, aliasing, implementation invariants, algorithm rationale

Interface docs cover member functions, constructors, public members, supertypes. For each function:

  • argument constraints
  • required receiver or ambient state (e.g. stream must be in goodbit)
  • exact return value and out-parameters
  • effects: receiver, heap, control flow, performance

Plus invariants visible to clients:

  • single-state (the list is sorted)
  • history (the stopwatch is monotonic, the list is immutable)

And global properties such as thread-safety, stated once for the whole class.

Implementation docs cover the same for private and protected helpers, in more depth:

  • effects on member variables
  • relationships between members
  • internal sharing and aliasing
  • implementation invariants maintainers must preserve but clients cannot rely on
  • rationale behind non-obvious algorithm choices

Only what clients can see goes in interface docs; everything else goes to implementation docs.

How to document

comments -> annotations -> types -> effect systems -> assertions -> contracts.

  • opinion: trade overhead for tool support; mix techniques; prefer simpler design over more documentation
TechniqueExplanationExample
CommentsFree-text notes next to code; for humans only, not checked, can drift out of sync// PRE: x, y >= 0
AnnotationsMachine-readable tags on declarations; part of the language, checked by tools@NonNull, @deprecated
Types & modifiersCompiler-enforced; document mutability, sharing, non-negativityconst, uint, Foo& vs Foo
Effect systemsTypes extended to say what a function doesKoka exn/div, C++ noexcept
AssertionsConditions checked at runtime; fail-fastassert(a > 0 && b > 0);
ContractsStructured pre/postconditions and invariants on declarations; meant for static verification, can express things assertions can’t (e.g. termination)Contract.Invariant(this.y >= 0);

Reading left to right

You write more and get more:

  • left: cheap and flexible but unchecked
  • right: costly but precisely machine-verified