HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Avoiding repetitive code for timestamping and updating status

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
updatingandstatusrepetitivetimestampingforcodeavoiding

Problem

This is some boilerplate I found myself writing on a new abstract class. It seems ripe for refactoring, but I'm not sure the best way to implement it more effectively. Is there a pattern for these sort of time-stamping/status-updating methods?

def create() {
    tsCreated = new DateTime()
    userCreated = springSecurityService.currentUser
    status = RequestStatus.OPEN
}

def accept() {
    tsAccepted = new DateTime()
    userAccepted = springSecurityService.currentUser
    status = RequestStatus.ACCEPTED
}

def send() {
    tsSent = new DateTime()
    userSent = springSecurityService.currentUser
    status = RequestStatus.SENT
}

def complete() {
    tsCompleted = new DateTime()
    userCompleted = springSecurityService.currentUser
    status = RequestStatus.COMPLETED
}

def cancel() {
    tsCanceled = new DateTime()
    userCanceled = springSecurityService.currentUser
    status = RequestStatus.CANCELED
}

Solution

No idea about groovy, but it looks like a case for an EnumMap with the map storing the (last) corresponding time and user. You need a single method

def action(RequestStatus status) {
    map.put(status, new Data(new DateTime(), springSecurityService.currentUser))
    this.status = status
}


If you really need 5 methods, you can define them trivially via action.

Code Snippets

def action(RequestStatus status) {
    map.put(status, new Data(new DateTime(), springSecurityService.currentUser))
    this.status = status
}

Context

StackExchange Code Review Q#53995, answer score: 5

Revisions (0)

No revisions yet.