什么是“静态滥用”,如何避免?

时间:2019-07-12 14:58:43

标签: java static minecraft

在线用户告诉我,我的代码是“静态滥用”。使用许多静态函数是否有问题,如果是的话,如何避免使用它们?

我目前正在开发一个Minecraft插件,该插件在游戏中添加了多个魔术棒(具有特殊功能的物品)。我有很多实用程序类,例如下面的类。它们中的大多数包含对多个棒有用的静态方法(每个棒是基础棒的扩展)。我使用这么多静态功能的原因是因为我不会一直创建新的对象/对实用程序类的引用。所以我要问的是:这是个坏习惯吗?使用大量静态函数有什么弊端吗?如果我不想一直创建新对象,该如何一次访问这些函数,而不必担心实例是否占用内存空间之类的事情?

感谢您的帮助!

如果您想查看完整的源代码,可以这样做here

这是我在其他代码中经常使用的实用工具类的示例:

package com.Wands;

import java.util.Random;

import org.bukkit.Location;
import org.bukkit.util.Vector;

public class LocationHelper {

    public static Location offsetLocation(Location startLocation, Vector offset) {

        // Add the offset vector to the start location
        return new Location(
                startLocation.getWorld(),
                startLocation.getX() + offset.getX(),
                startLocation.getY() + offset.getY(),
                startLocation.getZ() + offset.getZ());
    }

    /*
     * This function will move a location on the Y axis to find the nearest spot
     * where a player can stand
     */
    public static Location validateLocation(Location location) {

        // Create a new location to return later
        Location validatedLocation = location;

        // While block at location is solid
        while (validatedLocation.getBlock().getType().isSolid()) {

            // Move location up one
            validatedLocation.setY(validatedLocation.getY() + 1);
        }

        // While block under location is not solid
        while (!offsetLocation(validatedLocation, new Vector(0, -1, 0)).getBlock().getType().isSolid()) {

            // Move location down one
            validatedLocation.setY(validatedLocation.getY() - 1);
        }

        // Return validated location
        return validatedLocation;
    }

    public static Location getRandomNearbyPosition(Location startLocation, int range) {

        // Create a random number generator
        Random rdm = new Random();

        // Create a new location to return later
        Location randomLocation = startLocation;
        Location validatedRandomLocation = null;

        while (validatedRandomLocation == null
                || validatedRandomLocation.distance(startLocation) > range * 2
                || validatedRandomLocation.getBlock().getType().isSolid()) {

            // Safe the random offset to a vector
            Vector offset = new Vector(
                    rdm.nextInt(range * 2) - range,
                    rdm.nextInt(range * 2) - range,
                    rdm.nextInt(range * 2) - range);

            // Add offset to random location
            randomLocation = offsetLocation(startLocation, offset);

            // Validate random location
            validatedRandomLocation = validateLocation(randomLocation);
        }

        // Return random validated location
        return validatedRandomLocation;
    }

}

0 个答案:

没有答案