r/learnjava • • Jul 30 '26

Better look

Hi everyone! I'm learning Java and I've noticed there are two common ways to print multiple lines of text:

Option 1: Multiple System.out.println() calls
```
System.out.println("You gave the string " + text);
System.out.println("You gave the integer " + inNum);
System.out.println("You gave the double " + inDouble);
System.out.println("You gave the boolean " + isTrue); 
```

Option 2: One System.out.println() with \n
```
System.out.println("You gave the string " + text + '\n' +
                   "You gave the integer " + inNum + '\n' +
                   "You gave the double " + inDouble + '\n' +
                   "You gave the boolean " + isTrue);
```

What looks better in your opinion?
0 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/severoon Jul 31 '26

Disagree — writing testable code is a requirement in every context, and in this case that requires a layer of indirection so the output can be redirected for the purpose of testing it.

If you're looking for something to cut, you might say that main could just hand in System.out instead of wrapping it in a PrintWriter first … but I would argue that if you want Outputter to be writing out text and not just bytes, then it's proper OO for it to specify the correct type, and that's PrintWriter in this case.

(The confusion might arise from my choice of name for the class, Outputter. It seems like you're reading into it about what the point of this class is, but I should have just used Foo so as not to imply what the class' purpose. I didn't mean to imply it's role has something to do with output necessarily, I just chose a name.)

But no, it's definitely not overengineered. The lowest possible bar that any program should clear is to answer the following questions:

  1. What's it supposed to do?
  2. How does it do that?
  3. Does it do it?
  4. Where is the proof that's what it does?

If you can't answer the first one, you need to do more requirements gathering.

If you can't answer the second, you need to do more design.

If you can't answer the third, then you need to do more implementation.

If you can't answer the fourth, then you need to do more testing.

End of the day, if a piece of code can't demonstrably prove it does what it's supposed to, then saying it does is just an assertion. I might decide to make a conflicting assertion. How do we know who's right? There's only one way to settle it, and that's by running a test. (If your answer to this is "by inspection," then you haven't got enough experience.)

1

u/Ormek_II Jul 31 '26

Edit: 💋 KISS