Nivaar Exam Prep

25-Comp-B11 Advanced Software Design · May 2015

Question 25 of 27: Friend Functions and Modular Programming

Nivaar worked solution (AI-drafted; not reviewed by a licensed engineer) · Last updated

Notes on this paper

Reference texts: Sommerville, Software Engineering (10th ed., Pearson) — software processes, requirements engineering, agile methods, design principles, dependability; Pressman, Software Engineering: A Practitioner's Approach (9th ed.) — supplementary process and quality coverage; Gamma, Helm, Johnson & Vlissides (GoF), Design Patterns: Elements of Reusable Object-Oriented Software — structural/behavioural pattern catalogue (Adapter, Bridge, Strategy, Observer, Template Method, Composite, etc.); Sebesta, Concepts of Programming Languages (12th ed.) — polymorphism, dynamic binding, inheritance and language-level object semantics; Bertrand Meyer, Object-Oriented Software Construction — design by contract, preconditions/postconditions/invariants, the open–closed principle; Barbara Liskov's 1987 substitutability paper for Question 11; Rogers, Sharp & Preece, Interaction Design, and Nielsen, Usability Engineering, for Question 21's HMI-specific non-functional requirements.

PART I — General Principles

Question 25: Friend Functions and Modular Programming (Part V)

Question text not reproduced: the examination questions are © Engineers and Geoscientists BC. Open the official past paper (linked at the top of this page) to read the question, then follow the worked solution below.

friend grants a function or class direct ACCESS to another class's private/protected members, bypassing the encapsulation boundary the class's public interface would otherwise enforce.

Performance benefit. It lets tightly-coupled, performance-critical code (e.g., operator<<, a matrix-multiplication kernel, a custom iterator's implementation) access the internal representation DIRECTLY rather than through possibly-virtual public accessor calls, avoiding call overhead and unnecessary defensive copying in a hot path.

Why it is detrimental to modularity. It breaks encapsulation and information hiding — the central modular-programming principle (also central to Question 19 and Question 23): a friend can read AND WRITE the class's internal representation directly, so the class's actual invariant-preserving interface silently expands to include every friend function/class scattered anywhere in the codebase, not just its declared public methods. Consequences:

Conclusion. friend is a deliberate, narrow escape hatch traded against modularity for a genuine, measured performance need (canonical legitimate uses: operator-overload pairs, tightly-coupled iterator/container pairs) — it should be used sparingly, only where the performance case is real, never as a routine substitute for a proper public interface.