Skip to main content
Designing a Console Banking System to Showcase Core OOP and Domain Invariants in Java

Designing a Console Banking System to Showcase Core OOP and Domain Invariants in Java

January 8, 2025 3 min read Java, OOP, Software Architecture, Data Structures, Fintech

Designing a Console Banking System to Showcase Core OOP and Domain Invariants in Java is a Developer Journal article by Ancel Ajanga on https://ancel.co.ke. Why core object-oriented principles still matter: designing an auditable console banking system with strict domain encapsulation, polymorphism, and financial precision in Java. It focuses on: Tutorial code often treats OOP as boilerplate getters and setters, failing to demonstrate how encapsulation actually prevents invalid business states and financial corrup…

Why core object-oriented principles still matter: designing an auditable console banking system with strict domain encapsulation, polymorphism, and financial precision in Java.

Who this is for

Students, junior engineers, and developers looking to master real object-oriented design, encapsulation, and financial precision beyond textbook theory.

Problem

Tutorial code often treats OOP as boilerplate getters and setters, failing to demonstrate how encapsulation actually prevents invalid business states and financial corruption.

Business outcome

A robust terminal-based banking engine demonstrating strict account balance invariants, transaction audit trails, overdraft boundaries, and precise currency arithmetic.

Metrics

  • Zero floating-point rounding errors via strict BigDecimal arithmetic
  • Polymorphic account specialization for Savings and Checking rules
  • Immutable transaction log records capturing full audit history

In the era of microservices, serverless functions, and modern JavaScript frameworks, it is easy to forget that the foundation of reliable software engineering lies in clean object-oriented modeling and rigorous invariant protection.

I designed this Console Banking System in Java to demonstrate how classic OOP principles—**Encapsulation, Inheritance, Polymorphism, and Abstraction**—solve real business problems when modeled with discipline.

The Problem: Financial Invariants and Unchecked State

In financial systems, an invalid state is not just a UI bug; it is an accounting disaster: - An account balance must never become a negative number unless explicitly authorized by an overdraft agreement. - Money can never be created or destroyed: every withdrawal must reflect a corresponding debit, and transfers must be atomic. - Floating-point representations (`float` or `double`) introduce binary rounding inaccuracies (e.g., `0.1 + 0.2 = 0.30000000000000004`), which can never be permitted in ledger accounting.

Architectural Approach: Clean Object-Oriented Modeling

In textbooks, OOP concepts are often explained through trivial examples: `Dog extends Animal` or `Car extends Vehicle`. These examples fail to communicate how object-oriented design protects real business logic.

In a banking engine, the four pillars serve concrete purposes:

1. **Encapsulation**: Account balances and transaction histories must never be public fields. An external caller cannot simply write `account.balance = 5000`. Balances can only mutate through validated methods (`deposit(amount)`, `withdraw(amount)`) that enforce minimum balance rules, currency constraints, and overdraft limits. 2. **Inheritance**: Both a `SavingsAccount` and a `CheckingAccount` share core behaviors: an account number, account holder identity, balance tracking, and transaction history. An abstract `Account` base class houses shared capabilities while delegating specialized rules to subclasses. 3. **Polymorphism**: A `SavingsAccount` accrues interest upon monthly close, while a `CheckingAccount` charges per-transaction maintenance fees or permits bounded overdrafts. The banking system can iterate over a portfolio of `List<Account>` and invoke `account.endOfMonthProcessing()` without needing to inspect the underlying account type. 4. **Abstraction**: A customer interacting with the CLI does not need to know how interest is calculated or how transaction logs are structured. The interface exposes a clean API: deposit, withdraw, transfer, and print statement.

Technical Depth: Class Architecture and State Protection

The domain model is structured into clean, single-responsibility classes: - **`Account` (Abstract Base Class)**: Protects balance invariants with private fields and `BigDecimal` arithmetic (never floating-point floats or doubles, which introduce rounding errors in financial math). - **`SavingsAccount`**: Implements strict withdrawal caps and automated monthly interest computation based on average daily balance. - **`CheckingAccount`**: Models an explicit overdraft limit (`overdraftLimit`), allowing transactions to proceed into negative balance up to an authorized threshold while generating fee records. - **`Transaction`**: Immutable value object recording timestamp, transaction type (DEPOSIT, WITHDRAWAL, TRANSFER), amount, and post-transaction balance snapshot.

ava
public abstract class Account {
    private final String accountNumber;
    private final Customer owner;
    protected BigDecimal balance;
    private final List<Transaction> history;

    public synchronized boolean withdraw(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("Withdrawal amount must be positive");
        }
        if (!canWithdraw(amount)) {
            return false;
        }
        balance = balance.subtract(amount);
        history.add(new Transaction(TransactionType.WITHDRAWAL, amount, balance));
        return true;
    }

    protected abstract boolean canWithdraw(BigDecimal amount);
}

Defensive Input Handling and Invariant Enforcement

A console application accepts raw terminal string input. Without rigorous defensive programming, user inputs can trigger fatal runtime crashes: - Non-numeric inputs during transfer amount prompts. - Negative deposit amounts intended to secretly drain funds. - Transfers targeting non-existent recipient account numbers.

The system encapsulates input parsing in a robust `InputHandler` utility with structured try-catch loops, ensuring the banking engine handles malformed input gracefully and re-prompts the user with clear guidance.

Key Engineering Takeaways

1. **Never Use Floats for Money**: In any language, floating-point representations introduce rounding artifacts. Always use precise arbitrary-precision types like Java's `BigDecimal` or integer minor currency units (cents). 2. **Polymorphism Eliminates Conditionals**: If you find yourself writing `if (account.getType() == "SAVINGS")` throughout your codebase, you have an object-oriented design flaw. Let polymorphism and dynamic dispatch handle type-specific behavior. 3. **Foundations Outlive Trends**: Tools and frameworks come and go, but the discipline of clean encapsulation, domain validation, and explicit state modeling remains universally applicable across every language.

Review the Console Banking System Case Study or explore the [Banking System Project Page](/projects/banking-system). If you enjoy discussing core language fundamentals and software design, [feel free to get in touch](/contact).

Trade-offs

Intentionally built as a pure console application without web frameworks or ORMs to focus 100% on domain modeling, class responsibilities, and robust exception handling.

Challenges faced

Protecting account balances against negative withdrawals, unauthorized overdrafts, and concurrency inconsistencies without leaking internal state.