All Courses
OOP: ANTI PATTERNS

Unnecessary Friends

Concept Definition

An unnecessary friend is a function or class given private access when normal public behavior would be enough. C++ friendship is not automatically bad, but it bypasses encapsulation. Too much friendship makes private data less meaningful.

Think of a restricted lab where too many people receive master keys. The keys may help once, but security becomes weak.

Why It Matters

Friendship creates tight coupling. A friend function can depend on private details, so changing those details may break more code. This makes refactoring harder and weakens the class boundary.

Friend is justified when the clean public API would otherwise become worse, such as some non-member operators. But it should be a deliberate design choice, not a shortcut.

Syntax Block

class Box {
    friend void inspect(const Box& box); // special private access
};

Explained Code

Example: Avoid Friend When Getter Is Enough

class Temperature {
private:
    double celsius = 0.0;                       // private representation

public:
    explicit Temperature(double value) : celsius(value) {} // initialize
    double getCelsius() const { return celsius; } // safe public query
};

bool isFreezing(const Temperature& temperature) {
    return temperature.getCelsius() <= 0.0;     // no friendship needed
}

isFreezing() does not need private access. A public query communicates the needed information without exposing representation details broadly.

Key Points / Rules

  • Friendship should be rare and intentional.
  • Use friend when it creates a cleaner API than public exposure.
  • Stream operators may be friend if they need private fields.
  • Friendship is not inherited, mutual, or transitive.
  • Prefer public behavior when it preserves encapsulation.

Common Mistakes

  1. Using friend to avoid writing a proper interface. That hides a design problem.
  2. Making whole classes friends too easily. This gives many methods private access.
  3. Assuming friendship goes both ways. If A friends B, B does not automatically friend A.
  4. Using friend for testing private details. Tests should usually check public behavior.

Quick Check

  1. Why does isFreezing() not need to be a friend?
  2. When might a stream operator reasonably be a friend?

Viva Answer

Unnecessary friendship weakens encapsulation by giving private access without a strong reason. Use friend only when it makes the public API cleaner and safer.