Bank Ledger
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 57 of 57.
Challenge
HardBuild a small bank from Reference Classes in four files. All definitions are wrapped in suppressMessages(); use call. = FALSE in every stop().
Account.R: fieldsid,owner,balance(0 at the start).deposit(x)andwithdraw(x)stop withinvalid amountwhenxis missing or below 1;withdraw()stops withinsufficient funds in 2when the balance would go belowlowest(), which is 0.month_end()does nothing;line()returns1 ada checking: -20usingkind().Checking.R: kindchecking; the balance may go down to -100.Savings.R: kindsavings; at most 2 withdrawals per month (withdrawal limit on 2), counted only when they succeed;month_end()adds 1% interest, rounded down, and resets the count.Bank.R:open_account(kind, id, owner)(account 2 exists),get_account(id)(no account 9),transfer(from, to, amount), which changes nothing when the withdrawal fails,month_end()for every account, andstatement(), the lines of all accounts sorted by id.
The supplied code reads commands open checking 1 ada, dep 1 100, wd 2 30, tr 1 2 50 or month, prints ok or the error message for each, then the statement.
Your code goes in Account.R, Checking.R, Savings.R and Bank.R. main.R holds the supplied input/output code and cannot be edited.
Try it yourself
source("Account.R")
source("Checking.R")
source("Savings.R")
source("Bank.R")
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
bank <- Bank$new()
for (line in input) {
p <- strsplit(line, " ")[[1]]
n <- suppressWarnings(as.numeric(p[-1]))
msg <- tryCatch({
switch(p[1],
open = bank$open_account(p[2], as.numeric(p[3]), p[4]),
dep = bank$get_account(n[1])$deposit(n[2]),
wd = bank$get_account(n[1])$withdraw(n[2]),
tr = bank$transfer(n[1], n[2], n[3]),
month = bank$month_end())
"ok"
}, error = function(e) conditionMessage(e))
cat(line, ": ", msg, "\n", sep = "")
}
for (l in bank$statement()) cat(l, "\n", sep = "")
All lessons in Object Oriented Programming
1S3 Basics
Working With FilesLists With a ClassConstructor FunctionsPrint and Format MethodsValidators and HelpersRecap - Temperatures4Encapsulation in R
Closures as ObjectsEnvironments as ObjectsAccessor FunctionsGuarding StateRecap - Parking Meter2S3 Generics and Methods
Generics and UseMethodDefault MethodsMethods for Base GenericsNextMethod BasicsRecap - Shape Areas8Reference Classes
Defining Reference ClassesMethods and Field UpdatesCopy SemanticsInheritance and callSuperRecap - Task Queue11Project: Library Management
Books and MembersBorrowing BooksPractice on your own: Online R compiler