Void value as return parameter

后端 未结 8 2464
夕颜
夕颜 2021-02-19 18:50

I have this interface:

public interface Command {
    T execute(String... args);
}

it works fine for most uses. But when I try to mode

8条回答
  •  清歌不尽
    2021-02-19 19:14

    Keep the interface as it is: this is why Void is in the Standard Library. Just as long as whatever is calling the Command expects nulls to come back out.

    And yes, null is the only value you can return for Void.

    Update 2017

    For the last several years I have avoided Void as return types except where reflection is concerned. I have used a different pattern which I think is more explicit and avoids nulls. That is, I have a success type, which I call Ok which is returned for all commands like the OP's. This has worked very well for my team and has also propagated into other teams' use.

    public enum Ok { OK; }
    
    public class SideEffectCommand implements Command {
        @Override
        public Ok execute(String... args) {
            ...
            return Ok.OK; // I typically static import Ok.OK;
    }
    

提交回复
热议问题