Java – Design of objects and static methods

As shown in the figure below, there are two simple ways to make the streaming copier (Introducing Apache commons or similar software) Which one should I go and why?

public class StreamCopier {
private int bufferSize;

public StreamCopier() {
    this(4096);
}

public StreamCopier(int bufferSize) {
    this.bufferSize = bufferSize;
}

public long copy(InputStream in,OutputStream out ) throws IOException{
    byte[] buffer = new byte[bufferSize];
    int bytesRead;
    long totalBytes = 0;
    while((bytesRead= in.read(buffer)) != -1) {
        out.write(buffer,bytesRead);
        totalBytes += bytesRead;
    }

    return totalBytes;
}
}

VS

public class StreamCopier {

 public static long copy(InputStream in,OutputStream out)
     throws IOException {
     return this.copy(in,out,4096);
 }

 public static long copy(InputStream in,OutputStream out,int bufferSize)
     throws IOException {
     byte[] buffer = new byte[bufferSize];
     int bytesRead;
     long totalBytes = 0;
     while ((bytesRead= in.read(buffer)) != -1) {
         out.write(buffer,bytesRead);
         totalBytes += bytesRead;
     }

     return totalBytes;
}
}

Solution

I will use a non static (instance) version and provide it to consumers as an explicit dependency on setters:

Mocking it for unit testing is trivial, so consumer testing is not suitable for implementation; The exchange function is very simple. For example, use subclasses; > The dependency injection system works well

edit

In response to "useful!" How does this work when commenting on "how does this help ridicule":

class ThingThatUsesStreamCopier {

    // our copier instance. set in constructor,but might equally use
    // a setter for this:
    private StreamCopier copier;

    public ThingThatUsesStreamCopier(StreamCopier copier) {
        this.copier = copier;
    }

    public void makeCopy(Stream in,Stream out) {
        // probably something a little less trivial...
        copier.copy(in,out);
    }
}

When I test thingthatusesstreamcopier, I can create a mock object version of streamcopier and instantiate thingthatusesstreamcopier using this simulation

By doing so, I have complete control over my simulation behavior, so my tests are decoupled from any actual implementation of streamcopier I just test consumers, not consumers plus consumption

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>