假设我有这样的课程:
public class FileMethods {
private static final Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
public static void doSomething(){
}
}
我将如何正确初始化文档?这当前会引发编译错误(未捕获的异常),因此是否可以在没有显式方法调用的情况下初始化 doc?
更好地在静态初始化方法中初始化您的文档。使用该方法的优点是您可以将初始化包装在try/catch
块中。
--- Edited because a long answer can't fit in commentary ---
I am going to quote from the c2.com pattern and anti-pattern discussion forums, where one can dive into the intricacies of object-oriented thinking, and mull over the strengths and weaknesses of different approaches.
It is a fundamental breach of encapsulation to give functions more access to private state than they require. Utility methods that are left as members of a class are often granted more access than they require, making it harder to identify and enforce design invariants. If a method's functionality can be expressed in terms of a class's public interface, then writing it as a non-member function increases overall encapsulation.
A class with all static methods eventually has to bother itself with all of the data and items within the classes passed to it. This causes a number of issues.
The list goes on, but if you feel that your situation merits special consideration, then use static methods.
---Original post follows ---
A class that has all static members and methods is very problematic. Why not create an instance, like so
public class FileMethods {
private final Document doc;
public FileMethods() {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
public void doSomething() {
doc.checkSomething();
doc.doSomething();
doc.doSomethingElse();
}
}
and there it is. You will now have the ability to work on two documents at the same time. You also gain the ability to possibly test your FileMethods class in a unit testing framework (without some really backward code).
As far as the exception.
try {
doc = ...;
} catch (SomeCompilerException e) {
e.printStackTrace();
}
is a good start. Even better, if you cannot handle the exception in that block of code...
public FileMethods() throws SomeCompilerException {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
and handle it in the block of code where it makes sense.
try {
FileMethods methods = new FileMethods();
methods.doSomething();
} catch (SomeCompilerException e) {
System.out.println("Not possible to make a document right now due to " + e);
}