Skip to content

Code challenge: Flow of control

by aloshbennett on May 26th, 2014

Can you make this better?

The API needs to store the latest version of a record. It does so by checking the revision number of the record being inserted against the current version in the db. If the revision number of the new record is greater, it is inserted. Otherwise it is ignored. The db provides conditional APIs to perform check-and-update operations. Give it a shot.

DB APIs:

//Gets the current record. Returns null if no record is found.
public Record getRecord(String primaryId);
 
//Inserts a record. Throws exception if a record is already present.
public void insert(Record rec) throws ConstraintViolationException;
 
//Updates a record. Throws exception if the record is not of a 
//newer revision - basically the verison number should be increasing
public void update(Record rec) throws ConstraintViolationException;

And here is my attempt:

public void storeLatestVersion(Record newRec) {
    String primaryKey = newRec.primaryKey;
    Record currentRec = getRecord(primaryKey);
    if (currentRec==null) {
        try {
            insert(newRec);
            //done. lets go home
            return;
        } catch(ConstraintViolationException ce) {
            //Some one bet me to it. Let me fetch the current rec
            currentRec = getRecord(primaryKey);
        }
    }
 
    //at this point currentRec cannot be null.
    //making such an assumption makes me sad :(
 
    if (currentRec.versionNo < newRec.versionNo) {
        try {
            update(newRec);
            //yey! job well done
            return;
        } catch(ConstraintViolationException ce) {
            //someone has updated the record in the mean time?
            currentRec = getRecord(primaryKey);
        }
    }
 
    if (currentRec.versionNo >= newRec.versionNo) {
        //nothing to do as there is later version in the db.
        //lets ignore the current record.
        return;
    } else {
        //this can't be happening. something went wrong.
    }
}

From → java

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS