Java Reference
In-Depth Information
def accountsFile
Map<Integer, Account> accounts = [:]
private static int nextId
boolean dirty
I deliberately declared the variable representing the accounts file to be of type def rather
than File , for reasons I'll explain when I create the stub. The other attributes are a map
to represent the accounts cache (using generics, which Groovy compiles successfully but
doesn't enforce [ 9 ] ), a private static integer that will be my primary key generator,
and a Boolean flag to indicate whether the accounts cache needs to be refreshed.
9 That's another subtle trap. The syntax for Java generics compiles in Groovy, but just because you declared a
List<Integer> doesn't mean you can't add instances of String , Date , or Employee if you want to. In
Groovy, think of the generic declaration as nothing more than documentation.
Here's the method used to read the accounts from the file:
void readAccountsFromFile() {
accountsFile.splitEachLine(',') { line ->
int id = line[0]. toInteger ()
double balance = line[1]. toDouble ()
accounts[id] = new Account(id:id,balance:balance)
}
nextId = accounts?.keySet(). max () ?: 0
nextId ++
dirty = false
}
Each account is stored as plain text, with a comma separating the id from the balance .
Readingaccountsusesthe splitEachLine methodthattakestwoarguments:thedelim-
iter (a comma in this case) and a closure that defines what to do with the resulting list. The
closure says to parse the ID and balance into the proper data types, instantiate an account
with the resulting values, and save it in the map. Then I need to set the nextId variable
to one more than the max of the IDs used so far, which gives me an opportunity to use
the cool Elvis operator. [ 10 ] Finally, because this method refreshes the cache, I can set the
dirty flag to false .
10 I don't really go out of my way to find excuses to use the cool Elvis operator, but I don't pass them up when they
present themselves either.
The corresponding method to write out the accounts is shown next:
 
 
Search WWH ::




Custom Search