Is it an acceptable practice to initialize physical/external resources from a constructor when the resource is needed for the object to do it's work?
For instance, let's say I wanted to create an object that proxies a durable message queue and that the message queue is a physical database table.
Would that make sense to create an idempotent constructor which physically create the table if it doesn't exist yet?
E.g.
IMessageQueue queue = new SQLTableMessageQueue('table_name', dataSource);
Perhaps a static factory method would be more appropriate? In that case, the table creation would occur in the factory method and the constructor would be free of such behavior.
IMessageQueue queue = SQLTableMessageQueue.create('table_name', dataSource);
I'm not too sure what would be an appropriate approach? Another idea I had was to use the Repository Pattern.
Constructors must usually be side-effect free
- Impossible, unless you're constructing an empty object. Where did you hear that? – Robert Harvey Jan 21 '15 at 06:41Timer
you wouldn't start it right away when the constructor is called, but even that point is not very important for the question. – plalx Jan 21 '15 at 13:49this
to another thread before the constructor has finished. – Doval Jan 21 '15 at 14:06