Try/do pattern implementation in Java

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

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 (eg StringTryResult ).

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


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.


我不以任何方式认可这一点,但是在Java中使用“ out ”变量的一种非常低技术的方法是使用单元素数组:

String input = ...;
Date[] date = { null };
if (DateParser.tryParse(input, date)) {
  System.out.println(date[0]);
}
链接地址: http://www.djcxy.com/p/10914.html

上一篇: Netbeans SCSS文件自动完成就像CSS文件一样

下一篇: 在Java中尝试/做模式实现