开发者

Effective way to handle null in visitor pattern

开发者 https://www.devze.com 2023-02-13 08:26 出处:网络
Imagine 开发者_开发知识库you have a collection of objets and you use the Visitor pattern - how would you handle null retrieved from the collection most elegantly?Either your problem requires some spec

Imagine 开发者_开发知识库you have a collection of objets and you use the Visitor pattern - how would you handle null retrieved from the collection most elegantly?


Either your problem requires some special type of visitable objects or you're trying to impose too many responsibilities on your visitor pattern. If you really have meaningful object which must not be visited try Null Object pattern.

public class NullElement implements Element {

    public void accept(ElementVisitor visitor) {
        // noop
    }
}


I can't see any way other than putting an if (element != null) element.accept(visitor);

If you're using guava or something, you could of course do a filter but it seems like an overkill.

0

精彩评论

暂无评论...
验证码 换一张
取 消