简体   繁体   中英

Don't repeat checks on event methods (Bukkit/Spigot)

I was reviewing my codebase for a major project of mine and i've noticed that there are over 150 event handlers that all run essentially the same check:

        if (!(event.getDamager() instanceof Player))
            return;
        if (!(event.getEntity() instanceof Player))
            return;

        Player player = (Player) event.getDamager();

        Player victim = (Player) event.getEntity();

        if(!AntigriefManager.canInjure(player, victim)) return;

        if (!EnchantChecks.mainhand(player, this)) return;

My question is, can would there be a good way of abstracting this away?

Is it possible to pass those player and victim values to multiple EntityDamageByEntityEvent handlers instead of writing them above each one?

Thanks!

Make use of EventHandler , specifically priority and ignoreCancelled .

Right now you have this:

@EventHandler
public void onMyEvent(SomeEvent event) {
    //a) A bunch of precheck code
    //b) The actual code you want to run, in several different code bodies
}

What you will end up doing is splitting these tasks into two different listeners; one will handle the checks, the other will run whatever it is responsible for. For this, our checks will run on EventPriority.LOWEST , because those are run before any other priority. On top of that, if the event is cancelled, we will use EventHandler#ignoreCancelled to indicate our code should not be run:

@EventHandler(priority = EventPriority.LOWEST)
public void onMyPrechecks(SomeEvent event) {
    //a) A bunch of precheck code, for example:
    if (!AntigriefManager.canInjure(player, victim)) {
        //notice we cancel, instead of returning from a method
        event.setCancelled(true);
    }
}

//Elsewheres, in another class probably:
//priority should never go lower than LOW
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onMyEvent(SomeEvent event) {
    //b) The actual code you want to run, e.g.:
    event.getPlayer().sendMessage("running event!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM