Go course

Projects and Final ReviewProject: Mini Bank Ledger

Go

Display

Theme

Projects and Final Review · Test exercise

Project: Mini Bank Ledger

Time to bring together a lot of what you've learned: structs, maps, slices, enums, interfaces (error and fmt.Stringer), plus sentinel errors, custom errors, and wrapping with %w.

You'll build a mini bank for a campus cooperative. Part of the code is already provided:

  • The Jenis enum (Setoran, Penarikan, TransferMasuk, TransferKeluar, that is deposit, withdrawal, incoming transfer, outgoing transfer), along with its String() method.
  • The Transaksi{Jenis, Jumlah, Lawan} struct. Lawan is the other account's name in a transfer, and empty for deposits and withdrawals.
  • The sentinel errors ErrAkunTidakAda, ErrAkunSudahAda, ErrJumlahTidakValid (account not found, account already exists, invalid amount).
  • The custom error *SaldoKurangError (insufficient balance), which satisfies the error interface.
  • BankBaru, BukaAkun, Saldo, and Riwayat are already complete. Study how they use the map and wrap errors.

Task

Complete the three methods below. Every successful operation must append a Transaksi to the history of the account involved (b.riwayat[nama]). A failed operation must not change the balance or the history.

  1. func (b *Bank) Setor(nama string, jumlah int) error

    • jumlah <= 0 → an error that wraps ErrJumlahTidakValid.
    • The account doesn't exist → an error that wraps ErrAkunTidakAda (see how Saldo does it).
    • Success: the balance goes up; record Transaksi{Jenis: Setoran, Jumlah: jumlah}.
  2. func (b *Bank) Tarik(nama string, jumlah int) error

    • Validate the amount and the account as in Setor.
    • Insufficient balance → return &SaldoKurangError{Akun: nama, Saldo: <saldo saat ini>, Diminta: jumlah}, where <saldo saat ini> is the current balance.
    • Success: the balance goes down; record Transaksi{Jenis: Penarikan, Jumlah: jumlah}.
  3. func (b *Bank) Transfer(dari, ke string, jumlah int) error

    • Validate the amount, then both accounts must exist (ErrAkunTidakAda).
    • Insufficient balance in dari → a *SaldoKurangError for the dari account.
    • Success: move the money, record Transaksi{Jenis: TransferKeluar, Jumlah: jumlah, Lawan: ke} in the history of dari and Transaksi{Jenis: TransferMasuk, Jumlah: jumlah, Lawan: dari} in the history of ke.

The tests check the balances, the histories, and the errors: sentinel errors with errors.Is, and *SaldoKurangError through the message from its Error() method.

main.go
package main

import (
	"errors"
	"fmt"
	"slices"
)

type Jenis int

const (
	_ Jenis = iota
	Setoran
	Penarikan
	TransferMasuk
	TransferKeluar
)

func (j Jenis) String() string {
	switch j {
	case Setoran:
		return "Setoran"
	case Penarikan:
		return "Penarikan"
	case TransferMasuk:
		return "TransferMasuk"
	case TransferKeluar:
		return "TransferKeluar"
	default:
		return fmt.Sprintf("Jenis(%d)", int(j))
	}
}

type Transaksi struct {
	Jenis  Jenis
	Jumlah int
	Lawan  string
}

var (
	ErrAkunTidakAda     = errors.New("akun tidak ditemukan")
	ErrAkunSudahAda     = errors.New("akun sudah ada")
	ErrJumlahTidakValid = errors.New("jumlah harus lebih dari nol")
)

type SaldoKurangError struct {
	Akun    string
	Saldo   int
	Diminta int
}

func (e *SaldoKurangError) Error() string {
	return fmt.Sprintf("saldo %s tidak cukup: tersedia %d, diminta %d", e.Akun, e.Saldo, e.Diminta)
}

type Bank struct {
	saldo   map[string]int
	riwayat map[string][]Transaksi
}

func BankBaru() *Bank {
	return &Bank{
		saldo:   make(map[string]int),
		riwayat: make(map[string][]Transaksi),
	}
}

func (b *Bank) BukaAkun(nama string) error {
	if _, ada := b.saldo[nama]; ada {
		return fmt.Errorf("buka akun %q: %w", nama, ErrAkunSudahAda)
	}
	b.saldo[nama] = 0
	return nil
}

func (b *Bank) Saldo(nama string) (int, error) {
	s, ada := b.saldo[nama]
	if !ada {
		return 0, fmt.Errorf("saldo %q: %w", nama, ErrAkunTidakAda)
	}
	return s, nil
}

// Riwayat mengembalikan salinan riwayat transaksi agar tidak bisa diubah dari luar.
func (b *Bank) Riwayat(nama string) []Transaksi {
	return slices.Clone(b.riwayat[nama])
}

func (b *Bank) Setor(nama string, jumlah int) error {
	// TODO
	return nil
}

func (b *Bank) Tarik(nama string, jumlah int) error {
	// TODO
	return nil
}

func (b *Bank) Transfer(dari, ke string, jumlah int) error {
	// TODO
	return nil
}

func main() {
	bank := BankBaru()
	bank.BukaAkun("Ani")
	bank.BukaAkun("Budi")

	bank.Setor("Ani", 100000)
	if err := bank.Transfer("Ani", "Budi", 30000); err != nil {
		fmt.Println("Transfer gagal:", err)
	}
	if err := bank.Tarik("Budi", 50000); err != nil {
		fmt.Println("Tarik gagal:", err)
	}

	for _, nama := range []string{"Ani", "Budi"} {
		s, _ := bank.Saldo(nama)
		fmt.Printf("%s: saldo %d\n", nama, s)
		for _, t := range bank.Riwayat(nama) {
			fmt.Printf("  %-14v %7d %s\n", t.Jenis, t.Jumlah, t.Lawan)
		}
	}
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)