Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Bank Accounts and JSON Models

Build a small Objective-C model layer - an Account class with validation and NSError, a Bank that owns accounts, and JSON in and out - then see the same logic run as a verified C stand-in.

Time to combine what you have learned: classes and properties, readonly with a private setter, NSError ** for failures, collections, KVC-style model filling, copy semantics and JSON. The project is a small bank model: accounts that validate deposits and withdrawals, a bank that owns and finds accounts, and conversion to and from JSON so the state can be saved.

Objective-C does not run on this site. The Objective-C code below is the complete design for you to build in Xcode or with GNUstep, and the C stand-in at the end runs the same logic so you can see the behavior and the expected output.

Requirements

  1. An Account has an identifier, an owner, and a balance that outsiders cannot set.
  2. deposit:error: and withdraw:error: return BOOL and fill an NSError for invalid amounts and insufficient funds.
  3. A Bank owns accounts, opens new ones with unique ids, finds them by id and can transfer money between two accounts atomically (both succeed or neither changes).
  4. The whole bank converts to a JSON-ready dictionary and back, validating the data it reads.

The Account class

OBJECTIVEC
// Account.h
#import <Foundation/Foundation.h>

extern NSString * const BankErrorDomain;
typedef NS_ENUM(NSInteger, BankErrorCode) {
    BankErrorInvalidAmount = 1,
    BankErrorInsufficientFunds,
    BankErrorUnknownAccount,
    BankErrorBadData
};

NS_ASSUME_NONNULL_BEGIN

@interface Account : NSObject
@property (nonatomic, copy, readonly) NSString *identifier;
@property (nonatomic, copy, readonly) NSString *owner;
@property (nonatomic, readonly) double balance;

- (instancetype)initWithIdentifier:(NSString *)identifier owner:(NSString *)owner NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;

- (BOOL)deposit:(double)amount error:(NSError **)error;
- (BOOL)withdraw:(double)amount error:(NSError **)error;

- (NSDictionary *)dictionaryRepresentation;
+ (nullable instancetype)accountFromDictionary:(NSDictionary *)dict error:(NSError **)error;
@end

NS_ASSUME_NONNULL_END
OBJECTIVEC
// Account.m
#import "Account.h"

NSString * const BankErrorDomain = @"com.example.bank";

static NSError *BankMakeError(BankErrorCode code, NSString *message) {
    return [NSError errorWithDomain:BankErrorDomain code:code
                           userInfo:@{ NSLocalizedDescriptionKey: message }];
}

@interface Account ()
@property (nonatomic, readwrite) double balance;     // writable only inside the class
@end

@implementation Account

- (instancetype)initWithIdentifier:(NSString *)identifier owner:(NSString *)owner {
    if ((self = [super init])) {
        _identifier = [identifier copy];
        _owner = [owner copy];
        _balance = 0;
    }
    return self;
}

- (BOOL)deposit:(double)amount error:(NSError **)error {
    if (!(amount > 0)) {                      // also rejects NaN
        if (error) *error = BankMakeError(BankErrorInvalidAmount, @"Deposit must be positive");
        return NO;
    }
    self.balance += amount;
    return YES;
}

- (BOOL)withdraw:(double)amount error:(NSError **)error {
    if (!(amount > 0)) {
        if (error) *error = BankMakeError(BankErrorInvalidAmount, @"Withdrawal must be positive");
        return NO;
    }
    if (amount > self.balance) {
        if (error) *error = BankMakeError(BankErrorInsufficientFunds, @"Insufficient funds");
        return NO;
    }
    self.balance -= amount;
    return YES;
}

- (NSDictionary *)dictionaryRepresentation {
    return @{ @"id": self.identifier, @"owner": self.owner, @"balance": @(self.balance) };
}

+ (instancetype)accountFromDictionary:(NSDictionary *)dict error:(NSError **)error {
    id ident = dict[@"id"], owner = dict[@"owner"], balance = dict[@"balance"];
    if (![ident isKindOfClass:[NSString class]] || ![owner isKindOfClass:[NSString class]] ||
        ![balance isKindOfClass:[NSNumber class]] || [balance doubleValue] < 0) {
        if (error) *error = BankMakeError(BankErrorBadData, @"Malformed account data");
        return nil;
    }
    Account *account = [[Account alloc] initWithIdentifier:ident owner:owner];
    account.balance = [balance doubleValue];
    return account;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<Account %@ %@ %.2f>", self.identifier, self.owner, self.balance];
}
@end

Design notes: the public properties are readonly, so no code can set the balance without passing validation; the private class extension makes it writable only inside; init is disabled so every account has an id; and the factory validates the types of everything it reads from JSON, since that data is outside your control.

The Bank class

OBJECTIVEC
// Bank.h
@interface Bank : NSObject
@property (nonatomic, readonly) NSArray<Account *> *accounts;
- (Account *)openAccountForOwner:(NSString *)owner;
- (nullable Account *)accountWithIdentifier:(NSString *)identifier;
- (BOOL)transferAmount:(double)amount fromAccount:(NSString *)from toAccount:(NSString *)to error:(NSError **)error;
- (NSData *)JSONDataWithError:(NSError **)error;
+ (nullable instancetype)bankFromJSONData:(NSData *)data error:(NSError **)error;
@end
OBJECTIVEC
// Bank.m (core parts)
@interface Bank ()
@property (nonatomic, strong) NSMutableDictionary<NSString *, Account *> *byID;
@property (nonatomic) NSUInteger nextNumber;
@end

@implementation Bank

- (instancetype)init {
    if ((self = [super init])) { _byID = [NSMutableDictionary dictionary]; _nextNumber = 1; }
    return self;
}

- (NSArray<Account *> *)accounts {
    return [self.byID.allValues sortedArrayUsingDescriptors:
            @[[NSSortDescriptor sortDescriptorWithKey:@"identifier" ascending:YES]]];
}

- (Account *)openAccountForOwner:(NSString *)owner {
    NSString *ident = [NSString stringWithFormat:@"AC%04lu", (unsigned long)self.nextNumber++];
    Account *account = [[Account alloc] initWithIdentifier:ident owner:owner];
    self.byID[ident] = account;
    return account;
}

- (Account *)accountWithIdentifier:(NSString *)identifier { return self.byID[identifier]; }

- (BOOL)transferAmount:(double)amount fromAccount:(NSString *)from toAccount:(NSString *)to error:(NSError **)error {
    Account *source = self.byID[from], *target = self.byID[to];
    if (!source || !target) {
        if (error) *error = [NSError errorWithDomain:BankErrorDomain code:BankErrorUnknownAccount
                                            userInfo:@{ NSLocalizedDescriptionKey: @"Unknown account" }];
        return NO;
    }
    if (![source withdraw:amount error:error]) return NO;       // nothing changed yet if this fails
    if (![target deposit:amount error:error]) {
        [source deposit:amount error:NULL];                      // roll back the withdrawal
        return NO;
    }
    return YES;
}

- (NSData *)JSONDataWithError:(NSError **)error {
    NSArray *items = [self.accounts valueForKey:@"dictionaryRepresentation"];   // KVC on an array
    return [NSJSONSerialization dataWithJSONObject:@{ @"accounts": items }
                                           options:NSJSONWritingPrettyPrinted | NSJSONWritingSortedKeys
                                             error:error];
}

+ (instancetype)bankFromJSONData:(NSData *)data error:(NSError **)error {
    id root = [NSJSONSerialization JSONObjectWithData:data options:0 error:error];
    if (![root isKindOfClass:[NSDictionary class]] || ![root[@"accounts"] isKindOfClass:[NSArray class]]) {
        if (error && !*error) *error = [NSError errorWithDomain:BankErrorDomain code:BankErrorBadData
                                       userInfo:@{ NSLocalizedDescriptionKey: @"Expected {\"accounts\": [...]}" }];
        return nil;
    }
    Bank *bank = [[Bank alloc] init];
    for (NSDictionary *item in root[@"accounts"]) {
        Account *account = [Account accountFromDictionary:item error:error];
        if (!account) return nil;                                // reject the whole file
        bank.byID[account.identifier] = account;
    }
    return bank;
}
@end

The transfer is written so a failure leaves both accounts as they were: validate first, change second, undo the first change if the second fails. Real banks use a database transaction, but the idea is the same.

A main.m to exercise it:

OBJECTIVEC
int main(void) {
    @autoreleasepool {
        Bank *bank = [[Bank alloc] init];
        Account *ada = [bank openAccountForOwner:@"Ada"];
        Account *grace = [bank openAccountForOwner:@"Grace"];
        NSError *error = nil;
        [ada deposit:100 error:&error];
        if (![bank transferAmount:250 fromAccount:ada.identifier toAccount:grace.identifier error:&error]) {
            NSLog(@"Transfer failed: %@", error.localizedDescription);   // Insufficient funds
        }
        [bank transferAmount:40 fromAccount:ada.identifier toAccount:grace.identifier error:&error];
        NSData *json = [bank JSONDataWithError:&error];
        NSLog(@"%@", [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding]);
    }
    return 0;
}

Run the same logic in C

The program below implements the account rules, the transfer with rollback, and writes the state in a JSON-like line format. It prints deterministic output, so you can compare it with what your Objective-C version should log.

C Stand-in: the bank logic in C

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Extensions to try

  • Persist the JSON with writeToFile:atomically: and reload it at startup.
  • Add a Transaction class and an array in each account; expose transactions as readonly with a copy.
  • Make Bank thread-safe with a serial dispatch queue.
  • Post an NSNotification after each transfer and observe it from a logger (next project).
  • Write unit tests with XCTest for every error path.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is balance declared readonly publicly and readwrite in a class extension?

    Outside code can read the balance but only deposit and withdraw can change it.
  2. 2. In transferAmount:..., why is the withdrawal rolled back when the deposit fails?

    Money must not vanish if the second half of the operation fails.
  3. 3. Why does accountFromDictionary: check isKindOfClass: on each value?

    External data must be validated before use.
  4. 4. What does marking init as NS_UNAVAILABLE achieve?

    Callers must supply an identifier and owner, so no account lacks them.

Summary

  • Encapsulate state with readonly properties and private writable redeclarations.
  • Report failures with BOOL plus NSError **, and make multi-step operations all-or-nothing.
  • Validate every value read from JSON before trusting it.
  • Keep designated initializers explicit with NS_DESIGNATED_INITIALIZER.

Next: Project: An Observer and Notification Center