0

I am implementing a software and the user can, before starting a task, decide if he wants to create a log file for this task.

  • A csv-writer is created if logging is enabled
  • Throughout the code there are several lines which use the csv-writer to write into the log
  • The csv-writer is disposed

There are now three ways how to check if logging is enabled and I don't like any of them:

  1. Every time csv-writer is created or accessed put a 'if (isLogging)' check before it (a ton of calls)
  2. Create a csv-writer interface and make calls to the interface. Create another EmptyCsvWriter that implements the interface and has empty methods and initialize this one when isLogging is false (seems wrong to create a 'fake' null object)
  3. Create the csv-writer and pass isLogging. Check inside csv-writer if isLogging is enabled on every method call (why even create the csv-writer object in the first place - seems wrong, too)
Thypari
  • 801
  • 1
  • 6
  • 22
  • 1
    The second option is the most elegant one. It amkes all the code simpler, and easier to test. But it's not as efficient as the first one if you need to compute the inputs taken by the csv writer: you would produce the outputs for nothing if the writer discard them. The bonus, on the other hand, is that you would detect bugs in this input-producing code even if you use an noop writer. – JB Nizet Nov 20 '17 at 11:51
  • Thank you. Do you want to post it as answer, so I can checkmark it? – Thypari Nov 20 '17 at 13:54

1 Answers1

2

The second option is the most elegant one. It makes all the code simpler, and easier to test.

But it's not as efficient as the first one if you need to compute the inputs taken by the csv writer: you would produce the outputs for nothing if the writer discard them. The bonus, on the other hand, is that you would detect bugs in this input-producing code even if you use an noop writer.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255