Context: .NET, C#, but the question is about OOP in general.
When I write a class that should act as a “service”, like a socket listener, or a timer, I see two approaches when it comes to coding it:
-
Create a constructor, and inside the constructor, immediately start the background task. For instance:
public class MyTimer { private readonly TimeSpan interval; public MyTimer(TimeSpan interval) { this.interval = interval; StartTicking(); } private void StartTicking() { // do the ticking logic } } -
Create a constructor that accepts the class’ settings, and add an explicit method for starting up:
public class MyTimer { private readonly TimeSpan interval; public MyTimer(TimeSpan interval) { this.interval = interval; } public void StartTicking() { // do the ticking logic } }
I tend to think that the second approach is better:
A. The constructor is used only for creating a valid instance, keeping it minimal and clean.
B. The developer who actually uses my class is less astonished.
C. The hardware resources are not overused, since the “service” class does not immediately use them.
What do you think? Is it only a matter of coding style, or is it more than that?
Don’t start running in your constructor.