Skip to main content
7 events
when toggle format what by license comment
Jun 27, 2018 at 20:51 comment added amon @Sveta as usual, this depends on your exact requirements. A tryReload() method is certainly the most elegant approach if all you want to do is perform a reload, or ignore the action if it's not supported. In contrast, my suggested design also allows us to query whether the action is supported without immediately performing it. This is more general, but you're right: this generality might be unneeded. You could alternatively add a canReload() check in addition to tryReload(), but then you have to maintain two methods together and are duplicating information.
Jun 26, 2018 at 15:52 comment added user306112 @amon, won't be better if getReloadAction() returned true or false? Or even better, have a method in Weapon called tryReload() if the weapon is reloadable, based on a argument passed into the constructor, then the method will reload and return true, false if it can't. Much like this answer with the tryAdd() softwareengineering.stackexchange.com/a/372143/306112
Jun 26, 2018 at 5:55 comment added amon …But I do understand that returning null can be problematic, especially as Java doesn't support elegant C++-isms like if (auto reload = w.reload_action()) (*reload)();. It then may be desirable to make the interface more explicit by returning an Optional<> value as suggested in my answer. The Java equivalent then becomes something like w.getReloadAction().ifPresent(reload -> reload.reload());. I think in C# this discussion would be moot because we have the safe navigation operator, so returning null would be appropriate in that language?
Jun 26, 2018 at 5:53 comment added amon @RubberDuck I considered that while writing, but consciously decided against it. One use case is to run the action if it is present; here a null object like () -> {} would help. But it can also be desirable to merely ask if the action is available. A null object pattern complicates that use case: I'd need a singleton null object marker that can be checked with identity, or a special null object class that I can check with instanceof, or the action object needs an additional method to ask if it is really present (which complicates both a @FunctionalInterface and client code). …
Jun 26, 2018 at 3:53 comment added Hangman4358 I agree, I like the idea but if you are declaring a functional interface I would also declare a no-op implementation to avoid null checks.
Jun 25, 2018 at 23:19 comment added RubberDuck While I like your solution, I’m compelled to downvote because you return null instead of a no op action. It unnecessarily complicated client code.
Jun 25, 2018 at 22:02 history answered amon CC BY-SA 4.0