samples/delegatingwriter/src/org/apidesign/delegatingwriter/AltBufferedWriter.java
changeset 210 acf2c31e22d4
parent 209 1c999569643b
     1.1 --- a/samples/delegatingwriter/src/org/apidesign/delegatingwriter/AltBufferedWriter.java	Sat Jun 14 10:04:51 2008 +0200
     1.2 +++ b/samples/delegatingwriter/src/org/apidesign/delegatingwriter/AltBufferedWriter.java	Sat Jun 14 10:04:53 2008 +0200
     1.3 @@ -68,7 +68,7 @@
     1.4          // BEGIN: writer.delegateout
     1.5          // efficient, yet dangerous delegation skipping methods unknown to 
     1.6          // subclasses that used version 1.4
     1.7 -        if (csq != null && csq.length() < 1024) {
     1.8 +        if (shouldBufferAsTheSequenceIsNotTooBig(csq)) {
     1.9              write(csq.toString());
    1.10          } else {
    1.11              flush();
    1.12 @@ -103,7 +103,7 @@
    1.13              throw new IOException(ex);
    1.14          }
    1.15          
    1.16 -        if (isOverriden || (csq != null && csq.length() < 1024)) {
    1.17 +        if (isOverriden || shouldBufferAsTheSequenceIsNotTooBig(csq)) {
    1.18              write(csq.toString());
    1.19          } else {
    1.20              flush();
    1.21 @@ -112,6 +112,28 @@
    1.22          return this;
    1.23          // END: writer.conditionally
    1.24      }
    1.25 +
    1.26 +    /** At the end the purpose of BufferedWriter is to buffer writes, this
    1.27 +     * method is here to decide when it is OK to prefer buffering and when 
    1.28 +     * it is better to delegate directly into the underlaying stream.
    1.29 +     * 
    1.30 +     * @param csq the seqence to evaluate
    1.31 +     * @return true if buffering from super class should be used
    1.32 +     */
    1.33 +    private static boolean shouldBufferAsTheSequenceIsNotTooBig(CharSequence csq) {
    1.34 +        if (csq == null) {
    1.35 +            return false;
    1.36 +        }
    1.37 +        // as buffers are usually bigger than 1024, it makes sense to 
    1.38 +        // pay the penalty of converting the sequence to string, but buffering
    1.39 +        // the write
    1.40 +        if (csq.length() < 1024) {
    1.41 +            return true;
    1.42 +        } else {
    1.43 +            // otherwise, just directly write down the char sequence
    1.44 +            return false;
    1.45 +        }
    1.46 +    }
    1.47      
    1.48      public enum Behaviour {
    1.49          THROW_EXCEPTION,