I am reviewing some classes that use polymorphism and inheritance of a colleague of…
- User
I am reviewing some classes that use polymorphism and inheritance of a colleague of mine. However, I am a little bit stuck while understanding if her proposal is fine or not from a design perspective. Indeed, let me share the base class: class Account { private: std::string name; double balance;
public: Account(const std::string &name = "Unnamed Account", double balance = 0.0) : name{name}, balance{balance} {}
virtual bool deposit(double amount); virtual bool withdraw(double amount); virtual double get_balance() const; virtual std::string get_name() const; virtual void display() const { std::cout << "Account Name: " << name << ", Balance: " << balance << std::endl; } virtual ~Account() = default;}; ~ This class is a mix between an interface and a base class. Indeed, the user needs name and balance as per a base class. deposit and withdraw should be implemented for each derived, so I expect them as pure virtual. get_balance and get_name I expect them not virtual because they should be just getters. display could be changed while adding a private member that contains a class name such that it can be implemented just once because it can retrieve the class name from a private member. I have two questions:
- Does my improvements sound for you? (I know you have few context)
- Generally speaking, I can I choose from a design perspective what is the best approach in such a case? There are thumb rule or questions that I can ask myself to improve the code from a design perspective? Thank you for the feedback.
- Assistant
It's great that you're carefully analyzing the design of the class and thinking critically about how it can be improved. I'll try to address both of your questions in detail.
1. Do your proposed improvements make sense?
Let's examine your points regarding improvements to the
Accountclass:a) Deposit and withdraw as pure virtual methods
- Your suggestion to make
depositandwithdrawpure virtual methods (virtual bool deposit(double amount) = 0;) makes sense if the base classAccountis indeed intended to be an abstract base class (acting as an interface) that leaves specific behavior for derived classes. - In other words, if each type of account (such as
SavingsAccount,CheckingAccount, etc.) has completely different implementations fordepositandwithdraw, then making them pure virtual is appropriate. - However, if there’s a default implementation (e.g., generic logic for deposit/withdraw), you may want to keep them as
virtualwith a default behavior that can be optionally overridden.
b) Getters (
get_balanceandget_name) should not be virtual- You are correct:
get_balanceandget_nameseem like simple getters that rely on data members of the base class, and unless there's a strong reason for these to vary in behavior in derived classes, they shouldn’t bevirtualat all. Leave them as regular (non-virtual) member functions. - If no overriding is required for these functions, making them virtual violates the "You Aren't Gonna Need It" (YAGNI) principle.
c)
display()function enhancement- Good insight! If you want to define the behavior of
display()only once in the base class but allow it to include class-specific information, you can introduce a privatestd::stringin the base class to hold a class name or identifier (e.g.,"SavingsAccount","CheckingAccount", etc.). You can set this member in the constructor of the derived class usingAccount’s constructor. - Alternatively, the
typeid(*this).name()function from<typeinfo>can provide the runtime class name, but it’s not as clean and isn't user-friendly (the output can be cryptic or compiler-specific).
Your overall suggestions are valid and aligned with good design practices.
2. How to evaluate the design objectively?
When evaluating or designing a class that uses inheritance and polymorphism, you should consider the following principles and ask yourself specific guiding questions:
a) Single Responsibility Principle (SRP)
Does the class have a clear and focused responsibility?
- The
Accountclass seems reasonably focused—it represents a general concept of an account, providing basic fields (name,balance) and behaviors (deposit,withdraw). However, it's an interesting mix of being both an interface and a base class that carries implementation. Ensure you're not trying to do too much in one class.
b) Interface Segregation Principle (ISP)
Is the interface exposing only the required operations?
- If derived classes must implement
depositandwithdraw, these should either:- Be pure virtual methods (
= 0). - Or, provide default behavior in the base class where possible.
- Be pure virtual methods (
- For simple getters like
get_balanceandget_name, making them virtual unnecessarily burdens users who derive from this class—they shouldn't have to worry about overriding trivial functionality.
c) Liskov Substitution Principle (LSP)
Can I seamlessly substitute derived classes where the base is expected?
- Any derived class (e.g.,
SavingsAccount) should behave like anAccountwithout clients needing to know whether it's a base class or derived class. For example:- If
withdrawordepositisn't implemented properly in the derived class, you might break this principle. - To avoid this, the behavior of the base class should be as generic and intuitive as possible.
- If
d) Dependency Inversion Principle (DIP)
Am I coding to an abstraction, rather than a concrete implementation?
- If the
Accountclass will be used by higher-level modules as a polymorphic base, it’s better to define it abstractly—meaning minimal implementation in the base class and leaving specifics to derived classes.
e) Open/Closed Principle (OCP)
Can I extend the class without modifying its base structure?
- The base
Accountclass is reasonably extensible. By relying ondeposit,withdraw, and potentially virtual properties ofdisplay, you can add new account types and customize their behavior. - However, to adhere to OCP, ensure the base class provides enough customization points for derived classes without needing to edit the base itself.
Guiding Questions for Refactoring
Ask yourself these questions to assess and improve the design:
-
What is the role of this class?
- If
Accountis meant to be a reusable abstraction (interface), simplify it and make the non-essential parts likenameorbalanceoptional. Introduce a pure separator between what should be implemented and inherited.
- If
-
Which methods vary across derived classes?
- If all derived classes must override a method like
deposit, make it pure virtual.
- If all derived classes must override a method like
-
Which methods are fixed (base functionality)?
- If functionality like
get_balanceorget_nameis fixed, don’t expose them as virtual—make them non-virtual.
- If functionality like
-
Do I require polymorphic behavior?
displayis a candidate for polymorphic behavior, but if the output is derived from other fields in the base class, it could be made non-virtual to simplify the implementation.
-
Am I violating encapsulation?
- Ensure that the details (
name,balance) cannot be directly tampered with outside the class and provide controlled access via non-virtual getters if needed.
- Ensure that the details (
Final Suggestions
Here’s how you might refactor the
Accountclass based on your feedback:class Account { private: std::string name; double balance; protected: std::string account_type; // Add a member to store the type of account for display() public: Account(const std::string& name = "Unnamed Account", double balance = 0.0, const std::string& type = "Account") : name{name}, balance{balance}, account_type{type} {} virtual bool deposit(double amount) = 0; // Pure virtual for custom implementation in derived classes. virtual bool withdraw(double amount) = 0; // Same logic as deposit. double get_balance() const { return balance; } // Standard getters - keep non-virtual. std::string get_name() const { return name; } virtual void display() const { // Default behavior for display, extendable in derived classes if needed. std::cout << "Account Type: " << account_type << ", Account Name: " << name << ", Balance: " << balance << std::endl; } virtual ~Account() = default; // Virtual destructor for polymorphic base class. };Derived classes can set
account_typeto represent their type, provide their own implementations fordepositandwithdraw, and overridedisplayif required.
Takeaway
Your proposed improvements are solid, especially in making
depositandwithdrawpure virtual, simplifying getters, and ensuringdisplayis cleaner. When evaluating designs in general:- Focus on separating interface and implementation appropriately,
- Adhere to SOLID principles,
- Avoid premature generalization (don’t overuse virtual unnecessarily), and
- Make the design extensible without sacrificing clarity.
This approach will lead to a clean, maintainable design!
- Your suggestion to make