9 Library methods

 

This chapter covers

  • Problems with StringBuilder constructor invocation
  • Stream API misuse patterns
  • getClass() method pitfalls
  • String-to-boolean conversion problems
  • Common mistakes in date and time formatting
  • Non-atomic call sequences

In previous chapters, we discussed the pitfalls of using library methods related to numbers, strings, collections, and maps. These are most of the essential parts of the standard library; however, there are other library methods that could be misused but did not fit the previous chapters. We consider these in this chapter.

9.1 Mistake 82: Passing char to StringBuilder constructor

If you use StringBuilder, you can either provide the initial content or create it empty and append the initial content later:

StringBuilder sb = new StringBuilder("Hello");

The preceding code line is equivalent to

StringBuilder sb = new StringBuilder();
sb.append("Hello");

Well, it’s not strictly equivalent, as the constructor parameter affects the initial size of the inner buffer, so the performance could be slightly different. Still, behaviorally, it’s the same, and many people assume one can safely merge the first append() into the constructor to save the keystrokes. This may go badly if you start the append-chain with a char:

StringBuilder sb = new StringBuilder('[');    #1
sb.append(value);
sb.append(']');

9.2 Mistake 83: Producing side effects in a Stream API chain

9.3 Mistake 84: Consuming the stream twice

9.4 Mistake 85: Using null values in a stream where it’s not allowed

9.5 Mistake 86: Violating the contract of Stream API operations

9.6 Mistake 87: Using getClass() instead of instanceof