0% found this document useful (0 votes)
7 views39 pages

Solutions

This document is an official mock exam answer key for the Software Engineering Principles & Practices course at Egypt-Japan University of Science and Technology. It includes detailed answers to various questions covering topics such as requirements engineering, architectural layering, system resilience, and test-driven development. The exam assesses students' understanding of software engineering concepts and practices through structured questions and scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views39 pages

Solutions

This document is an official mock exam answer key for the Software Engineering Principles & Practices course at Egypt-Japan University of Science and Technology. It includes detailed answers to various questions covering topics such as requirements engineering, architectural layering, system resilience, and test-driven development. The exam assesses students' understanding of software engineering concepts and practices through structured questions and scenarios.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Department of Computer Science and Software Engineering

Egypt-Japan University of Science and Technology (E-JUST)

Course Code: CSE322 / CSE323 Semester: Spring 2026


Course Title: Software Engineering Principles & Practices Duration: Solutions Memo
Document Type: Official Mock Exam Answer Key Total Marks: 30 Marks

Question 1: Requirements Engineering & Actor Classification (4 Marks)


(a) Requirements Extraction (1 Mark)
• Functional Requirement (FR): The system shall allow drivers to locate charging blocks and
reserve time slots via a mobile application.

• Non-Functional Requirement (NFR): The system must process and confirm slot reservations
in under 2 seconds (Quality Attribute: Performance / Responsiveness).

(b) Actor Classification Table (1.5 Marks)

Actor Name Classification Engineering Rationale


Driver Primary Initiates the use case to reserve slots; is the direct system beneficiary.
Station Controller Supporting Responds to and assists the primary actor by monitoring hardware power.
Grid Operator Offstage Never interacts with live system directly; has analytical stake in midnight metrics

(c) Requirement Taxonomy Classification (1.5 Marks)


1. NFR: Security attribute; governs how data must be securely handled in transit rather than a
specific user feature.

2. FR: Functional behavior; defines an explicit operational capability accessible to the end user.

3. NFR: Scalability/Performance metric; dictates operational quality thresholds under concurrent


load spikes.

Question 2: Architectural Layering & Information Hiding (4 Marks)


(a) Architectural Layer Assignment (1.5 Marks)
1. hash driver credentials(input pin) → Technical Services Layer
Rationale: Cross-cutting cryptographic security utility applied system-wide.

2. write relay register(voltage level) → Hardware Layer


Rationale: Manipulates physical electronic hardware registers and pin configurations directly.

3. cache station status(station id, status) → Technical Services Layer


Rationale: Common state optimization infrastructure independent of core business criteria.

(b) Connector Specification & Rationale (2.5 Marks)

FUNCTION set_power_flow ( is_enabled : BOOLEAN )

Information Hiding Rationale: By exposing an abstract BOOLEAN state interface, the upper Business
Logic layer remains fully isolated from lower hardware configuration metrics such as target electronic
voltages (0V vs 12V) or physical register flags.

1
Question 3: System Resilience & Logic Auditing (5 Marks)
(a) Failure Identification (2 Marks)
1. Synchronous Blocking: The SYNC call halts execution on the thread, making the remote system
vulnerable to complete freezes if network latency spikes.

2. Infinite Busy-Wait (Retry Storm): The CONTINUE structure re-fires identical request payloads
immediately during server overloads without incorporating delays, actively exacerbating the target
server’s failure state.

(b) Corrected Logic Implementation (3 Marks)

FUNCTION s y n c_ d r on e _ lo c a ti o n ( drone_id , coordinates ) :


MAX_ATTEMPTS = 5 # Pattern 1:
Bounded iteration limit
FOR i FROM 1 TO MAX_ATTEMPTS :
STATUS = AWAIT C A L L _ C O O R D I N A T I O N _ S E R V E R _ A S Y N C ( drone_id , coordinates )
# Pattern 2: Asynchronous
IF STATUS . code == " SUCCESS " :
RETURN STATUS
ELSE IF STATUS . code == " SERVER_OVERLOAD " :
WAIT (2 * i ) # Pattern 3:
Exponential Back - off Delay
CONTINUE
ELSE :
RETURN " EXECUTION_ERROR "
RETURN " R E S I L I E N C E _ T I M E O U T _ F A I L U R E " # Graceful failure
boundary

Question 4: Specification Artefacts & QA Refinement Loop (5 Marks)


(a) Gherkin Scenario: Happy Path (1.5 Marks)

Feature : Ride Cancellation


Scenario : Commuter cancels ride successfully before driver departs
Given the commuter has a confirmed scheduled ride
And the assigned driver status is " STATIONARY "
When the commuter requests to cancel the ride
Then the ride status updates to " CANCELLED "
And no financial cancellation penalty is applied to the commuter account

(b) Gherkin Scenario: Failure Path (1.5 Marks)

Feature : Ride Cancellation


Scenario : Commuter fails to cancel ride after driver departs
Given the commuter has a confirmed scheduled ride
And the assigned driver status is " EN_ROUTE "
When the commuter requests to cancel the ride
Then the cancellation request is rejected with an error message
And the ride status remains " EN_ROUTE "

2
(c) Senior QA Audit Log Table (2 Marks)

Vague Adjective Target Quality Quantified Testable Metric Replacement


“highly responsive” Performance Cancellation verification API latency ≤ 150 ms under 95th percentile load.
“completely secure” Security All payloads require TLS 1.3 encryption and OAuth2 tokens expiring in 15 min.

3
Question 5: AI-Assisted Engineering & Golden Prompt Crafting (4
Marks)

Role : You are a Principal Software Engineer specializing in high - throughput


transactional railway systems .

Context : We are building an international cross - border booking sub - system .


Bookings exceeding $1 ,000 must be routed to a manager approval queue .
Payment failures must be retried up to 4 times using an exponential back -
off strategy before throwing a system exception .

Examples :
- Example 1: Input booking is $500 . Payment succeeds on try #1. System sets
booking status to ’ CONFIRMED ’ and returns success .
- Example 2: Input booking is $1200 . System sets status to ’ PENDING_APPROVAL ’
and forwards transaction to the Manager Audit Queue without attempting
immediate payment .

Task : Write the core execution logic for the p r o c e s s _ r a i l _ b o o k i n g ( booking_id ,


amount ) function matching these parameters .

Negative Constraints :
1. Do NOT log raw credit card numbers or CVV codes within any system audit
trails or error logging outputs .
2. Do NOT allow unapproved bookings over $1 ,000 to bypass the validation
workflow under any edge - case failure conditions .

Question 6: Test-Driven Prompting (TDP) & Edge Case Cage (4


Marks)
(a) Pre-Implementation Failing Unit Test (1.5 Marks)

FUNCTION t e s t _ a l l o c a t e _ c o r e s _ b o u n d a r y _ m a x () :
# Establish mathematical constraint before implementation code exists
EX PE CT _R AI SE _E RR OR = False
TRY :
a l l o c a t e _ c o m p u t e _ c o r e s (8)
CATCH ValueError :
EX PE CT _R AI SE _E RR OR = True
ASSERT EXP EC T_ RA IS E_ ER RO R == False

(b) Edge Case Cage / Padlocks (1.5 Marks)


1. Boundary Padlock Assertion: ASSERT allocate compute cores(8) == "SUCCESS"

2. Threshold Padlock Assertion: ASSERT RAISES(ValueError, allocate compute cores, 9)

3. Extreme Padlock Assertion: ASSERT RAISES(ValueError, allocate compute cores, 100)

(c) Prompt Negative Constraint Appendage (1 Mark)


"Negative Constraint: Do NOT append code that silently truncates or clamps inputs exceeding
8 back down to 8 (e.g., inside an IF statement); you must explicitly raise a ValueError."

4
Question 7: Traceability Matrices & Process Violations (4 Marks)
(a) Use Case Cumulative Weight Calculations (1.5 Marks)
• UC-A (Inbound Log) = PW(REQ-1) + PW(REQ-5) → 5 + 3 = 8

• UC-B (Stock Audit) = PW(REQ-1) + PW(REQ-2) → 5 + 3 = 8

• UC-C (Procurement Order) = PW(REQ-2) + PW(REQ-3) + PW(REQ-4) → 3 + 4 + 2 = 9

(b) Orphaned Requirement Analysis (1 Mark)


• Identified Gap: REQ-6 (Predictive Stock Relocation) traces to zero production use cases.

• Architectural Meaning: This points to an orphaned requirement, proving to system de-


signer review panels that a requested business stakeholder demand was neglected during upstream
scoping.

(c) Lifecycle Implementation Prioritization (1.5 Marks)


• Decision: Implement UC-C (Procurement Order) first.

• Rationale: UC-C possesses the highest aggregate Priority Weight (Total PW = 9). Delivering
high-weight components first ensures engineering teams maximize early product lifecycle value
deployment.

(d) Process Integrity Audit (1 Mark)


• Technical Term: Gold Plating (or Scope Creep).

• Consequence: It incorporates unverified engineering code logic loops that have no requirement
documentation backings and zero testing coverage, creating budget waste and introducing un-
known surface defects.

5
EJUST — CSE322/CSE323 Software Engineering
Mock Final Examination — Answer Key
Total Marks: 100

Exercise 1: Requirements Engineering & Architecture [20 marks]


1.1 [5 marks]

• FR: The system shall allow students to order meals via a mobile app and unlock designated lockers
using a QR code. [2.5]
• NFR: The system shall maintain locker temperature between 2°C and 8°C for cold meals and above
60°C for hot meals (Food Safety / Reliability). [2.5] Grading note: NFR must be a quality attribute
(safety, performance, usability, reliability). “Use QR code” or “send email” are FR, not NFR.

1.2 [6 marks]

1. calculate_thermal_load(...) → Business Logic [1]. Rationale: Encodes domain rules about


food-type temperature targets. [1]
2. send_qr_email(...) → Technical Services [1]. Rationale: Infrastructure utility (email gateway)
usable by any layer; not a business rule. [1]
3. read_locker_thermistor() → Hardware [1]. Rationale: Direct physical sensor interaction. [1]
Trap: Students who place email in Business Logic because “it is part of the user flow” score partial
only.

1.3 [4 marks]

FUNCTION set_locker_climate(target_celsius: INTEGER)

Rationale: Hides PWM duty cycles, heating/cooling element voltages, thermistor resistance values, and
H-bridge polarity. Business Logic only specifies the target temperature; implementation details remain
concealed. [4] Acceptable alternative: FUNCTION set_locker_climate(mode: ENUM {HEATING, COOLING,
OFF}) if rationale clearly states hidden hardware details. A Boolean alone is insufficient here because
climate control is not binary.

1.4 [5 marks]

• Primary: Student [1]. Rationale: Initiates core goals (orders meal, requests pickup) and is the
main beneficiary. [0.5]
• Supporting: Cafeteria Staff [1]. Rationale: Responds to orders by preparing and loading meals;
secondary actor. [0.5]
• Offstage: Payment Gateway / Banking API [1]. Rationale: External system essential for billing
but not directly controlled or interacted with by the primary workflow. [1] Common mistake:
Omitting Offstage actor scores partial only.

Generated by [Link]
Exercise 2: System Resilience & Logic Auditing [20 marks]
2.1 [8 marks]

1. Synchronous Blocking [2]. The CALL_PAYMENT_GATEWAY_SYNC blocks the calling thread until the
gateway responds, rendering the UI / order queue unresponsive during payment. [2]
2. Infinite Busy-Wait / Retry Storm [2]. The WHILE True loop retries immediately (CONTINUE) on
timeout without exponential backoff or a bounded attempt limit, overwhelming the gateway and
wasting client resources. [2] Grading: “Slow code” or “it might crash” earns 0. Must name the
precise anti-pattern and explain thread/server consequences.

2.2 [12 marks]

FUNCTION process_payment(student_id, amount):


MAX_ATTEMPTS = 3
FOR i FROM 1 TO MAX_ATTEMPTS:
response = AWAIT CALL_PAYMENT_GATEWAY_ASYNC(student_id, amount)
IF [Link] == "SUCCESS":
RETURN response
ELSE IF [Link] == "GATEWAY_TIMEOUT":
WAIT(2^i * 1000) // Exponential backoff: 2s, 4s, 8s
CONTINUE
ELSE:
RETURN "PAYMENT_ERROR"
RETURN "TIMEOUT_FAILURE"

• Use of ASYNC / AWAIT [3]


• Bounded retry (MAX_ATTEMPTS) [3]
• Exponential backoff (not fixed delay) [3]
• Graceful failure return after exhaustion [3]

Exercise 3: Traceability & Process Integrity [20 marks]


3.1 [10 marks]

Requirement PW UC-1 UC-2 UC-3

REQ-1 5 X X
REQ-2 4 X
REQ-3 3 X
REQ-4 2 X X
Total PW 7 9 5

• UC-1: 5 + 2 = 7 [2]
• UC-2: 5 + 4 = 9 [2]
• UC-3: 3 + 2 = 5 [2]

Decision: Implement UC-2 (Pickup Meal) first. [2]


Justification: It delivers the highest stakeholder value (Total PW = 9) by combining authentication

Generated by [Link]
and food safety, the two most critical requirements. [2] Trap: Students who compute single-requirement
PW or omit the stakeholder-value justification score partial.

3.2 [5 marks]

• Name: Gold Plating (or Scope Creep) [2].


• Systemic harms: (any two of the following, 1.5 marks each, max 3)
– Wastes engineering resources on unrequested features.
– Introduces unverified complexity and potential defects.
– Pollutes the traceability matrix (no requirement backing).
– Creates untested functionality with no acceptance criteria.
– Diverts effort from validated use cases with higher PW.

3.3 [5 marks]

• Verification: “Did we build the system correctly?” [1]


Example: The QR scanner unlocks exactly the locker assigned to the student’s active order. [1.5]
• Validation: “Did we build the correct system?” [1]
Example: Students actually prefer locker pickup over counter collection during peak hours; observed
adoption rate � 70%. [1.5]

Exercise 4: Design & Specification [20 marks]


4.1 [8 marks]

(a) Happy path [3]:

Scenario: Student successfully picks up ready meal


Given the student has an active order with status "READY"
And the assigned locker is at safe temperature
When the student scans the valid QR code
Then the locker door unlocks
And the order status changes to "COLLECTED"

(b) Failure path [3]:

Scenario: Student scans invalid QR code


Given the student has an active order
When the student scans an expired or already-used QR code
Then the locker remains locked
And the system logs the rejected attempt
And the student receives an error message "Invalid or expired QR"

(c) Edge case [2]:

Scenario: Pickup attempted during thermal alarm


Given the student has a valid QR code for order "ORD-123"
And the locker temperature is outside the safe range
When the student scans the QR code
Then the locker remains locked
And the system displays "Pickup unavailable: temperature unsafe"

Generated by [Link]
And the incident is escalated to cafeteria staff

Grading: Happy path alone = Satisfactory. All three scenarios with correct Given/When/Then syntax =
Excellent.

4.2 [4 marks]

• “fast pickup” → “QR scan-to-door-unlock time � 3 seconds at the 95th percentile under
normal load.” [2]
• “secure storage” → “Lockers remain locked until a single-use, SHA-256-hashed QR code
is scanned; QR expires 15 minutes after meal readiness.” [2] Any quantifiable, testable
metric accepted. Vague replacements earn 0.

4.3 [4 marks]

1. Start: Refund request received. [0.5]


2. Activity: Validate order_id and retrieve order status. [1]
3. Decision: Is refund reason eligible (TIMEOUT or CANCELLED)? [1]
• [Yes] → Activity: Calculate refund amount (100% or 50%). [0.5]
• [Yes] → Activity: Issue refund to original payment method. [0.5]
• [No] → Activity: Log rejection and notify student. [0.5]
4. End: Refund process complete. [0.5]

4.4 [4 marks]

• Persona: A malicious student who shares their QR code screenshot on social media before using
it. [1]
• Hidden Requirement: QR codes must be cryptographically bound to the student’s session/
device and invalidated immediately upon first scan to prevent replay attacks. [1.5]
• Edge Case: Two students present the same QR code simultaneously at different lockers; the system
must reject the second scan and flag the account. [1.5]

Exercise 5: AI-Assisted Engineering & Testing [20 marks]


5.1 [8 marks]

Golden Prompt structure (must include all 4 components):

Role: You are a backend engineer writing robust refund logic.


Context: We process refunds for a cafeteria locker system.
Example 1: If reason is "PICKUP_TIMEOUT" and elapsed_minutes > 30, refund_percent = 100.
Example 2: If reason is "USER_CANCEL" and meal_status is "PREPARING", refund_percent = 50.
Task: Generate the process_refund(order_id, reason) function that calculates refund_percent and updates
↪ the order status.
Negative Constraint: Do NOT log the student's full credit card number or CVV in the refund audit trail;
↪ use only masked card identifiers (last 4 digits).

• Role + Context [2]


• Two worked examples (Few-Shot) [3]
• Task definition [1]

Generated by [Link]
• Negative Constraint [2]

5.2 [8 marks]

(a) Failing unit test establishing 25% boundary [2]:

def test_discount_boundary_25_percent():
# Mathematical boundary: 25% is the maximum allowed discount
assert calculate_final_price(100.00, 25) == 75.00

(b) Three Padlocks [6]:

• Boundary Padlock: assert calculate_final_price(100.00, 25) == 75.00 [2]


• Threshold Padlock: python def test_discount_threshold_26_percent(): with
[Link](ValueError): calculate_final_price(100.00, 26) [2]
• Extreme Padlock: python def test_discount_extreme_100_percent(): with
[Link](ValueError): calculate_final_price(100.00, 100) [2]

(c) Negative Constraint [2]:

“Do NOT silently clamp invalid discount_percent values to 25 or round them down; explicitly
raise ValueError for any input outside the inclusive range 0–25.”

5.3 [4 marks]

Calculations:

• Unit: 30/50 = 60% [1]

• Integration: 15/50 = 30% [1]

• E2E: 5/50 = 10% [1]

Evaluation: Does not match the 70/20/10 pyramid. Unit tests are below 70% and integration tests
exceed 20%.
Risk: The test suite will have slow feedback, higher maintenance cost, and integration tests may mask
missing unit-level coverage for individual modules, allowing defects to persist in isolated logic. [1]

END OF ANSWER KEY

Generated by [Link]
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

Egypt-Japan University of Science and


Technology
Department of Computer Science & Engineering

CSE322 — Software Engineering


Mock Final Examination — Model Answer Key
INSTRUCTOR USE ONLY — DO NOT DISTRIBUTE

Marking Philosophy (from instructor analysis):


• Award marks for rationale, not just the label. “Gold Plating” alone ̸= full marks.
• Penalise vague adjectives (“fast”, “secure”) as unquantified placeholders.
• Pseudocode with no retry limit / no async ⇒ deduct marks for each missing
element.
• Excellent band = correct name + systemic consequence + correct artefact.

Exercise 1: Requirements Engineering & Architecture

1.1 Requirements Extraction


Model Answer
(a) Functional Requirement (2 marks):
“The system shall verify the nurse’s staff ID and dispense the requested medication
upon successful verification.”
• Accept any answer describing a system action (verify ID, dispense medication,
check stock).
• Must use “shall” or “must” construction tied to a behaviour.
(b) Non-Functional Requirement (2 marks):
“The system shall dispense medication within 3 seconds of a valid request at the 95th
percentile (Performance).”
OR: “The system shall permit only authenticated staff to access dispensing functions
(Security).”
• Must name the quality attribute (Performance, Security, Usability, Reliabil-
ity).
• Must include a measurable metric — “fast” or “secure” alone = 0 marks.

Instructor Trap / Common Mistake

Common trap: Students write two FRs (e.g. “verify ID” and “log dispensing”)
and label one as NFR. Logging is a Technical Service / FR, not a quality attribute.

1
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

Deduct 1 mark if metric is missing from NFR.

1.2 Layered Architecture Assignment


Model Answer
1. check stock level(medication id) → Business Logic
Reason: Implements a domain rule — determining whether a resource is available
before dispensing.
2. rotate dispensing motor(direction, duration ms) → Hardware
Reason: Directly controls a physical actuator (motor); raw device interaction.
3. send audit log(nurse id, medication id, timestamp) → Technical Ser-
vices
Reason: Cross-cutting infrastructure utility used across multiple layers; not a
domain rule.
2 marks each: 1 for correct layer + 1 for correct justification.

Instructor Trap / Common Mistake

Classic trap: send audit log placed in Business Logic “because security policy
requires logging.” The instructor’s rubric explicitly classifies logging as Technical
Services — it is infrastructure, not a domain rule. Deduct 1 mark if justification is
absent or wrong.

1.3 Information Hiding in Connectors


Model Answer
# Hides motor direction and timing behind a Boolean
abstraction
FUNCTION d i s p en s e _m e d ic a t io n ( should_dispense : BOOLEAN )

Explanation: The Business Logic layer only needs to express “dispense” or “do
not dispense.” The motor direction (CLOCKWISE) and duration (duration ms) are
hardware implementation details hidden inside the connector’s body.
Mark allocation:
• 2 marks — correct Boolean parameter hiding hardware specifics.
• 2 marks — clear explanation of what is hidden and why.

Instructor Trap / Common Mistake

Trap: Writing dispense medication(direction: STRING, duration: INT)


still exposes hardware details ⇒ 0 marks for hiding. Over-engineering with multiple
status codes when Boolean suffices ⇒ deduct 1 mark.

2
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

Exercise 2: System Resilience & Code Auditing

2.1 Identifying Failures


Model Answer
Three failures (2 marks each):
1. Synchronous Blocking
CALL PAYMENT GATEWAY SYNC blocks the calling thread until the gateway responds,
making the entire application unresponsive for the full timeout duration. At
scale, this exhausts thread-pool resources.
2. Infinite Busy-Wait / Retry Storm
The WHILE True loop with CONTINUE and no delay retries the gateway immedi-
ately and indefinitely. Under load, this generates a storm of concurrent retries
that can prevent the gateway from recovering.
3. Missing Error Handling for Non-Timeout Failures
The ELSE IF SUCCESS branch only handles success. Any other [Link]
(e.g. DECLINED, INVALID CARD) is silently ignored — the function loops forever
on non-transient errors, never returning to the caller.
Accept a third failure as: no retry limit / no bounded termination condition.

Instructor Trap / Common Mistake

Trap: Students who write only “it’s slow” or “it might crash” receive 0 marks.
The instructor requires: precise name + system-level consequence. Also: missing
the missing-error-handling failure is very common — only 1 failure identified ⇒
maximum 2/6.

2.2 Corrected Logic


Model Answer
FUNCTION process_payment ( order_id , amount ) :
MAX_ATTEMPTS = 3
FOR attempt FROM 1 TO MAX_ATTEMPTS :
# 1. Async call - does not block the thread
RESULT = AWAIT C A L L _ P A Y M E N T _ G A T E W A Y _ A S Y N C ( order_id ,
amount )

IF RESULT . status == " SUCCESS ":


log_transaction ( order_id , amount , RESULT .
transaction_id )
RETURN RESULT

ELSE IF RESULT . status == " GATEWAY_TIMEOUT ":


# 2. Exponential back - off : 2ˆ attempt seconds

3
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

WAIT (2 ˆ attempt )
CONTINUE

ELSE :
# 3. Non - transient error - fail immediately
RETURN " PAYMENT_ERROR : " + RESULT . status

# 4. All retries exhausted


RETURN " TIMEOUT_FAILURE "

Mark allocation (1 mark each):


• AWAIT / async call present.
• MAX ATTEMPTS = 3 and FOR loop (bounded).
• WAIT(2ˆattempt) or equivalent exponential back-off.
• Non-transient error handled with an immediate return.
• Graceful TIMEOUT FAILURE return after exhausting retries.

Exercise 3: Traceability, Gherkin & Prompt Engineering

3.1 Traceability Heatmap & Prioritisation


Model Answer
(a) Total PW Calculations (3 marks):
Requirement PW UC-1 UC-2 UC-3
REQ-1: Staff ID Verification 6 X
REQ-2: Stock Level Check 4 X
REQ-3: Dispensing Audit Log 5 X
REQ-4: Low-Stock Alert 3 X
REQ-5: Nurse Account CRUD 2 X
Total PW 11 7 2
UC-1 = REQ-1 (6) + REQ-3 (5) = 11. UC-2 = REQ-2 (4) + REQ-4 (3) = 7.
UC-3 = REQ-5 (2) = 2.
(b) Orphaned Requirements (1 mark): None. Every requirement maps to
exactly one use case. Award 1 mark for correctly identifying there are no orphans.
(c) Implementation Order (2 marks):
UC-1: Dispense Medication should be implemented first.
Reason: It has the highest Total PW (11), meaning it satisfies the most critical
stakeholder requirements (Staff ID Verification + Audit Logging) early in the
development cycle, delivering maximum value first.
(d) Process Violation (1 mark):
Name: Gold Plating (also accept: Scope Creep).
Two harms:
• Wastes development resources on an unrequested feature with no stakeholder

4
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

backing.
• Introduces unverified complexity/bugs into the system with zero test coverage.

Instructor Trap / Common Mistake

Major trap for (a): Students who assign only one requirement per UC compute
UC-1 = 6 instead of 11. This is the deliberate multi-mapping trap — award
maximum 1/3 if all UCs are computed as single-requirement. Trap for (d): “Gold
Plating” alone earns 0.5/1. Must include at least one harm.

3.2 Gherkin Acceptance Criteria


Model Answer
(a) Happy Path Scenario (3 marks):
Feature : Medication Dispensing

Scenario : Nurse successfully requests and receives


medication
Given the nurse is authenticated with a valid staff ID
And the requested medication has sufficient stock
When the nurse submits a dispense request via the tablet
app
Then the system dispenses the medication from the robotic
cabinet
And the dispense event is recorded in the audit log
And the stock level is decremented by one unit

(b) Failure Path Scenario (2 marks):


Scenario : Nurse requests an out - of - stock medication
Given the nurse is authenticated with a valid staff ID
And the requested medication has a stock level of 0
When the nurse submits a dispense request via the tablet
app
Then the system rejects the request with an " Out of Stock
" message
And no dispensing action is performed
And a low - stock alert is sent to the pharmacy manager

(c) QA Refinement (1 mark):


Vague term: “without delay”
Measurable replacement: “The system shall dispense the medication within 3
seconds of a valid authenticated request at the 95th percentile under normal load
conditions (SLA).”

5
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

Instructor Trap / Common Mistake

Trap: Gherkin scenarios covering only the happy path score Satisfactory (3/6
maximum). The instructor’s rubric explicitly requires failure paths. Missing And
clauses for audit logging ⇒ deduct 0.5 marks. For (c), “response should be fast” as
a replacement is still vague ⇒ 0 marks.

Exercise 4: Prompt Engineering & Test-Driven Development

4.1 Golden Prompt — Few-Shot with Negative Constraint


Model Answer
Model Prompt:

Role: You are a senior backend engineer building safety-critical healthcare logic.
Context: I am building a rate-limiting module for a Hospital Medication
Dispensing System. A nurse’s account must be automatically locked after
repeated failed dispense requests.
Example 1: If a nurse exceeds 3 failed login attempts, set account status to
LOCKED and record the event timestamp.
Example 2: If account status is LOCKED, reject all dispense requests for 10
minutes and return a RATE LIMIT EXCEEDED error code.
Task: Generate the function rate limit nurse(nurse id) that locks an ac-
count after 5 consecutive failed dispense requests within a 10-minute sliding
window.
Negative Constraint: Do NOT log, store, or transmit any biometric data
(fingerprints, facial features) in the audit trail or any log output. Only the nurse
ID and event timestamp may be recorded.

Mark allocation (1 mark each):


• Role/context is present and domain-accurate.
• Example 1 is a valid, domain-specific worked example.
• Example 2 is a second valid, domain-specific worked example (must differ from
Example 1).
• Task is clearly and precisely stated for rate limit nurse.
• Negative Constraint is present, specific, and protects sensitive data.

Instructor Trap / Common Mistake

Critical trap: A task description with no worked examples = Zero-Shot prompt,


not Few-Shot. Score maximum 2/5. Providing examples but omitting the Negative
Constraint ⇒ maximum 3/5. Generic negative constraint (“do not make mistakes”)
⇒ 0 marks for that component.

6
EJUST · Spring 2026 CSE322 — Answer Key (Instructor Only)

4.2 TDP & Edge Case Cage


Model Answer
(a) Failing Unit Test — Boundary Constraint (1 mark):
TEST " dosage must not exceed 500 mg boundary ":
# This test FAILS before implementation exists
weight = 50 # kg
dose = 10 # mg / kg = > computed = 500 mg ( boundary )
result = calculate_dosage ( weight , dose )
ASSERT result == 500 # Exact boundary must be accepted

(b) Three Padlocks (1.5 marks — 0.5 each):


# Boundary Padlock : exact limit must PASS
ASSERT calculate_dosage (50 , 10) == 500 # 50 * 10 = 500

# Threshold Padlock : one unit beyond limit must RAISE error


ASSERT RAISES_ERROR calculate_dosage (50 , 10.02) # > 500

# Extreme Padlock : extreme input must RAISE error


ASSERT RAISES_ERROR calculate_dosage (100 , 50) # 5000 mg

(c) Negative Constraint for AI Prompt (0.5 marks):


“Do NOT silently clamp, cap, or round down the computed dosage if it exceeds
500 mg. The function must raise an explicit error and halt — silent clamping is a
patient-safety violation.”

Instructor Trap / Common Mistake

Trap: Writing the test after describing the implementation ⇒ violates TDD
philosophy; deduct 0.5 marks. Boundary padlock testing 499 instead of exactly
500 ⇒ wrong boundary; deduct 0.5 marks. Missing the “raises error” assertion in
Threshold/Extreme padlocks ⇒ deduct 0.5 marks each.

Exercise Max Marks


Exercise 1 — Requirements & Architecture 14
Exercise 2 — System Resilience & Code Auditing 11
Exercise 3 — Traceability, Gherkin & Prompt Engineering 13
Exercise 4 — Prompt Engineering & TDP 8
Total 40
— End of Answer Key —
INSTRUCTOR USE ONLY — DO NOT DISTRIBUTE TO STUDENTS

7
CSE322/CSE323 — Software Engineering
Final Mock Examination — Answer Key
Spring 2026 | Total Marks: 100

Exercise 1: Requirements Engineering & Architecture (20 marks)


1.1 Actor Classification (4 marks)

Actor Type Role Rationale

Nurse Primary Initiates vital sign Uses bedside tablet to view vitals and
monitoring; main respond to alerts
beneficiary of
real-time data
Pager Gateway / Supporting Responds to alerts Receives and acts on threshold breach
Doctor generated by the notifications
system
Hospital Administrator Offstage Has stake in Reviews weekly reports for regulatory
/ Regulator compliance and compliance; affected by data quality
trend reports; never
interacts directly
with the system

Marking: 1 mark per correct actor + type + rationale. Deduct 1 mark if Offstage is missing or
misclassified.

1.2 Requirements Extraction (4 marks)

(a) Functional Requirement (2 marks)

“The system shall display real-time vital signs (heart rate, blood oxygen, blood pressure) on the
bedside tablet when a nurse selects a patient.”

Justification: Describes what the system does. If removed, the system cannot perform its core function.
(1 mark for correct FR, 1 mark for justification)

(b) Non-Functional Requirement (2 marks)

“The system shall maintain 99.9% uptime during network outages by caching vital signs locally on
the bedside tablet for up to 4 hours.”

Justification: Describes how well the system performs (availability/ reliability). The system still
“works” without it, but poorly. (1 mark for correct NFR, 1 mark for justification)

Alternative acceptable NFRs:

• “Heart rate readings shall update on the tablet within 2 seconds of sensor capture.” (Performance)

• “All patient data shall be encrypted using AES-256 at rest and TLS 1.3 in transit.” (Security)

Generated by [Link]
1.3 Layered Architecture Assignment (4 marks)

Function Layer Rationale

(i) Business Logic Encodes domain rule: “what is a


check_vital_threshold(heart_rate, dangerous heart rate?”
threshold)
(ii) send_pager_alert(doctor_id, Technical Services Infrastructure utility; any layer might
message) need alerting
(iii) read_pulse_oximeter_sensor() Hardware Direct physical device interaction
(iv) encrypt_patient_record(data) Technical Services Cross-cutting security infrastructure; not
a business rule

Marking: 1 mark per correct assignment + rationale. Deduct 0.5 if rationale is vague.

1.4 Information Hiding & API Contract (4 marks)

FUNCTION read_spo2(patient_id: STRING) -> spo2_percent: INTEGER

Input: patient_id (STRING) — identifies which patient to read from


Output: spo2_percent (INTEGER, range 70–100) — blood oxygen percentage
Hidden: Raw voltage (0–3.3V), ADC resolution, sensor calibration formula, hardware register addresses.

Marking:

• 1 mark: correct function header hiding voltage

• 1 mark: correct input(s)

• 1 mark: correct output(s)

• 1 mark: clear statement of what is hidden

Trap: Exposing voltage as a parameter (e.g., read_sensor(voltage: FLOAT)) loses 2 marks.

1.5 Persona Discovery (4 marks)

Persona 1 — Frustrated Night-Shift Nurse:

• Action: “I accidentally tapped the wrong patient ID at 3 AM and saw another patient’s vitals for
5 seconds before the screen corrected itself.”

• Hidden Requirement: REQ: Strict Patient Identity Verification — system must confirm
patient ID match before displaying vitals.

Persona 2 — Malicious Insider (Nurse):

• Action: “I tried to access the vitals of a celebrity patient not assigned to my ward.”

• Hidden Requirement: REQ: Role-Based Access Control (RBAC) — nurses can only view
patients in their assigned ward.

Persona 3 — Frustrated Nurse During Network Outage:

• Action: “The Wi-Fi went down and I couldn’t see any vitals for 30 minutes.”

Generated by [Link]
• Hidden Requirement: REQ: Local Data Caching with Sync Queue — tablet must cache
last-known vitals and queue updates for reconnection.

Persona 4 — Attacker (Man-in-the-Middle):

• Action: “I intercepted unencrypted vital sign packets between tablet and server.”

• Hidden Requirement: REQ: End-to-End Encryption for Vital Data Streams — all real-time
data must be encrypted in transit.

Marking: 1 mark per valid persona + hidden requirement pair. Must have at least 4. Deduct 0.5 if
requirement is too vague.

Exercise 2: System Resilience & Logic Auditing (16 marks)


2.1 Identify Failures (6 marks)

Failure Name (Precise SE Vocabulary) System-Level Consequence

1 Synchronous Blocking FETCH_PRESCRIPTION_SYNC blocks the


dispensing thread for the full DB timeout
duration, freezing the pill dispenser UI
and preventing other patients from
receiving medication
2 Infinite Busy-Wait / Retry Storm The WHILE True loop with CONTINUE
retries immediately upon timeout,
generating unlimited requests that
overwhelm the pharmacy DB and
potentially crash both systems
3 Missing Graceful Failure for Persistent If the DB is down for an extended period,
Timeouts the function never returns a failure status
to the caller, causing the nurse station to
wait indefinitely with no actionable error

Marking: 2 marks per failure (1 for precise name, 1 for systemic consequence). Accept “Infinite Retry
Loop” as equivalent to “Infinite Busy-Wait.”

2.2 Corrected Logic (6 marks)

FUNCTION dispense_medication(patient_id, pill_count):


MAX_RETRIES = 3
BACKOFF_MS = 1000

FOR i FROM 1 TO MAX_RETRIES:


PRESCRIPTION = AWAIT FETCH_PRESCRIPTION_ASYNC(patient_id)

IF [Link] == "SUCCESS":
RELEASE_PILLS(pill_count)
RETURN "SUCCESS"
ELSE IF [Link] == "DB_TIMEOUT":

Generated by [Link]
IF i == MAX_RETRIES:
RETURN "FAILURE: Pharmacy DB unreachable after 3 attempts"
WAIT(BACKOFF_MS * (2 ^ (i - 1))) // Exponential back-off
CONTINUE
ELSE IF [Link] == "NOT_FOUND":
RETURN "ERROR: Prescription not found"
ELSE:
RETURN "ERROR: Unexpected status"

RETURN "FAILURE: Max retries exceeded"

Marking:

• 2 marks: Async/non-blocking fetch (AWAIT or equivalent)

• 2 marks: Bounded retry with exponential back-off

• 2 marks: Graceful failure return (not silent crash or infinite loop)

2.3 Resilience Pattern Naming (4 marks)

Pattern Name Problem It Solves

Asynchronous Call (ASYNC/ Prevents thread blocking so the dispenser remains responsive to
AWAIT) other patients during slow DB operations
Exponential Back-Off Prevents Retry Storm by increasing delay between retries,
reducing load on the failing pharmacy DB
Bounded Retry (Circuit Breaker Limits resource consumption and provides a definitive failure
precursor) point so the system can escalate instead of waiting forever

Marking: 1 mark per pattern name + 1 mark per correct problem description. Accept “Bounded Retry”
or “Retry Limit.”

Exercise 3: Design, Specification & Traceability (24 marks)


3.1 Traceability Heatmap (6 marks)

(a) Matrix with X marks (2 marks)

Requirement PW UC-1: Book Appt UC-2: Start Video UC-3: Process Payment

REQ-1: Patient 5 X X
Authentication
REQ-2: 4 X
Calendar
Availability
Check

Generated by [Link]
Table 5 – continued
Requirement PW UC-1: Book Appt UC-2: Start Video UC-3: Process Payment

REQ-3: 5 X
PCI-DSS
Payment
Compliance
REQ-4: HIPAA 3 X X
Session
Encryption
REQ-5: 2 X
Recording
Consent
Capture

(b) Total PW calculations (2 marks)

• UC-1 (Book Appt): 5 (REQ-1) + 4 (REQ-2) = 9


• UC-2 (Start Video): 5 (REQ-1) + 3 (REQ-4) + 2 (REQ-5) = 10
• UC-3 (Process Payment): 5 (REQ-3) + 3 (REQ-4) = 8

(c) Implementation decision (2 marks)

Implement UC-2 (Start Video) first. It has the highest Total PW (10), meaning it delivers the
most critical stakeholder value by addressing authentication, encryption, and consent — all high-risk
compliance requirements.

Marking: Deduct 1 mark per use case if multi-requirement mappings are missed. Deduct 1 mark if
decision lacks stakeholder-value justification.

3.2 QA Refinement Loop (4 marks)

Vague Term Measurable Replacement Standard

“secure” “All video streams shall be encrypted using HIPAA / FIPS-140


AES-256-GCM with ephemeral keys rotated every 15
minutes”
“fast” “Video session establishment time shall be � 3 SLA
seconds at the 95th percentile under 100 concurrent
sessions”

Marking: 0.5 marks per vague term identified. 1 mark per measurable replacement + standard. Deduct
0.5 if standard is mismatched or missing.

3.3 Gherkin Scripting (8 marks)

(a) Happy Path (4 marks)

Feature: Join Video Consultation


Scenario: Patient successfully joins an active consultation

Generated by [Link]
Given the patient has a confirmed appointment for today at 14:00
And the doctor has started the video session
When the patient clicks the "Join Consultation" button
And the patient grants camera and microphone permissions
Then the patient is connected to the video call
And the session timer begins counting
And the chat panel is displayed

Marking: 1 mark for correct Given/When/Then structure. 1 mark for realistic happy path. 1 mark for
at least one And clause. 1 mark for completeness.

(b) Failure Path (4 marks)

Scenario: Patient attempts to join after consultation has ended


Given the patient had a confirmed appointment for today at 14:00
And the doctor has already ended the video session
When the patient clicks the "Join Consultation" button
Then the system displays "This consultation has ended"
And the patient is redirected to the appointment history page
And no video connection is attempted

Marking: 1 mark for correct Given/When/Then structure. 1 mark for realistic failure path. 1 mark for
at least one And clause. 1 mark for completeness.

Trap: Failure path that only says “error message shown” without system behaviour loses 2 marks.

3.4 Process Integrity — Gold Plating (6 marks)

(a) Name (1 mark)

Gold Plating (also acceptable: Scope Creep)

(b) Three systemic harms (3 marks)

1. Wastes engineering resources on unverified, unrequested functionality that could have been
spent on validated requirements.
2. Introduces unverified complexity and potential bugs into a system that was not designed
to host a chatbot, risking stability of core features.
3. Pollutes the traceability matrix by creating a feature with no requirement backing, no Priority
Weight, and no test coverage, making the project un-auditable.

Marking: 1 mark per distinct, systemic harm. “It’s not in the requirements” alone earns 0.5 marks.

(c) Refutation using traceability (2 marks)

“The chatbot has no requirement ID, no Priority Weight, and no mapped use case, so it cannot be
traced, tested, or justified — regardless of perceived user benefit.”

Marking: Must explicitly mention traceability matrix, requirement backing, or Priority Weight. Generic
“it’s not needed” earns 0 marks.

Generated by [Link]
Exercise 4: AI-Assisted Engineering & Prompt Crafting (16 marks)
4.1 Golden Prompt Construction (10 marks)

ROLE: You are a senior backend engineer writing robust Python functions
for a healthcare appointment system.

CONTEXT: The telemedicine platform sends SMS reminders 24 hours before


appointments. Patients reply CONFIRM or CANCEL via SMS. Cancellations
release the slot and notify the doctor. After 3 consecutive no-shows,
the patient account is flagged.

EXAMPLE 1 — Confirm:
Input: { "patient_id": "P123", "response": "CONFIRM", "appointment_id": "A456" }
Output: { "status": "CONFIRMED", "action": "none", "notify_doctor": false }

EXAMPLE 2 — Cancel:
Input: { "patient_id": "P123", "response": "CANCEL", "appointment_id": "A456" }
Output: { "status": "CANCELLED", "action": "release_slot", "notify_doctor": true }

TASK: Generate the `process_reminder_response(patient_id, response, appointment_id)`


function that implements this logic, including the no-show counter increment
and account flagging after 3 consecutive missed appointments.

NEGATIVE CONSTRAINT: Do NOT log the patient's phone number, appointment ID,
or any PHI (Protected Health Information) in plaintext audit logs. Use
anonymised patient tokens only.

EDGE CASE CAGE — BOUNDARY PADLOCK: The function must correctly handle
exactly 3 consecutive no-shows (flag account) vs 2 no-shows (do not flag yet).

Marking:

• 1 mark: Role definition present

• 1 mark: Context/Scenario (2–3 sentences)

• 2 marks: Example 1 (positive case, clear pattern)

• 2 marks: Example 2 (positive case, different branch)

• 1 mark: Specific task statement

• 2 marks: Negative Constraint protecting sensitive data

• 2 marks: Edge Case Cage instruction (Boundary/Threshold/Extreme)

4.2 Prompt Critique (6 marks)

Generated by [Link]
Weakness What Is Missing Why It Matters

Zero-Shot (no Few-Shot worked examples Without examples, the AI cannot


examples) demonstrating input/output patterns learn the expected branching logic
(CONFIRM vs CANCEL vs no-show)
and may hallucinate incorrect
behaviour
No Negative Explicit instruction on what NOT to do Without exclusion rules, the AI may
Constraint (e.g., “Do not log PHI”) generate code that violates HIPAA by
logging sensitive patient data in
plaintext
Vague adjectives Measurable constraints replaced “secure” “Secure” and “efficient” are
and “efficient” with specific metrics un-testable; the AI has no boundary
conditions to optimise against,
producing unreliable output

Marking: 2 marks per weakness (1 for identification, 1 for explanation). Accept any three valid weak-
nesses.

Exercise 5: Test-Driven Development & Validation (24 marks)


5.1 TDP — The Failing Test First (4 marks)

def test_calculate_copay_tier_c_boundary():
# Tier C = 50% patient responsibility
result = calculate_copay(insurance_tier="C", base_cost=200)
assert result == 100 # 50% of 200 = 100

Marking:

• 2 marks: Test is written BEFORE implementation (TDP philosophy stated or implied)

• 2 marks: Establishes a mathematical boundary (exact percentage calculation)

Alternative acceptable boundary tests:

• Tier A: assert calculate_copay("A", 500) == 0

• Tier D: assert calculate_copay("D", 150) == 150

5.2 Edge Case Cage — All Three Padlocks (12 marks)

(a) Boundary Padlock (4 marks)

def test_boundary_tier_c_exactly_50_percent():
# Boundary: Tier C pays exactly 50%
result = calculate_copay(insurance_tier="C", base_cost=100)
assert result == 50 # Exactly at the 50% boundary

Marking: 2 marks for testing exact boundary. 2 marks for clear assertion.

(b) Threshold Padlock (4 marks)

Generated by [Link]
def test_threshold_invalid_tier_e():
# Threshold: One step beyond valid tier set (A, B, C, D)
try:
calculate_copay(insurance_tier="E", base_cost=100)
assert False, "Should have raised ValueError for invalid tier"
except ValueError:
pass # Expected

Marking: 2 marks for testing one beyond valid set. 2 marks for correct exception handling.

(c) Extreme Padlock (4 marks)

def test_extreme_negative_base_cost():
# Extreme: Negative cost is physically impossible
try:
calculate_copay(insurance_tier="B", base_cost=-9999)
assert False, "Should have raised ValueError for negative cost"
except ValueError:
pass # Expected

Marking: 2 marks for extreme/invalid input. 2 marks for correct exception handling.

Alternative acceptable extreme: base_cost=0, tier=None, tier=""

5.3 Negative Constraint for AI Prompt (4 marks)

“Do NOT silently clamp, round, or default invalid insurance_tier values. Any tier outside {A, B,
C, D} or any negative base_cost MUST raise a ValueError immediately. Do NOT return 0, null, or
any default value for invalid inputs.”

Marking:

• 2 marks: Explicitly prohibits silent handling (clamping/rounding/defaulting)

• 2 marks: Mandates ValueError for invalid inputs

5.4 Verification vs Validation (4 marks)

(a) Verification (2 marks)

Verification asks: “Did we build the system correctly?” — does the code match the specification?
Evidence: All unit tests pass, including Boundary, Threshold, and Extreme padlocks. The cal-
culate_copay function correctly implements the tier percentages and raises ValueError for invalid
inputs, matching the specification exactly.

Marking: 1 mark for correct definition. 1 mark for concrete evidence.

(b) Validation (2 marks)

Validation asks: “Did we build the correct system?” — does it solve the real patient billing
problem?
Additional evidence needed: - User acceptance testing with hospital billing staff confirming the
copay calculations match real insurance contracts

Generated by [Link]
• User acceptance testing with hospital billing staff confirming the copay calculations match real
insurance contracts
• End-to-end test: a patient books an appointment, insurance is verified, and the billed copay
matches their Explanation of Benefits (EOB)
• Playwright E2E test showing the patient portal displays the correct copay before confirming
the appointment

Marking: 1 mark for correct definition. 1 mark for at least one concrete validation activity beyond unit
tests.

Summary Marking Scheme

Exercise Topic Marks

1.1 Actor Classification 4


1.2 FR/NFR Extraction 4
1.3 Layer Assignment 4
1.4 Information Hiding 4
1.5 Persona Discovery 4
2.1 Failure Identification 6
2.2 Corrected Logic 6
2.3 Resilience Patterns 4
3.1 Traceability Heatmap 6
3.2 QA Refinement 4
3.3 Gherkin Scripting 8
3.4 Gold Plating 6
4.1 Golden Prompt 10
4.2 Prompt Critique 6
5.1 Failing Test 4
5.2 Three Padlocks 12
5.3 Negative Constraint 4
5.4 Verification/Validation 4
TOTAL 100

Grading Philosophy Reminders:

• Excellent (90–100): All artefacts produced, precise vocabulary, systemic reasoning, no vague
adjectives, all traps avoided.

• Good (75–89): Most artefacts produced, minor vocabulary slips, one trap triggered.

• Satisfactory (60–74): Some artefacts missing, conceptual understanding present but imprecise,
2+ traps triggered.

• Needs Improvement (<60): Major gaps in artefacts, confused FR/NFR, missed code failures,
Zero-Shot prompts, happy-path-only Gherkin.

END OF ANSWER KEY

Generated by [Link]
Department of Computer Science and Software Engineering
Egypt-Japan University of Science and Technology (E-JUST)

Course Code: CSE322 / CSE323 Semester: Spring 2026


Course Title: Software Engineering Principles & Practices Duration: Solutions Memo
Document Type: Official Mock Exam II Answer Key Total Marks: 30 Marks

Question 1: Behavioral Design Patterns & State Encapsulation (6


Marks)
(a) State-Transition Table (2 Marks)
Current State Triggering Event Destination State
Idle select start Scanning
Scanning scan item Scanning (Self-transition)
Scanning hardware error Maintenance
Scanning proceed to checkout PaymentPending
PaymentPending pay success Idle
PaymentPending hardware error Maintenance

(b) State Pattern Pseudocode Implementation (2.5 Marks)

// Context Interface Base


INTERFACE KioskState :
FUNCTION handle_scan ( context , item_id )
FUNCTION handle_payment ( context )

CLASS ScanningState IMPLEMENTS KioskState :


FUNCTION handle_scan ( context , item_id ) :
context . add_to_cart ( item_id )
// Remains in scanning
FUNCTION handle_payment ( context ) :
context . transition_to ( NEW P ay m e nt P e nd i n gS t a te () )

CLASS P a ym e n t Pe n d in g S ta t e IMPLEMENTS KioskState :


FUNCTION handle_scan ( context , item_id ) :
PRINT " Error : Payment in progress . Cannot scan . "
FUNCTION handle_payment ( context ) :
IF context . v e r i f y _ b a n k _ t r a n s a c t i o n () == TRUE :
context . clear_cart ()
context . transition_to ( NEW IdleState () )

(c) Dependency Trap Analysis (1.5 Marks)


• The Dependency Trap: Hardcoding direct instantiation inside state subclasses introduces
structural **Tight Coupling**, breaking the Open-Closed Principle since introducing a new state
requires changing existing state class files.

• The Architectural Correction: Abstract the transitions out by using a localized state factory
lookup matrix or passing handling controls back up to the master context controller class wrapper.

1
Question 2: White-Box Testing & Cyclomatic Complexity Analysis (6
Marks)
(a) Control Flow Graph Mapping (2 Marks)
• Node 1: Entry point and parameter initialization block.

• Node 2: Conditional checking evaluation statement: zone id == "ZONE A".

• Node 3: Nested branch verification check: weight kg > 500.

• Node 4: Surcharge math execution block for heavy Zone A items.

• Node 5: Surcharge math execution block for standard Zone A items.

• Node 6: Outer branch evaluation statement: zone id == "ZONE B".

• Node 7: Surcharge math execution block for Zone B items.

• Node 8: Dead-code evaluation block: zone id == "ZONE A" AND weight kg <= 100.

• Node 9: Sub-branch math execution block for impossible condition.

• Node 10: Default fallback catch-all surcharge configuration block.

• Node 11: Unified exit statement returning calculation metric.

(b) Cyclomatic Complexity Formula Computation (2 Marks)


• Using structural counting mappings: Edges (E) = 13, Vertices/Nodes (V ) = 11, Connected
Components (P ) = 1.

• Formula calculation: M = 13 − 11 + 2(1) = 4. The Cyclomatic Complexity of this codebase logic


is exactly **4**.

(c) Traps Statement Coverage Gaps (2 Marks)


• Structural Defect Trap: Node 8 contains a **Dead Code Contradiction**. Because the code
path can only be reached if zone id != "ZONE A" from the outer check, the nested statement
zone id == "ZONE A" evaluates to false every single time.

• Statement Coverage Failure: Standard statement coverage purely checks whether lines exe-
cute. If code execution routes around the dead branch block entirely, statement metric tracking
can report 100% validation coverage while hiding dead logic loops completely.

Question 3: DevSecOps CI/CD Pipelines & Gate Vulnerabilities (6


Marks)
(a) Process Integrity Breakdown (1.5 Marks)
• Architectural Term: **Gold-Shielding Bypassing** (or Security Technical Debt accumulation
/ Logging Suppressions).

• Engineering Consequence: It removes automated regression oversight controls from produc-


tion, allowing active threat exploits to breach production servers under the false pretense of
deployment speed optimizations.

2
(b) Quantified QA Pipeline Policy Gate Specification (2.5 Marks)

Test Metric Category Operational Acceptance Target Binary Failure Condition Rule
Security Scan Compliance 0 Open Critical CVE Flaws (OWASP) REJECT if any Severity Level ≥ 8.0 exists.
Code Coverage Bounds Minimum 85% Branch Test Coverage REJECT if deployment suite falls below 85%.
Performance Bounds API Endpoint Latency ≤ 200 ms REJECT if 95th-percentile exceeds 200 ms under tes

(c) Testing Taxonomy Contrast (2 Marks)


• **SAST (Static Analysis):** Audits and scans text-based source files directly for structural flaws,
bad code styles, and unsafe dependencies *without running the application*.

• **DAST (Dynamic Analysis):** Evaluates a running system instance externally by injecting mock
malicious runtime payloads to expose operational attack surfaces.

• **Scenario Match:** The vulnerability was identified using a **SAST** architecture component
during compilation.

3
Question 4: Software Configuration Management & Branching Topolo-
gies (6 Marks)
(a) Branching Topologies Comparison (2 Marks)
• **GitFlow:** Features multiple long-lived development streams (features, releases, develop) which
accumulate large code diffs over time, increasing the risk of massive merge conflicts.

• **Trunk-Based Development:** Mandates that all developers merge short-lived feature updates
back into a single central branch (the trunk) multiple times a day. This isolates changes to small
increments and prevents code streams from diverging.

(b) Force Merging Vulnerability Analysis (2 Marks)


• Technical Term: **Force Pushing Overwrites** (git push --force / Blind Resolution).

• Engineering Consequence: This practice overwrites verified peer-reviewed updates made by


other developers, silently deletes operational code loops, and risks introducing breaking defects
directly into the production codebase.

(c) Feature Toggle Mechanisms (2 Marks)


• Mechanism Definition: A **Feature Toggle** wraps new, uncompleted logic inside a condi-
tional switch statement (e.g., if ([Link] enabled("NEW ENGINE"))).

• Continuous Deployment Utility: This allows code to be merged safely into the main line and
deployed to production inactive. The logic remains dormant until the configuration flag is flipped
to active in production, separating code deployment from feature release.

Question 5: Agile Estimation Metrics & Sprint Capacity Auditing (6


Marks)
(a) Historical Average Velocity Calculation (1.5 Marks)
P
Story Points Fully Completed Successfully
• Velocity = Total Observed Count of Sprints

• Velocity Calculation = 30+32+28


3 = 90
3 = 30 Story Points per Sprint.

(b) Sprint 03 Performance Matrix Audit (1.5 Marks)


• Metric Diagnosis: In Sprint 03, the team committed to 40 points, which was significantly over
their demonstrated capacity. This over-commitment resulted in a **Sprint Overload Failure**,
causing completed story points to drop to 28 while introducing 5 new bugs due to rushed delivery.

(c) Scrum Master Metric-Driven Rejection Response Statement (3 Marks)


Professional Response Framework:

”We cannot accept or integrate the unestimated maps engine modification mid-sprint. Our
historical engineering data establishes a firm velocity boundary of exactly 30 story points
per sprint. Pushing unplanned workload injections into an active sprint violates our quality
rules, introduces code defects, and causes sprint overload failures, as evidenced in Sprint 03.
This emergency feature must instead be formally sized, added to the product backlog, and
prioritized for inclusion in Sprint 05 planning based on our sustainable capacity thresholds.”

4
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

Egypt-Japan University of Science and Technology


CSE322/CSE323 – Software Engineering
Mock Final Examination II – Answer Key
Total Marks: 100

1 Requirements Engineering & Architecture [20 marks]

1.1 1.1 [5 marks]


• FR: The system shall recognize the driver’s license plate via OCR and automatically raise the
entry barrier if the plate matches an active reservation. [2.5]
• NFR: The system shall process entry requests with an average latency ≤ 2 seconds at the
95th percentile during peak occupancy (Performance). [2.5]
Grading note: NFR must be a quality attribute (performance, security, reliability, usability). “Use
camera” or “process payment” are FR, not NFR.

1.2 1.2 [6 marks]


1. detect_license_plate(...) → Hardware [1]. Rationale: Direct physical sensor interac-
tion (camera frame capture and OCR hardware). [1]
2. compute_dynamic_price(...) → Business Logic [1]. Rationale: Encodes domain rules
about demand-based pricing; core business rule. [1]
3. write_audit_log(...) → Technical Services [1]. Rationale: Cross-cutting infrastructure
utility used across all layers; not a business rule. [1]
Trap: Students who place audit logging in Business Logic because “it is related to security policy”
score partial only. Logging is always a Technical Service.

1.3 1.3 [4 marks]

FUNCTION g e t _ g a r a g e _ o c c up a n c y () RETURNS OccupancyReport

Rationale: Hides camera-specific details (frame resolution, OCR confidence thresholds, neural-
network model identifiers, raw pixel data). Business Logic only receives a structured occupancy
report; implementation details remain concealed. [4]
Acceptable alternative: FUNCTION query_occupancy(zone_id: STRING) RETURNS INTEGER
if rationale clearly states hidden camera/OCR internals.

1.4 1.4 [5 marks]

FUNCTION reserve_spot ( driver_id : STRING , preferred_zone : STRING )


PRE : driver_id is non - empty and registered in the system .
PRE : preferred_zone exists in the garage layout .
POST : Returns reservation_id ( UUID ) if a spot is available .
POST : Raises N o S p o t A v a i l a b l e Er r o r if preferred_zone is full .
POST : Raises In val id Dr ive rE rr or if driver_id is not registered .

- Hides DB schema [2]. Independent team only needs the signature and pre/post-conditions. [2]
- Pre/post-conditions present and non-trivial [1].

1
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

2 System Resilience & Logic Auditing [20 marks]

2.1 2.1 [8 marks]


1. Synchronous Blocking [2]. The CALL_OCR_SERVICE_SYNC blocks the calling thread until the
OCR service responds, rendering the entry lane unresponsive and creating a physical traffic
jam at the gate. [2]

2. Infinite Busy-Wait / Retry Storm [2]. The WHILE True loop retries immediately (CONTINUE)
on “PLATE_NOT_FOUND” without exponential backoff or a bounded attempt limit, over-
whelming the OCR service and potentially burning out the barrier motor through repeated
activation attempts. [2]

Grading: “It’s slow” or “it might crash” earns 0. Must name the precise anti-pattern and explain
thread/system consequences.

2.2 2.2 [12 marks]

FUNCTION open_gate ( plate_number ) :


MAX_ATTEMPTS = 3
FOR i FROM 1 TO MAX_ATTEMPTS :
result = AWAIT C A L L _ O C R _ S E R V I C E _ A S Y N C ( plate_number )
IF result . status == " SUCCESS ":
A C T I V A T E _ B A R R I E R _ M O T O R ()
RETURN result
ELSE IF result . status == " PLATE_NOT_FOUND ":
WAIT (2^ i * 1000) // Exponential backoff : 2s , 4s , 8 s
CONTINUE
ELSE :
RETURN " ACCESS_DENIED "
// Graceful physical fallback after exhaustion
A C T I V A T E _ M A N U A L _ O V E R R I D E _ M O D E ()
DISPLAY " Please proceed to manual booth "
RETURN " O C R _ U N A V A I L A B L E _ F A L L B A C K "

- Use of ASYNC / AWAIT [3] - Bounded retry (MAX_ATTEMPTS) [3] - Exponential backoff
(not fixed delay) [3] - Graceful physical fallback (manual override mode) [3]

3 Traceability & Process Integrity [20 marks]

3.1 3.1 [10 marks]

Requirement PW UC-1 UC-2 UC-3


REQ-1 5 X X
REQ-2 4 X X
REQ-3 3 X X
REQ-4 2 X X
Total PW 11 8 9

- UC-1 (Reserve): 5 + 4 + 2 = 11 [2] - UC-2 (Enter): 5 + 3 = 8 [2] - UC-3 (Pay): 4 + 3 +


2 = 9 [2]
Decision: Implement UC-1 (Reserve Spot) first. [2]
Justification: It delivers the highest stakeholder value (Total PW = 11) by combining license-
plate recognition, dynamic pricing, and audit logging — the three most critical requirements for
revenue and security. [2]

2
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

Trap: Students who compute single-requirement PW or omit the stakeholder-value justification


score partial.

3.2 3.2 [5 marks]


• Name: Scope Creep (or Gold Plating) [2].
• Systemic harms: (any two of the following, 1.5 marks each, max 3)
– Wastes engineering resources on unrequested features.
– Introduces unverified complexity and potential security vulnerabilities (social media API
integration).
– Pollutes the traceability matrix (no requirement backing).
– Creates untested functionality with no acceptance criteria.
– Diverts effort from validated use cases with higher PW.

3.3 3.3 [5 marks]


• Verification: “Did we build the system correctly?” [1]
Example: The OCR service correctly recognizes 98% of license plates under standard lighting
conditions (ISO/IEC 27001 compliance test). [1.5]
• Validation: “Did we build the correct system?” [1]
Example: 85% of surveyed drivers report that automated entry reduces their average parking
time by at least 3 minutes compared to ticket-based systems. [1.5]

4 Design & Specification [20 marks]

4.1 4.1 [8 marks]


(a) Happy path [3]:
Scenario : Driver enters successfully with recognized plate
Given the driver has an active reservation for zone " A "
And the license plate " ABC -123" is registered to the reservation
When the driver approaches the entry gate
Then the OCR camera recognizes the plate
And the barrier raises within 2 seconds
And the system logs the entry timestamp

(b) Failure path [3]:


Scenario : Plate unrecognized after maximum OCR attempts
Given the driver approaches the entry gate
When the OCR service fails to recognize the plate after 3 attempts
Then the barrier remains lowered
And the system displays " Please proceed to manual booth "
And the failed attempt is logged with the captured frame hash

(c) Edge case [2]:


Scenario : Driver enters during network outage
Given the driver has a valid reservation
And the central server is unreachable
When the driver approaches the entry gate
Then the local edge controller validates the plate from cached data
And the barrier raises if the plate is in the local whitelist
And the system queues the entry event for later synchronization

3
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

Grading: Happy path alone = Satisfactory. All three scenarios with correct Given/When/Then
syntax = Excellent.

4.2 4.2 [4 marks]


• “quick entry” → “Barrier raise time ≤ 2 seconds from plate detection to full open at
the 95th percentile under normal load.” (SLA) [2]

• “safe payment” → “All payment card data is encrypted using AES-256 at rest and
TLS 1.3 in transit; CVV is never stored.” (PCI-DSS) [2]

Any quantifiable, testable metric with a cited standard accepted. Vague replacements earn 0.

4.3 4.3 [4 marks]


(i) Actor: Driver [0.5]

(ii) System operations (happy path):

• Driver sends reserve_spot(driver_id, preferred_zone) [0.5]


• System returns reservation_id + spot_number [0.5]

(iii) Failure path:

• Driver sends reserve_spot(driver_id, preferred_zone) [0.5]


• System returns NoSpotAvailableError [0.5]

(iv) Return values: UUID on success, exception on failure [1]

Notation accuracy is explicitly graded. Missing return values or incorrect operation names penal-
ized.

4.4 4.4 [4 marks]


• Persona: Fraudster (stolen plate cloner) [1]

• Hidden Requirement: The system must validate that the recognized plate matches the
reservation’s registered vehicle type (e.g., sedan vs. truck) to prevent plate-cloning fraud.
[1.5]

• Edge Case: A fraudster photographs a valid driver’s plate and displays it on a tablet at the
gate; the system must detect the lack of a physical vehicle via ultrasonic or LIDAR presence
sensors. [1.5]

5 AI-Assisted Engineering & Testing [20 marks]

5.1 5.1 [8 marks]


Golden Prompt structure (must include all 4 components):
Role : You are a pricing engineer for a smart parking system .
Context : We compute dynamic parking prices based on real - time occupancy ,
parking duration , and vehicle type .
Example 1: If occupancy = 0.90 , duration = 2 hours , vehicle_type = "
sedan " ,
base_rate = 10 , multiplier = 1.5 , final_price = 15.00.

4
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

Example 2: If occupancy = 0.30 , duration = 1 hour , vehicle_type = " truck


",
base_rate = 15 , multiplier = 1.0 , final_price = 15.00.
Task : Generate the c o m p u t e _ d y n a m i c _ p r i c e ( occupancy , duration ,
vehicle_type )
function that returns the final price as a float .
Negative Constraint : Do NOT expose raw revenue totals , hourly breakdowns
,
or internal multiplier tables in any log output or exception
message .

- Role + Context [2] - Two worked examples (Few-Shot) [3] - Task definition [1] - Negative
Constraint [2]

5.2 5.2 [8 marks]


(a) Failing unit test establishing 15-minute boundary [2]:
def t e s t _ e n t r y _ w i n d o w _ b o u n d a r y _ 1 5 _ m i n u t e s () :
# Mathematical boundary : 15 minutes is the maximum allowed offset
assert v a l i d a t e _ e n t r y _ w i n d o w (
reservation_time = datetime (2026 ,6 ,9 ,10 ,0) ,
current_time = datetime (2026 ,6 ,9 ,10 ,15)
) == 15.0

(b) Three Padlocks [6]:

• Boundary Padlock:
def t e s t _ b o u n d a r y _ e x a c t l y _ 1 5 _ m i n u t e s () :
assert v a l i d a t e _ e n t r y _ w i n d o w (
datetime (2026 ,6 ,9 ,10 ,0) , datetime (2026 ,6 ,9 ,10 ,15)
) == 15.0

[2]

• Threshold Padlock:
def t e s t _ t h r e s h o l d _ 1 6 _ m i n u t e s () :
with pytest . raises ( ValueError ) :
validate_entry_window (
datetime (2026 ,6 ,9 ,10 ,0) , datetime (2026 ,6 ,9 ,10 ,16)
)

[2]

• Extreme Padlock:
def t e s t _ e x t r e m e _ 2 4 _ h o u r s () :
with pytest . raises ( ValueError ) :
validate_entry_window (
datetime (2026 ,6 ,9 ,10 ,0) , datetime (2026 ,6 ,10 ,10 ,0)
)

[2]

(c) Negative Constraint [2]:

“Do NOT return the absolute time difference for invalid entries; explicitly raise Val-
ueError for any current_time outside the reservation window ± 15 minutes.”

5
CSE322/CSE323 – Mock Final Examination II Answer Key – Spring 2026

5.3 5.3 [4 marks]


Calculations:

• Unit: 20/50 = 40% [1]

• Integration: 25/50 = 50% [1]

• E2E: 5/50 = 10% [1]

Evaluation: Does not match the 70/20/10 pyramid. Unit tests are critically below 70%
and integration tests severely exceed 20%.
Risk: The test suite will have slow CI/CD feedback, fragile cross-module tests that break on
internal refactoring, and insufficient isolation of individual component defects, allowing bugs to
propagate undetected into integration. [1]

END OF ANSWER KEY

6
Answer Key — Mock Final Exam

Q1
a) FR: System shall allow students to submit exams online.
b) NFR: Response time ≤ 2 seconds (Performance).
c) Primary: Student Supporting: Authentication Service Offstage: University Ad-
ministration
d) Replace with: Response time ≤ 2 seconds at 95th percentile

Q2
a) validate exam submission → Business Logic log exam activity → Technical Services
trigger camera → Hardware
b) FUNCTION set proctoring(enabled: BOOLEAN)
c) Logging is cross-cutting infrastructure used by all layers → Technical Services

Q3
a) - Synchronous Blocking - Infinite Busy-Wait (Retry Storm)
b)

FUNCTION submit_exam(data):
MAX = 3
FOR i FROM 1 TO MAX:
RESULT = AWAIT SEND_TO_SERVER_ASYNC(data)
IF [Link] == "SUCCESS":
RETURN RESULT
ELSE IF [Link] == "BUSY":
WAIT(5)
CONTINUE
ELSE:
RETURN "ERROR"
RETURN "TIMEOUT_FAILURE"

Q4
a) UC-A = 5 + 3 = 8 UC-B = 4 = 4 UC-C = 4 + 2 = 6
b) None
c) UC-A → highest PW → delivers maximum stakeholder value first

Q5
a) Given student is logged in When student submits exam Then exam is stored success-
fully

1
b) Given student is logged in When submission fails due to network Then system
retries and shows error after limit
c) Submission time ≤ 2 seconds

Q6
a) ASSERT check attempts(3) == LOCKED
b) Boundary: attempts = 3 → LOCKED Threshold: attempts = 4 → LOCKED
Extreme: attempts = 100 → LOCKED
c) Do NOT silently ignore invalid attempt counts

Q7
Role: You are a backend engineer
Context: Exam submission system with retry logic
Example 1: If attempts ¡ 3 → retry with delay
Example 2: If attempts 3 → return failure
Task: Generate submission retry logic
Negative Constraint: Do NOT block thread with synchronous calls

You might also like