Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

I was working on Java some code. It had two different objects that extended a common base object. There was a method that was called to load the common values. The receiving methods would then cast the returned object to the type that it was given. Here was the original code:

private ConvergeBaseRequest setProperties(ConvergeBaseRequest request) {
    // do some stuff
    request.setSslMerchantId(merchantId);
    request.setSsluserId(userId);
    request.setSslPin(pin);
    return request;
}

It was called by:

request = (ConvergeCCSaleRequest) setProperties(request);

After a little tweaking, I came up with the following method:

private <T extends ConvergeBaseRequest> T setProperties(T request) {
    // do some stuff
    request.setSslMerchantId(merchantId);
    request.setSsluserId(userId);
    request.setSslPin(pin);
    return request;
}

This made it simpler to call also,

request = setProperties(request);

With just a little bit of smarts, we were able to use Java Generics to make our calling code a little bit simpler.

July 19th, 2016

Posted In: Java, java ninja, Javaninja

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com