UNC COMP 301 - F26/Lec 22 - SOLID Design Principles (Cont.); Testing revisited
Overview
Muhammad Sayeed Ghani completes the SOLID design principles discussion with examples in Java, showing how the Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion principles shape extensible, substitutable, focused, and testable code. He connects dependency injection to JUnit 5 test doubles and inversion of control, including examples from MVC, JavaFX, and a small framework, then defers a broader testing and debugging review to the final lecture.
Key takeaways
- A Discount interface makes a ticket pricer open to new categories such as veterans or early-bird discounts without editing its tested pricing logic.
- A Square is not necessarily a safe Rectangle subtype when inherited width and height setters promise independent changes; resizing a 5-by-4 rectangle should yield area 20, but the square implementation can yield 16.
- Splitting print, scan, and fax into separate Java interfaces prevents unsupported operations from compiling against a basic printer and avoids forcing unrelated classes to change.
- Constructor-injected Notifier abstractions let a checkout service switch between email and SMS without changing tax logic, and let tests substitute a fake notifier.
- A JUnit 5 test double can record notification recipients and messages, allowing a checkout test to verify a 100 base price plus 7 percent tax produces 107 without sending a real message.
- Inversion of control shifts call timing to an external framework: JavaFX calls start after launch, and the MiniApp example runs registered command handlers after application setup.
Chapters
- Muhammad Sayeed Ghani says the semester's final lecture will be Tuesday, before Thanksgiving.
- The last assignment is due shortly after Thanksgiving and will be primarily manually graded.
- The lecture continues the SOLID discussion, beginning with the Open-Closed Principle after reviewing the Single Responsibility Principle.
- The original Java ticket pricer takes a category string and base price, using categories such as student, senior, and regular.
- Adding a veterans discount requires modifying the pricer's conditional logic, risking bugs in previously tested code.
- A Discount interface lets separate implementations, such as StudentDiscount and NoDiscount, calculate the price.
- A new discount can be added by passing a new Discount implementation, such as a veterans or early-bird discount, without changing the ticket pricer.
- Because Discount has one method, Java lambda expressions can represent discount rules without separate classes.
- The discount example resembles Decorator but does not wrap and augment an existing object; it selects a replacement strategy.
- Observer and Iterator also illustrate OCP: adding an observer or using an iterator does not require modifying the existing subject or collection code.
- The Liskov Substitution Principle requires a subtype to work wherever its supertype is expected.
- A Rectangle permits independent width and height setters, while a Square override must keep both dimensions equal.
- A resize method sets a Rectangle to width 5 and height 4 and expects area 20, but a Square can end with dimensions 4 by 4 and area 16.
- Java's virtual method dispatch invokes Square's overridden setters even when client code holds a Rectangle reference.
- An instanceof Square check can special-case resizing, but every new subtype then forces changes to client code.
- That subtype-dependent branch violates OCP and spreads repeated type checks across clients.
- A better design can make Rectangle and Square separate Shape implementations that share an area operation.
- Separate APIs, such as setWidth and setHeight for Rectangle versus setSide for Square, avoid promising incompatible behavior through inheritance.
- A single OfficeDevice interface requiring print, scan, and fax forces a basic printer to implement unsupported operations.
- Throwing UnsupportedOperationException for scan or fax defers misuse until runtime instead of preventing it at compile time.
- Changing a fax method's parameters would also force changes to devices that do not support fax.
- Separate Printer, DocumentScanner, and Fax interfaces let a basic printer implement only printing while an all-in-one device implements all three.
- Java permits an all-in-one machine to implement multiple interfaces, while a client typed as DocumentScanner cannot accidentally scan through a basic Printer reference.
- The printAll example uses String... to accept zero or more document names, which Java collects into a String array.
- Runnable, Iterable, Comparable, and the model observer each provide focused operations such as run, iterator, compareTo, and update.
- An interface with one abstract method is a functional interface and can be implemented with a lambda expression.
- The checkout service combines high-level tax calculation rules with the low-level detail of sending an email.
- Replacing email with SMS or postal mail requires modifying the service, violating OCP and making tests trigger real notification behavior.
- The Dependency Inversion Principle says high-level and low-level modules should both depend on abstractions.
- The interface's method signatures define an abstraction, while concrete notification classes provide implementation details.
- A Notifier interface separates checkout logic from delivery, with EmailNotifier and SMSNotifier as possible implementations.
- CheckoutService receives a Notifier through its constructor and uses its send method instead of constructing an email sender internally.
- The application selects and injects the concrete notifier, leaving checkout logic unchanged when delivery methods change.
- Constructor injection keeps the notifier dependency fixed for each service instance; a setter is another possible injection method.
- Dependency Injection is a technique for supplying dependencies through a constructor or setter; Dependency Inversion is the design principle about depending on abstractions.
- Aggregation commonly uses dependency injection, while composition creates and owns its dependency inside the containing class.
- The application entry point performs the wiring, sometimes called the composition root, in the general sense of assembling components.
- MVC examples inject the model into the controller and the model or controller into the view.
- The model contains business rules, making it the higher-level component compared with a view that presents or controls interaction.
- A 2048 model can remain the same while desktop arrow-key controls or mobile swipe controls change with the view.
- Separating the model from the view allows the presentation detail to change without rewriting game rules.
- MVC illustrates dependency inversion by keeping business logic independent of replaceable presentation details.
- Dependency injection lets a test supply a FakeNotifier instead of sending a real email or SMS.
- The fake records recipient and message data in an ArrayList, acting as a test double that can also serve as a spy.
- A checkout test injects the fake, checks that a base price of 100 with 7 percent tax produces 107, and verifies that one notification was recorded.
- JUnit 5 assertions compare floating-point values with a tolerance, such as 0.1, and can inspect the recorded message contents.
- In ordinary code, the application decides when to call library methods; with inversion of control, an external framework decides when to call application code.
- JavaFX demonstrates this when launch transfers control to the framework, which later calls the application's start method.
- Dependency injection is one form of inversion of control because components receive dependencies from outside rather than creating them themselves.
- Other examples discussed include JUnit, Observer registration, and Thread.start, where a scheduler determines when the thread runs.
- The abstract MiniApp class defines an overridable start method and a final launch method that controls the startup sequence.
- GreeterApp registers Runnable lambda handlers for hello and bye commands through onCommand.
- MiniApp.launch calls start, then runs registered handlers; the framework reports that help has no registered handler.
- The example mirrors JavaFX: application code supplies callbacks, while the framework controls when those callbacks execute.
- Ghani closes the SOLID discussion and postpones a broader return to testing because little lecture time remains.
- The final lecture is planned to revisit testing and debugging and reflect on course topics useful in industry.
- The dependency-injection test double example previews how isolating a high-level module can make its behavior easier to verify.
Transcript excerpt
0:00 So we are essentially almost at the end of the semester. Um as I mentioned in the past lecture um we will be finishing before Thanksgiving. So Tuesday will be the last lecture. Uh today we should be finishing off with our dis discussion on the solid design principles and uh based on the amount of time remaining we will spend some time looking at perhaps one or two topics from the previous lectures which could uh have some which uh probably deserve a little bit more attention than we've already given and that includes um testing and debugging and perhaps We'll take a look at uh one more topic on Tuesday.
0:49 Uh just an announcement regarding the assignment, the last assignment which is I believe due um immediately after Thanksgiving. So you will have a few extra days for that. Um it is different in that it is uh going to be primarily um manually graded and so um it'll probably take us a few uh extra days to grade that. Hopefully it should be done before your final exams, right? Which means before next Saturday. All right. So let's continue on from where we left off. We had started discussion on the solid design principles uh where we had spoken about the five different design principles which we have in fact been using
1:36 throughout the design patterns uh that we've had we've been talking about in this course. And in the last lecture we we spoke about the single responsibility principle. And today we'll continue on our discussion on the second the O in the solid which is the open closed principle and then uh continue on and finish off our discussion on the rest of the uh design principles. All right. So let's take a look at the
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Muhammad Sayeed Ghani.