A Quick Java Gem, Borrowing from C#

September 23, 2013 Steve Hawley

I love the C# operator as.  This is syntactic sugar to cast an object of one type another type, but evaluate to null if the types are incompatible.  This is equivalent to writing the following code:

Bar bar = o is bar ? (Bar)o : null;

It’s just neater to use as.  I’ve been writing some Java code and I really wanted the as operator but Java doesn’t have it.  Instead I could write this equivalent:

Bar bar = o instanceof Bar.class ? (Bar)o : null;

but embedding that ternary expression into my code is sloppy.  Instead, I wrote it into this object:

public class Cast {

    public static <T> T as(Object o, Class<T> cl) {

        if (o == null) return null;

        return cl.isInstance(o) ? cl.cast(o) : null;

    }

}

which when used in context feels a lot neater to me:

Bar bar = Cast.as(o, Bar.class);

Remember that in addition to solving problems, a software engineer needs to write code that is maintainable.  If your code doesn’t read well, it’s harder to maintain.  This gem hides what would otherwise be a series of warts in my code.

About the Author

Steve Hawley

Steve has been with Atalasoft since 2005. Not only is he responsible for the architecture and development of DotImage, he is one of the masterminds behind Bacon Day. Steve has over 20 years of experience with companies like Bell Communications Research, Adobe Systems, Newfire, Presto Technologies.

Follow on Twitter More Content by Steve Hawley
Previous Article
Atalasoft 10.4 SDKs Released
Atalasoft 10.4 SDKs Released

Update: Atalasoft version 10.4.1 was released in early 2014 and brings...

Next Article
Addressing Switching Forces in Toolkit Buying
Addressing Switching Forces in Toolkit Buying

Bob Moesta from The Rewired Group has a framework for thinking about how...

Try any of our Imaging SDKs free for 30 days with Full Support

Download Now