views:

209

answers:

3

Hi,

I should probably know things like this by now - but for some reason this one passed me by!

I have an object that I instantiate - it's quite nifty as it also extends a superclass and does some stuff in the contructor - in fact all the vital parameters and method calls are handled in the constructor.

After this I never call the object again to do something - I don't pass it to any other objects either - after it's instantiated it does it stuff and all is good. I am just worried that this is a kind of bad code smell?

What do you guys think?

+5  A: 

Yes, doing significant work in the constructor is usually a bad idea.

Could you do this through a static method instead? The static method could create an instance of the superclass and then do whatever it needs to. The only problem with this approach would be if the superclass called virtual methods during its constructor, but that's a code smell in itself...

Jon Skeet
+2  A: 

There should a purpose for the object to exist. Constructor is only a tool for preparing the object so it can work as needed after creation. If you don't use the object, you don't need to create it either.

Creation of unnecessary objects consumes memory and also makes garbage collector do more work, so you should consider rewriting code (possibly with a static method as it has already been suggested).

Malcolm
+3  A: 

It may be a smell from the superclass, not the subclass.

Why do you need to do that? Is there functionality in the superclass that is publicly accessible only through the constructor? If so then you probably do need to create an instance to access that functionality. But it may be better to hide that behaviour behind a normal method rather than a subclass constructor.

But that's still not as good as fixing the superclass.

finnw