IB COMPUTER SCIENCE | B3.1.2 Class Design and Behaviour

Lesson objective

Construct class designs with appropriate attributes, methods, behaviour contracts and UML relationships that satisfy application requirements.

Learn

B3.1.2 | CLASS DESIGN AND BEHAVIOUR

01 | DESIGN THE RESPONSIBILITIES BEFORE WRITING THE BODY

A library asks for software that identifies each physical copy, records who has borrowed it and rejects a second loan until the first copy is returned. Before coding, decide which object owns each piece of information and which operations are allowed to change it.

A class design describes the state a kind of object needs, the methods it offers and the behaviour those methods promise. A drawing of class names alone is not a complete design.

This common SL/HL lesson constructs designs from requirements and uses UML class diagrams to communicate attributes, operations and relationships. We keep behaviour contracts alongside diagrams because signatures alone do not explain all the rules.

02 | BEGIN WITH CONCRETE REQUIREMENTS

Our first design manages current loans only: each BookCopy has a unique copy ID and title; it starts available; an available copy can be borrowed by an existing student; a borrowed copy rejects another borrowing; returning a borrowed copy makes it available. Returning an already available copy reports failure.

The surrounding application verifies that the student exists before requesting a loan. The object still rejects empty student-ID text. Stored data, user authentication and simultaneous requests require separate application design.

Treat these as the supplied rules for the example. If a real client needs loan history, due dates or a borrowing limit, add those requirements explicitly rather than pretending the first model already satisfies them.

03 | FIND CANDIDATES, THEN CHECK THEIR ROLES

Requirement phrase Candidate design role Reason
Physical book copy Class BookCopy Has identity, state and operations
Copy ID and title Attributes Describe a particular copy
Current borrower ID Optional attribute in the current-state model Records whether and by whom it is borrowed
Borrow and return Methods Request controlled state transitions
Borrowing rejection Behaviour / rule Defines when a method must leave state unchanged
Pink page heading User-interface detail Not a BookCopy domain responsibility

Nouns and verbs are useful clues, not a mechanical design algorithm. A noun can become an attribute rather than a class; a verb can belong to an application service rather than every domain object.

04 | GIVE THE CLASS ONE COHERENT JOB

BookCopy manages the current loan state of one copy. It should not also draw the whole website, send every email, connect to all databases and generate every report. Those responsibilities change for different reasons.

High cohesion means its data and methods support a focused purpose. Clear collaboration lets other units handle lookup, persistence and display while calling the copy’s operations.

A design can have too many tiny classes as well as one oversized class. Choose useful responsibilities based on the requirements, then test whether the objects have enough information to perform them.

05 | READ THE THREE UML COMPARTMENTS

BookCopy
- copyId: String
- title: String
- borrowerId: String [0..1]
+ BookCopy(copyId: String, title: String)
+ isAvailable(): Boolean
+ borrow(studentId: String): Boolean
+ returnBook(): Boolean
BookCopy class: name, attributes, then operations.

UML means Unified Modeling Language. A basic class rectangle has a name compartment, an attributes compartment and an operations compartment, separated by horizontal lines. An operation describes the callable service; its implementation is the method code.

Read this as a type-level design for any BookCopy object. It is not an object snapshot with copyId = C17 and title = Networks. The diagram declares what instances can store and do, rather than one instance’s current values.

06 | ATTRIBUTE NOTATION: NAME, TYPE AND MULTIPLICITY

The attribute entry - copyId: String gives visibility, name and type. String indicates text; it does not specify one particular ID. borrowerId: String [0..1] indicates an optional value, zero or one borrower ID.

Here no borrower means available. Do not store an independent available flag unless you also design how to keep it consistent with borrowerId. Two editable representations of the same fact can disagree.

The design requires copyId to be unique across the managed copies. A String type alone does not enforce that cross-object rule; the collection or persistence layer must preserve it.

07 | VISIBILITY: WHAT CALLERS MAY USE

Symbol UML meaning Purpose
+ Public Part of the intended callable interface
- Private Restricted internal state or operation
# Protected Access for an appropriate inheritance context; language rules vary

The design makes borrowerId private and provides controlled borrow/return operations. This communicates an intended access boundary, not a guarantee that every language implements it identically.

Java private can enforce member access restrictions. In Python, _borrower_id conventionally signals non-public intent but does not enforce UML private access. Map design intent honestly to the implementation language.

08 | OPERATION SIGNATURES: INPUTS AND RESULTS

Signature part Example Meaning
Operation name borrow Requested behaviour
Parameter and type studentId: String A value the caller supplies
Return type : Boolean after parentheses A True/False result for the caller
No parameters isAvailable() Reads the receiving object’s state without another input

The full signature + borrow(studentId: String): Boolean does not tell you which situations return True. The contract must say that a successful state change returns True and an already borrowed copy returns False.

A returned Boolean is not a printed message and not another student ID. Pick result types that support callers clearly. The object receiving the method is not listed as an extra UML parameter here.

09 | INITIALIZATION IS PART OF THE DESIGN

The displayed BookCopy(copyId: String, title: String) line is a constructor-style creation notation used in this lesson. It supplies initial identifying data and establishes borrowerId as absent. Constructor notation may vary between languages and diagram conventions; no ordinary result type is shown here.

In Python, calling the class creates an instance and __init__ initializes its state. In Java, the constructor has the class name. Both should leave a valid starting object.

Do not require callers to remember a second unrelated operation to make a newly created copy available. State the initialization rule so every instance starts consistently.

10 | A CONTRACT DESCRIBES MORE THAN A SIGNATURE

Contract part borrow(studentId) in this model
Purpose Attempt to record a current loan for this copy
Inputs / assumptions Student ID supplied as text; surrounding application has checked existence
Input validation Empty or non-text ID raises a documented validation error before mutation
Success If available, store the cleaned ID and return True
Rejection If already borrowed, return False and preserve the existing borrower
Side effects Only this copy’s loan state changes on success

A precondition states what is assumed before the operation; a postcondition states what holds after it completes normally. Also specify errors or rejection paths.

A method name that sounds sensible cannot replace these details. Decide who checks which rule so neither the caller nor the object silently assumes someone else did it.

11 | CONSTRUCT ALL THREE BEHAVIOUR CONTRACTS

Operation Starting state Result State afterwards
isAvailable() Either valid state True if no borrower, otherwise False Unchanged
borrow(validId) Available True On loan to that ID
borrow(validId) On loan False Original borrower preserved
returnBook() On loan True Available; borrower removed
returnBook() Available False Still available

A query such as isAvailable inspects state. Commands such as borrow and returnBook can change it. This design returns a result for both success and rejected transitions.

Keep an invariant: a copy has at most one current borrower, and availability corresponds to an absent borrower. A rejected operation must not quietly damage that invariant.

12 | WALK THROUGH A CONCRETE OBJECT

Call on C17 Returned result borrowerId afterwards
Create BookCopy(C17, Networks) A new instance Absent
borrow(S01) True S01
borrow(S02) False S01
returnBook() True Absent
returnBook() False Absent

This is a behaviour trace of an object using the design. The second borrow does not overwrite S01, because rejection includes preservation of the original state.

C18 is another instance; these calls do not update its borrower. The diagram defines shared operations but the trace describes one receiver’s instance state.

13 | INTERACTIVE: CHECK A DESIGN AGAINST ITS REQUIREMENT

For each requirement, choose the design element that actually satisfies it. Then check the contracts, not just whether a name looks familiar. This activity evaluates the supplied alternatives; other well-justified complete designs may also be valid.

14 | METHODS NEED ORDERED INTERNAL LOGIC

A design of behaviour can include structured steps without committing every implementation detail. For borrow: validate the supplied ID; if already borrowed, return False without changing state; otherwise store the cleaned ID and return True.

The order expresses a policy. Here an invalid ID raises an error even if the copy is already borrowed, because validation occurs first. Another policy needs to be stated consistently.

For returnBook: if available, return False; otherwise clear the borrower and return True. The same signature with different rules could create a different system.

15 | CHECK THAT THE DESIGN CAN BE IMPLEMENTED

class BookCopy:
    def __init__(self, copy_id, title):
        self._copy_id = copy_id
        self._title = title
        self._borrower_id = None

    def is_available(self):
        return self._borrower_id is None

    def borrow(self, student_id):
        if not isinstance(student_id, str) or not student_id.strip():
            raise ValueError("Student ID required")
        if not self.is_available():
            return False
        self._borrower_id = student_id.strip()
        return True

    def return_book(self):
        if self.is_available():
            return False
        self._borrower_id = None
        return True

copy = BookCopy("C17", "Networks")
print(copy.borrow("S01"))
print(copy.borrow("S02"))
print(copy.return_book())

The outputs are True, False, True. The UML uses language-neutral camelCase names; this Python mapping uses conventional snake_case, so borrow remains borrow while isAvailable maps to is_available. Maintain a clear mapping rather than accidentally omitting an operation.

This short implementation checks that the state and contracts are sufficient. A construction question asking for a class design still needs the requested design representation, not only a block of code.

16 | NEW REQUIREMENT: KEEP LOAN HISTORY

The school now wants every past loan, including who borrowed a copy, the issue date, due date and eventual return date. A single current borrower field cannot retain multiple events over time.

Introduce a Loan class representing one loan event. Link each Loan to a Member and a BookCopy, and store dates on the Loan rather than repeating member details or putting all history into a single string.

This is a revised model, not additional fields to bolt onto the original current-only representation without reconciliation. Decide one authoritative representation of active loans and derive availability from it.

17 | DESIGN THREE COLLABORATING CLASSES

Member
- memberId: String
- name: String
+ getMemberId(): String
Member class: name, attributes, then operations.
BookCopy
- copyId: String
- title: String
+ getCopyId(): String
BookCopy class: name, attributes, then operations.
Loan
- issueDate: Date
- dueDate: Date
- returnedDate: Date [0..1]
+ isActive(): Boolean
+ finish(returnDate: Date): Boolean
Loan class: name, attributes, then operations.

In this history model, association links identify the Member and BookCopy for a Loan. They are not repeated as extra scalar ID attributes in this conceptual diagram. An implementation or database mapping can choose suitable references or stored keys.

Loan.isActive checks whether returnedDate is absent. Loan.finish records a valid return once and rejects an already finished event. A LoanService coordinates creating loans and checking whether a copy already has an active one. This avoids retaining a second independent current-borrower fact on BookCopy.

18 | UML ASSOCIATIONS AND MULTIPLICITIES

Read the number at the opposite end from the object you start with: a Member links to 0..* Loans; a Loan links to 1 Member. A BookCopy links to 0..* historical Loans; each Loan links to 1 BookCopy.

0..* means zero or more. 1 means exactly one. Multiplicity expresses how many related objects are allowed; it is not the number currently created in a sample run.

19 | HISTORY IS MANY; ACTIVE LOANS ARE RESTRICTED

A copy can have many loans across its lifetime but at most one active loan at a time. The association multiplicity 0..* correctly describes the history and does not, by itself, enforce the active-state rule.

Add the constraint: “For each copy, at most one linked Loan has returnedDate absent.” LoanService checks and creates the new event through a coordinated operation.

Database constraints or transactional coordination may be needed for simultaneous requests. A diagram communicates a requirement; it does not automatically enforce it in a running system.

20 | SHOW A COLLABORATION AS A SEQUENCE OF RESPONSIBILITIES

Step Responsible unit Action
1 Interface / application Obtain member and copy identifiers
2 LoanService Locate valid Member and BookCopy objects
3 LoanService / storage Check and coordinate the no-active-loan rule
4 Loan creation Establish member/copy links and dates; returnedDate absent
5 Persistence service Save the accepted event through the chosen failure policy
6 Interface Display success only after the agreed successful outcome

BookCopy does not need a database connection or screen widget to represent its identity. Loan captures event state; a service coordinates operations spanning several objects.

A class diagram shows structural relationships. This responsibility sequence explains collaboration over time. A UML sequence diagram could express messages formally, but this table is a readable supporting behaviour plan.

21 | ASSOCIATION IS NOT AUTOMATICALLY INHERITANCE

A Loan is linked to a BookCopy, but a Loan is not a kind of BookCopy. Use an association for that link, rather than drawing an inheritance relationship just because the objects interact.

If BookCopy and LaptopCopy genuinely specialize ResourceCopy under a compatible contract, inheritance can be considered. UML generalization uses a solid line with a hollow triangle pointing toward the more general superclass.

Plain association lines do not specify ownership lifetime, navigation or composition diamonds by default. Only add a more specific relationship notation when the requirements justify its meaning. Detailed multiple-class inheritance is developed in the HL objectives.

22 | BUILD TRACEABILITY FROM RULE TO DESIGN TO TEST

Requirement Design element Test evidence
Identify same-title copies BookCopy.copyId and uniqueness rule C17 and C18 remain distinguishable
Reject a second current loan Current-only borrow contract, or revised service active-loan constraint Second request rejected; original loan preserved
Permit a return once returnBook, or revised Loan.finish contract First succeeds; second rejected
Retain historical dates Loan date attributes and links Returned event remains retrievable
Empty-loan history allowed 0..* multiplicities A new copy/member has no linked events

The alternatives in this table are two explicitly different models. Do not mix their state without deciding how facts remain authoritative.

A design is useful when every required behaviour has an owner and every important rule has a checkable expected result.

23 | TRANSFER THE METHOD TO A DIFFERENT SCENARIO

A classroom quiz needs questions with text and correct answers, and attempts that record a student’s responses and score. Question, Quiz and Attempt are useful candidates, but the exact design depends on whether questions are reused and whether attempt history is retained.

Place question text on Question rather than duplicating it in every attempt. A method such as checkAnswer(response: String): Boolean needs a defined matching rule: exact case, normalized case or another policy.

An Attempt can record responses and coordinate score calculation without becoming a kind of Question. Identify relationships and multiplicities from the actual requirements rather than copying the library diagram unchanged.

24 | CONSTRUCT IT: DESIGN A SCHOOL EQUIPMENT ITEM

An EquipmentItem has a unique item ID, name and non-negative condition score from 0 to 5. Staff can update the condition; an out-of-range update must be rejected without changing the old score. Construct a class diagram and a method contract.

Reveal one possible design
EquipmentItem
- itemId: String
- name: String
- condition: Integer
+ EquipmentItem(itemId: String, name: String, condition: Integer)
+ getCondition(): Integer
+ updateCondition(value: Integer): Boolean
EquipmentItem class: name, attributes, then operations.

Initialization accepts valid values or raises a documented validation error. updateCondition receives an integer, returns True and updates for 0–5 inclusive, otherwise returns False without mutation. The contract assumes integer input; a separate wrapper or typed interface handles non-integers. Item-ID uniqueness is maintained by the managing collection/service.

25 | COMMON DESIGN ERRORS

Error Repair
Only list class names Include appropriate attributes, operations and contracts
Confuse sample values with types Write copyId: String in a class design; C17 belongs in a snapshot
Return type missing or misleading State what callers actually receive
One borrower string stores complete history Introduce event objects when history is required
Multiplicity 0..* enforces one active loan Add the active-state constraint separately
A link means inheritance Distinguish association from meaningful is-a specialization
Every field needs a public setter Provide controlled operations preserving the required rules
Diagram silently guarantees storage and security Assign those responsibilities and failure policies explicitly

A neat diagram can still describe an inadequate design. Review it against the scenario and walk through both successful and rejected operations.

26 | A COMPLETE CONSTRUCT RESPONSE

Start with the requirements and scope. Identify coherent classes, attribute types and methods with parameter/result types. Draw labelled relationships and justified multiplicities, and describe initialization, state changes and failure behaviour.

Then walk through a small object example and trace each requirement to a design owner and test. Revise any duplicated state, missing event history or operation with no clear responsibility.

The next lesson distinguishes static and non-static variables and methods, building on the difference between class-level definitions and instance-specific state.

MATCH THE CLASS-DESIGN IDEA

Terminology

Terminology

Class design

A plan for a class’s state, operations, contracts and relationships.

Requirement

A behaviour, property or constraint the solution must satisfy.

Responsibility

A coherent piece of information or behaviour assigned to a unit.

UML

Unified Modeling Language, a notation for communicating software models.

Class compartment

A region of a class rectangle, such as name, attributes or operations.

Attribute

A named property storing information about an instance or class.

Attribute type

The kind of value allowed by a property’s design.

Operation

A specified callable service with a name and signature.

Method

An implementation of an operation’s behaviour.

Signature

An operation’s identifying input and result information in the chosen notation.

Parameter

A named input declared for an operation.

Return type

The type of result supplied to a caller.

Visibility

The intended access boundary for a member.

Public +

UML visibility marking an accessible interface member.

Private -

UML visibility indicating restricted internal members.

Protected #

UML visibility associated with specialization access; mapping depends on language.

Initialization

Establishing a valid starting state for an instance.

Contract

The promised inputs, results, state effects and failure behaviour.

Precondition

A condition assumed before an operation proceeds.

Postcondition

A condition promised after an operation’s normal completion.

Invariant

A property expected of valid state across operations.

Association

A structural relationship allowing links between instances.

Multiplicity

How many related instances may be linked at a given end.

0..1

Zero or one related value/instance.

0..*

Zero or more related instances.

Generalization

An inheritance/specialization relationship toward a more general classifier.

Cohesion

How closely a unit’s contents support its responsibility.

Traceability

A connection from requirements to design elements and evidence.

Authoritative state

The chosen representation treated as the source for a fact.

Behaviour trace

A record of operations, results and resulting state over time.

Questions

Questions

CHECK YOUR UNDERSTANDING

Select all correct choices. Each exact set earns one point.

1. Which belong in a useful class design?
2. Which interpret the BookCopy UML correctly?
3. Which visibility interpretations are correct?
4. Which are expressed by borrow(studentId: String): Boolean?
5. Which preserve the current-only loan invariant?
6. Which justify a new Loan class for history?
7. Which describe the history diagram?
8. Which must be stated separately from historical 0..* multiplicity?
9. Which distinguish relationships correctly?
10. Which strengthen a constructed design?

EXPLAIN AND COMPARE

Write your answers before revealing each sample.

1. Construct a UML design for the current-only BookCopy model.

2. Explain why class diagrams use types rather than only example values.

3. Describe the contract for rejecting a second loan.

4. Explain why a single current borrower field is insufficient for loan history.

5. Trace borrow S01, borrow S02, return and return on a newly available C17.

6. Explain the meanings of the Member–Loan multiplicities.

7. Explain why historical multiplicity does not enforce one active loan.

8. Distinguish an association from generalization in this scenario.

9. Construct an updateCondition contract for integer scores from 0 to 5.

10. Explain how traceability improves class design.

11. Describe a clear separation between domain state and interface responsibilities.

12. Construct a checklist for a complete class-design response.

CONSTRUCT IT | QUIZ ATTEMPT DESIGN

Construct a class design for a QuizAttempt that records one student ID, a non-negative score and whether the attempt has been submitted. It starts unsubmitted with score 0. Adding a non-negative integer number of marks is allowed only before submission; a rejected update leaves state unchanged. Include attributes, method signatures, initialization and success/rejection contracts.

Reveal one possible design

Private studentId: String, score: Integer and submitted: Boolean. Creation supplies a valid student ID, sets score to 0 and submitted to False. Public addMarks(marks: Integer): Boolean accepts non-negative integer marks only while unsubmitted, otherwise returns False without changes. Public submit(): Boolean changes unsubmitted to submitted and returns True, or returns False if already submitted. Public getScore(): Integer reports the score. This simplified scenario has no maximum score; add a maximum only when required, and specify how the caller validates student existence and non-integer inputs.

Flashcards

Flashcards

Click to flip. Select the ideas you need to revisit.

0 cards selected for revision.

Selections are kept while this page is open.

Workbook

Workbook

COMING SOON

The workbook for B3.1.2 Class Design and Behaviour is coming soon. Complete the matching task and written questions in your exercise book.