Try/do pattern implementation in Java
Asked Answered
V

2

8

I'm a fan of the try/do (or trier/doer) pattern, which is best implemented in C# using out parameters, e.g.:

DateTime date;
if (DateTime.TryParse("2012-06-18", out date))
{
    //Do something with date
}

I'm currently working on a Java 1.5 project, for which I'm implementing the try/do pattern using a new class called TryResult which is returned from any methods which implement the try/do pattern:

public class TryResult<ResultType> {

    private boolean mSuccess = false;
    private ResultType mResult = null;

    public TryResult(boolean success, ResultType result) {
        super();
        this.mSuccess = success;
        this.mResult = result;
    }

    public boolean isSuccess() {
        return mSuccess;
    }

    public ResultType getResult() {
        return mResult;
    }

}

This is working well, but I will be porting this code to a different platform which uses J2ME, and therefore generics aren't available.

My current options are to either remove the generics from the TryResult class above and using plain old Object and casting, or make a new class for the types I will end up using (e.g. StringTryResult).

Is there a better way to implement this pattern on J2ME/Java 1.3?

Vituperate answered 18/6, 2012 at 14:46 Comment(2)
With Object and casting.Tammitammie
@lukas Thanks for your comment. I guess it wasn't clear, but that's what I meant by 'removing generics'. I'm hoping that there's a better solution though.Vituperate
E
4

What you are trying to implement is called a Maybe monad in functional languages.

There are experiments to do this in java, see here and here.

The problem is, Java's type system is unfortunately not advanced enough to support this on a large scale.. Also, the standard libraries do not support anything like that, which reduces the use of such a construct to your own code only :(

See Scala and Clojure for languages that support this.

As far as Java ME goes, I'd think twice about implementing special types just for the sake of this. It is a nice in idea theory, however, it would make things just more difficult, eg. duplicating all types in your whole app.

Erlking answered 18/6, 2012 at 16:38 Comment(1)
Thanks for your answer, definitely some interesting reading here. Regarding implementing special types, I expect to concede to practicality and use a special type for the most common result types (e.g. StringTryResult will be commonly used) and use Object and casting for the other cases.Vituperate
S
0

I don't endorse this an any way, but a really low-tech way to do "out" variables in Java is to use single element arrays:

String input = ...;
Date[] date = { null };
if (DateParser.tryParse(input, date)) {
  System.out.println(date[0]);
}
Simpson answered 18/6, 2012 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.