oop - Should a newly created class "start" itself during construction? -
context: .net, c#, question oop in general.
when write class should act "service", socket listener, or timer, see 2 approaches when comes coding it:
create constructor, , inside constructor, start background task. instance:
public class mytimer { private readonly timespan interval; public mytimer(timespan interval) { this.interval = interval; startticking(); } private void startticking() { // ticking logic } }
create constructor accepts class' settings, , add explicit method starting up:
public class mytimer { private readonly timespan interval; public mytimer(timespan interval) { this.interval = interval; } public void startticking() { // ticking logic } }
i tend think second approach better:
a. constructor used creating valid instance, keeping minimal , clean.
b. developer uses class less astonished.
c. hardware resources not overused, since "service" class not use them.
what think? matter of coding style, or more that?
don't start running in constructor.
- users of api won't expect that, , makes class harder use
- from exception handling standpoint, want able report error happens when constructing object, separately error happens during execution.
- it prevents sharing instances of object, if ever wanted static factory singleton pattern.
- i second striplingwarrior's point there many reasons, dependency injection, object creation needs happen first other class can run later.
Comments
Post a Comment