Home > database >  Reassign a field in child classes (clean code)
Reassign a field in child classes (clean code)

Time:10-19

Below, you will find a code snippet I have written for a program simulating a bank account.

I am wondering whether there is a cleaner way to design the inheritance for the friendlyName field?

Ideally, I would have stored it as a const, but it prevents from reasigning its value in child classes.

Thanks a lot!

public abstract class Account
{
   protected string friendlyName;
   public string ShowBalance()
   {
      var message = new StringBuilder();
      message.Append($"Your {friendlyName} balance is {Balance}");
             .Append("See you soon!");
      return message.ToString();
   }
}

public class SavingsAccount : Account
{
    public SavingsAccount()
    {
       friendlyName = "savings account";
    }
}

public class CurrentAccount : Account
{
   public CurrentAccount()
   {
      friendlyName = "current account";
   }
}

CodePudding user response:

You cannot make it const as it would need to be initialized when it is declared. You could make it readonly and set it in the children constructors and this gets as close to const as you can with values that aren't compile-time constants.

public abstract class Account
{
   protected readonly string friendlyName;
   // the rest is the same
}

CodePudding user response:

You can make it an abstract property. Inheriting, non-abstract classes then must override it

public abstract class Account
{
   protected abstract string FriendlyName { get; }

   ...
}

public class SavingsAccount : Account
{
    protected override string FriendlyName => "savings account";
}

public class CurrentAccount : Account
{
    protected override string FriendlyName => "current account";
}
  • Related