After seeing 1000 ctors

I heard it a lot of times. When I was learning Java, a flash definition about constructor methods faded away in the classroom. A “silly” definition that nobody seemed to remember a bunch of years later.

Sometimes the things that are easily forgotten are the most basic principles. We take them as a fact and we rarely reevaluate them.

One of the basics in OOP is the role of a constructor method:

A constructor method is a special method that contains ONLY the required initializations for the instance to be created in a valid state, ready to be used.

Said this, any constructor what invokes complex methods, services to retrieve data, contains lots of lines of code, or even loops, IS A MISTAKE and needs to be fixed.

A constructor has to be minimum! The instance should be created just in time and any complex initialization should be the responsibility of any other method of the instance.

This answer on Stack Overflow is very good. Be sure to read it 🙂 and keep you ctors clean!

http://stackoverflow.com/questions/1183531/how-much-work-should-the-constructor-for-an-html-parsing-class-do

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s