-1

假设我有这样的课程:

public class FileMethods {

private static final Document doc=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

public static void doSomething(){
}

}

我将如何正确初始化文档?这当前会引发编译错误(未捕获的异常),因此是否可以在没有显式方法调用的情况下初始化 doc?

4

2 回答 2

7

更好地在静态初始化方法中初始化您的文档。使用该方法的优点是您可以将初始化包装在try/catch块中。

于 2013-08-26T00:58:58.943 回答
1

--- 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.

  1. It inverts encapsulation, as behavior becomes permanently external to the classes. For example, the "doSomething" in the example below does not belong to any class instance. Inverted encapsulation == classes that act more like structs, lacking critical behavior required to solve the problem.
  2. It complicates unit testing. I could try to whip together a quick example, but this covers it far better than I would be able to do so quickly.
  3. It makes your code hard to maintain in ways that are easy to foresee will need maintenance. Ever consider that you might need a second document? Have fun cut-and-pasting (a bug injection technique), or converting your stuff to instances (a fun hunt through the code) so you can have a base class and subclasses for the differences. Starting with instances, you would only need to mark the instance class abstract, create two subclass files, and move one method into the "was default" subclass, writing the method for the other subclass. No hunting through the codebase == win.
  4. All static classes are very hard to unload. No memory reduction is possible when not using them, without some very exotic class loading.
  5. All static classes are very hard to make performant. No ability to create a class per thread, or class per parallel task. No guarantees that between method calls that you can prevent other threads from calling methods. With instances, you can create thread-private instances.

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);
 }
于 2013-08-26T01:06:39.680 回答