you are a professor at SFU teaching the courses CMPT276. Give me practice questions for the upcoming midterm. Show the answer below and explain your process
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Here's a set of practice questions for the CMPT 276 (Software Construction) midterm, modeled after what you might expect in Professor Joe Hummel’s course at Simon Fraser University (SFU). These questions cover key topics such as:
Scenario: You're designing a game with different types of characters like Warrior, Mage, and Archer. Each character can attack and use an ability. All characters must implement a common interface.
Part A:
Which SOLID principle ensures that adding new character types (e.g., Necromancer) won’t require modifying existing code?
Part B:
Which design pattern would be appropriate to encapsulate the creation of these varied character types?
Answer:
Part A: Open/Closed Principle (OCP) — Classes should be open for extension but closed for modification.
Part B: Factory Method or Abstract Factory pattern.
Explanation:
The Open/Closed Principle allows extensibility without changing existing logic. Using a Factory Method, you can delegate instantiation logic to subclasses, or use an Abstract Factory if character creation is more complex (e.g., grouped by factions).
Question 2: UML Class Diagram – Relationships
Given the following description, draw the appropriate relationships in UML class diagram form (textual representation):
A Library contains many Books. A Book can belong to only one Library. Both Library and Book are concrete classes. A Person can borrow multiple Books, and each Book can be borrowed by multiple People over time (many-to-many, temporal).
Answer (Textual UML Snippet):
plaintext
Library "1" <---> "0..*" Book : contains
Book "*" --- "0..*" Person : borrowed_by
Person "1" --- "0..*" Book : borrows
(Note: In proper UML, you'd indicate multiplicities and relationship types.)
Explanation:
Association between Library and Book (composition or aggregation depending on lifetime dependency).
Many-to-many association between Book and Person with labels indicating the role (borrowed_by, borrows).
If lifetime dependency is strong (Book ceases to exist outside Library), then it's Composition. Otherwise, Aggregation.
Question 3: Design Patterns
Scenario: You are building a text editor. You want to support functionalities like bold, italic, underline, etc., and allow combinations like bold+italic. You also want to add new formatting options easily.
Part A:
Which design pattern best fits this scenario?
Part B:
Explain how the pattern works in this context.
Answer:
Part A: Decorator Pattern
Part B: The decorator pattern allows behavior to be added to individual objects dynamically. You define a base TextComponent interface, a concrete PlainText class, and decorators like BoldDecorator, ItalicDecorator, etc., which wrap a TextComponent and add their own formatting logic.
Explanation:
This promotes open/closed principle — you can add new decorators without modifying existing formatting code. Each decorator adds functionality and forwards other calls to the wrapped object.
Question 4: Unit Testing / Mocking
You’re testing a class EmailSender that depends on SMTPService.
java
public class EmailSender {
private SMTPService service;
public EmailSender(SMTPService service) {
this.service = service;
}
public void sendWelcomeEmail(User user) {
String msg = "Welcome " + user.getName();
service.send(user.getEmail(), "Welcome!", msg);
}
}
Question:
Write pseudocode / high-level structure for a unit test of sendWelcomeEmail() using Mockito.
Answer:
java
@Test
public void testSendWelcomeEmail() {
// Arrange
SMTPService mockService = Mockito.mock(SMTPService.class);
User testUser = new User("Alice", "alice@example.com");
EmailSender sender = new EmailSender(mockService);
// Act
sender.sendWelcomeEmail(testUser);
// Assert
Mockito.verify(mockService).send("alice@example.com", "Welcome!", "Welcome Alice");
}
Explanation:
We isolate EmailSender by mocking its dependency SMTPService. Then we verify that the correct method was called with expected parameters. This is a classic example of dependency injection + mocking for testability.
Question 5: Coupling & Cohesion
You're reviewing two designs for a payment system.
Design A: PaymentProcessor directly instantiates and calls methods from CreditCardProcessor, PayPalProcessor, and CryptoProcessor.
Design B: PaymentProcessor delegates to a PaymentStrategy interface implemented by the three processor classes.
Question:
Which design exhibits looser coupling and higher cohesion? Why?
Answer:
Design B has looser coupling and higher cohesion.
Explanation:
Loose Coupling: PaymentProcessor doesn't need to know about specific implementations — it depends on an abstraction (PaymentStrategy).
High Cohesion: Each strategy class has a single responsibility for handling one kind of payment.
This adheres to the Dependency Inversion Principle.
Question 6: Inheritance vs Composition
You're designing classes for vehicles.
Option 1 (Inheritance):
java
class Vehicle {}
class Car extends Vehicle {}
class Motorcycle extends Vehicle {}
Option 2 (Composition):
java
interface Vehicle {}
class Car implements Vehicle {}
class Motorcycle implements Vehicle {}
// OR
class Vehicle {
Engine engine;
}
Question:
When would you prefer Option 2 over Option 1? What are the trade-offs?
Answer:
Prefer Option 2 (Composition) when:
Behavior varies independently (e.g., a car and a motorcycle share little logic).
You want to avoid deep inheritance hierarchies.
You need more flexibility (e.g., a vehicle that is both drivable and flyable — composition allows multiple interfaces).
Trade-offs:
Inheritance: Simpler but tightly couples base and derived classes.
Composition: More flexible, promotes reuse, easier to maintain.
🧠 Bonus Question (Short Answer)
What is the Liskov Substitution Principle? Provide a violation example in Java.
Answer:
LSP states that objects of a superclass should be replaceable with objects of its subclasses without breaking the application.
Violation Example:
java
class Bird {
void fly() { /*...*/ }
}
class Sparrow extends Bird {}
class Ostrich extends Bird {
void fly() { throw new UnsupportedOperationException(); } // violates LSP
}
Using Bird b = new Ostrich(); b.fly(); breaks expected behavior.
📘 Summary Table
Topic
Key Concept/Pattern
OOP Principles
SOLID
Creating Objects
Factory / Abstract Factory
Dynamic Functionality
Decorator
Multiple Behaviors
Strategy
Testability
Dependency Injection + Mocks
Class Relationships
Aggregation vs Composition
Interface Segregation
ISP (not asked, but related)
Would you like a PDF version or want to simulate a timed test environment? I can help format these into flashcards or generate similar questions focused on a specific topic (e.g., just design patterns).