A second class, with more detail
Your second class is where the shape of a good class becomes clear: it holds its own data, guards its own rules and offers a small set of useful methods.
A class that sets itself up
C#
public class BankAccount
{
private double balance;
public BankAccount(double opening)
{
balance = opening;
}
public void Deposit(double amount)
{
if (amount > 0)
{
balance = balance + amount;
}
}
public double Balance()
{
return balance;
}
}What is better here
- The constructor sets a sensible starting value, so no object begins in a broken state.
- The deposit method refuses a negative amount, so the rule lives with the data.
- The balance can be read but not set directly from outside.
One responsibility. A class should have one reason to change. If you struggle to describe what a class does in one sentence, split it.
Related to this is a question you will meet constantly: where a variable can be seen.