简体   繁体   English

您是否认为我在滥用静电?

[英]Do you think I'm abusing of statics?

I'm new in Java programming and I think I have clear what are the objects and how to work with them. 我是Java编程的新手,我想我很清楚这些对象是什么以及如何使用它们。

However, now that I'm writing a program I have noticed that I have used a lot the 'static' keyword for methods, and I'm doubting if it is because it is really neccesary and logical or if it is because I have not internalized in my mind the OO concepts. 但是,由于我正在编写程序,所以我注意到我对方法使用了很多“静态”关键字,并且我怀疑这是否是因为它确实是必要的和合乎逻辑的,还是因为我没有在我看来,OO概念是内部化的。

To be more specific, my program should read from a txt file and put each line in an ArrayList, this is my code: 更具体地说,我的程序应从txt文件读取并将每一行放入ArrayList中,这是我的代码:

public class FileBody {

    private static final String SEPARATOR = ";";
    private static String headerField1 = "regex";
    private static String headerField2 = "origin";
    private static String headerField3 = "destination";
    private static final String HEADER = headerField1 + SEPARATOR + headerField2
            + SEPARATOR + headerField3 + SEPARATOR;

    // Getters & setters

    public static String getHeader() {
        return HEADER;
    }

    public static String getHeaderField1() {
        return headerField1;
    }

    public static void setHeaderField1(String headerField1) {
        FileBody.headerField1 = headerField1;
    }

    public static String getHeaderField2() {
        return headerField2;
    }

    public static void setHeaderField2(String headerField2) {
        FileBody.headerField2 = headerField2;
    }

    public static String getHeaderField3() {
        return headerField3;
    }

    public static void setHeaderField3(String headerField3) {
        FileBody.headerField3 = headerField3;
    }

    // End getters & setters

    public static File createFileIfNotExists(String path) throws IOException {
        File file = new File(path);
        if (file.createNewFile());
        return file;
    }

    public static File getFile(String path) throws IOException {
        File file = createFileIfNotExists(path);
        return file;
    }

    public static boolean isEmpty(File file) throws Exception {
        FileReader fileReader = new FileReader(file);
        if (fileReader.read() != -1) {
            fileReader.close();
            return false;
        } else {
            fileReader.close();
            return true;
        }
    }

    public static void writeHeaderToEmptyFile(File file) throws Exception {
        if (isEmpty(file)) {
            BufferedWriter bufferedWriter = new BufferedWriter(
                    new FileWriter(file, false));
            bufferedWriter.write(HEADER);
            bufferedWriter.close();
        } else {
            return;
        }
    }

    public static ArrayList<String> getLines(File file) throws Exception {
        ArrayList<String> lines = new ArrayList<>();
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        while (bufferedReader.ready()) {
            lines.add(bufferedReader.readLine());
        }
        bufferedReader.close();
        return lines;
    }

}

Do you think I could have done it better with objects? 您认为我可以用对象做得更好吗? If the answer is yes, could you give me the guidelines to do that? 如果答案是肯定的,您能给我指导方针吗?

Thank you very much for your help. 非常感谢您的帮助。

Having mutable static fields should be avoided where-ever possible. 应尽可能避免具有可变的静态字段。 In particular, what you have won't work because they are only initalised once. 尤其是,您只能使用一次,因此无法使用。

// only run once even if these fields are changed.
private static final String HEADER = headerField1 + SEPARATOR + headerField2
        + SEPARATOR + headerField3 + SEPARATOR;

Most likely what you want is 您最想要的是

public static String getHeader() {
    return headerField1 + SEPARATOR + headerField2
        + SEPARATOR + headerField3 + SEPARATOR;
}

The only field which should be static is SEPARATOR as this is a constant. 唯一应该为static字段是SEPARATOR因为这是一个常数。 I would try to make all the other fields into non-static fields (and their getter/setters) 我会尝试将所有其他字段都设为非静态字段(及其获取/设置程序)

You have some utility/helper methods at the end of the class. 在课程的最后,您有一些实用程序/帮助程序方法。 I would put these in another class as they don't appear to be related. 我将它们放在另一个类中,因为它们似乎无关。 ie have a clear utility class for these methods instead. 也就是说,请为这些方法使用明确的实用程序类。 eg 例如

class FileBody {
    public void writeHeaderToEmptyFile(File file) throws IOException {
        if (!FileUtils.isEmpty(file)) return
        try (Writer w = new FileWriter(file)) {
            w.write(getHeader());
        }
    }
}

class enum FileUtils {
    /* no instances */ ;

    // TODO replace all callers with new File(x);
    public static File getFile(String filename) { 
         return new File(filename);
    }

    public static boolean isEmpty(File file) {
        return file.length() > 0;
    }

    public static List<String> getLines(File file) throws Exception {
        return Files.readAllLines(Paths.get(file.getAbsolutePath()));
    }
}

Let's have a quick look at what you did right and wrong: 让我们快速看一下您做对与错的事情:

Right: 对:

You kept your fields private and provided public methods to access that. 您将字段设为私有,并提供了访问该字段的公共方法。 +1 for that. +1。

Wrong: 错误:

  1. You are keeping static fields private. 您将静态字段设为私有。 Private fields can be accessed only from within the class (except in case of reflection: let's not go into that right now). 只能从类内部访问私有字段(除非发生反射,除非现在就不要进入该字段)。 So there is no added advantage you are gaining from marking it as static. 因此,将其标记为静态不会带来任何额外的优势。 Instead it will be an overhead in the memory (small in this case but still) 相反,它将是内存的开销(在这种情况下较小,但仍然)

  2. If at all you want them as static, you should have not left them immutable. 如果您完全希望它们是静态的,则不应使它们保持不变。 static fields are class level fields and not marking them as final, you are allowing different objects of your class to modify them which may lead to data corruption. 静态字段是类级别的字段,并且未将它们标记为final,因此您允许类的不同对象对其进行修改,这可能导致数据损坏。

  3. Right now you are using Strings which have a separate memory management mechanism in Java. 现在,您正在使用在Java中具有单独的内存管理机制的字符串。 But if you use the same code with object references(marking object references as static), then you would be keeping your objects alive in memory for a long time unnecessarily which will be a huge strain on memory. 但是,如果对对象引用使用相同的代码(将对象引用标记为静态),则不必要地使对象在内存中存活很长时间,这将对内存造成巨大压力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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