SOLID Principles (Java)

Context: FIT2099_MOC Β· Robert C. Martin’s five design guidelines (not laws) Β· the shared rationale vocabulary for the design assignment Β· all aimed at Reducing Dependencies (ReD)

Quick Revision

  • 🎯 Objective: judge and justify a design against five principles βž” low coupling, high cohesion, easy extension.
  • πŸ“¦ Core Components: S Β· O Β· L Β· I Β· D.
  • ⚑ Key Constraint: SOLID = guidelines, not laws β€” over-applying (too many tiny classes/abstractions) adds complexity; apply where it reduces real dependency pain.

πŸ“ The Five Principles

PrincipleOne-lineSmellFix
SSingle Responsibilityone class, one reason to changeGod class; unrelated methodssplit by reason-to-change
OOpen-Closedopen to extend, closed to modifyinstanceof chain grows per featureabstract method / polymorphism
LLiskov Substitutiona subtype must be usable as its baseoverride throws / empty / instanceoffix the abstraction (sibling interface)
IInterface Segregationno client forced onto unused methodsempty method bodies to satisfy an interfacesplit into small interfaces
DDependency Inversiondepend on abstractions, not concreteshigh-level class references concrete typesinject/hold an interface type
  • ReD thread βž” every principle ultimately reduces dependencies so the design tolerates change (coupling/cohesion/extensibility).
  • Chained relationships βž” ISP feeds LSP (small interfaces are easier to fully honour) and SRP (small interfaces β†’ focused classes).

πŸ“ LCOM β€” measuring cohesion (SRP)

  • Lack of Cohesion of Methods βž” where = methods, = instance fields, = methods touching field .
  • Read it βž” LCOM = perfectly cohesive (every method uses every field); high LCOM (β†’ 1) = the class splits into unrelated clusters βž” SRP candidate.
  • Heuristic βž” with and is a warning sign (but hard to avoid entirely).

⚠️ Downcasting & instanceof (cross-cutting smell)

  • Upcasting βž” subclass β†’ supertype, implicit & safe (Vehicle v = new Sedan();) β€” enables polymorphism; good.
  • Downcasting βž” supertype β†’ subclass, explicit & risky (((Truck) vehicle).cargo();) β€” bypasses compile checks, can throw ClassCastException.
  • Why bad (design) βž” depends on a lower-level type (breaks abstraction), often signals an LSP and OCP violation, and grows if (x instanceof Y) chains.
  • When tolerable βž” occasionally the cleaner-abstraction cost is too high; if you must downcast, guard with instanceof first and justify it in the rationale (rarely needed in assignments).

🧠 Active Recall