Extensions by behavior

An effective strategy in Swift is to organize your code into extensions by behavior. You can even apply access modifiers to extensions themselves, which will help you categorize entire sections of code as public, internal, or private.

Begin by adding some basic fraud protection to CheckingAccount. Add the following properties to CheckingAccount:

fileprivate var issuedChecks: [Int] = [] fileprivate var currentCheck = 1

These will keep track of checks that have been written by the checking account.

Next, add the following private extension:

private extension CheckingAccount {

func inspectForFraud(with checkNumber: Int) -> Bool { return issuedChecks.contains(checkNumber)

}

func nextNumber() -> Int { let next = currentCheck currentCheck += 1

return next

}

}

These two methods can be used by CheckingAccount to determine the number of a check that is being written, as well as check to ensure it has been in fact issued by the account.

Notably, this extension is marked private. A private extension implicitly marks all of its members as private as well. These fraud protection tools are meant to be used by the CheckingAccount only — you definitely don’t want other code incrementing the currentCheck number!

Putting these two methods together also ties together two related and cohesive methods. It’s clear to yourself and anyone else maintaining the code that these two are cohesive and help solve a common task.

results matching ""

    No results matching ""