When we create an instance of a class, we often need to do some initialization.  Constructors and initializers achieve this goal.  These are two different ways to get our data into an instance and are an essential part of our design.  In this episode, we examine the design decisions we need to make as we decide how to use these common methods.

Constructors And Initializers – The Distinction

A constructor and an initializer method can be thought of in very similar ways.  However, there is one particular trait that differs between the two approaches.  A constructor returns an instance of a class, whereas an initializer sets values on an instance.  This may seem to be a minor difference.  It is not.  There are situations where we need to create many instances of a class, and a “fat” constructor can lead to performance issues.  The creation of an instance is an important operation.  Thus, it is best to complete it in as short a time as possible.

That is where an initializer comes in.  We can create an instance quickly and then take our time populating that instance (i.e., initializing it).

A No-Args Constructor

Many languages include a default constructor for classes that takes zero arguments.  This provides a quick way to get an instance.  I personally find these important and highly useful in extending classes.  The exception to providing a default constructor is when you need to provide limited instances or some level of instance management.

Adding Parameters

Once you start adding parameters to your instance creation, you should consider an initializer.  That provides a cleaner way to create an instance and then populate it.  You also give the developer the ability to “lazy load” data, for that instance.  That is an important option in large systems and large classes.  A good initialization routine also provides an opportunity for a mirroring cleanup method that makes it easy for a developer to control resource usage within classes.

A few core parameters for an instance may be convenient, but once that list gets long, it can slow the process.  It is better first to get a valid instance and then do something with it.

https://rb-sns.com

Rob Broadhead

Rob is a founder of, and frequent contributor to, Develpreneur. This includes the Building Better Developers podcast. He is also a longtime student of technology as a developer, designer, and manager of software solutions. Rob is a founder and principle of RB Consulting and has managed to author a book about his family experiences. In his free time, he stays busy raising five children (although a few have grown into adults). When he has a chance to breathe, he is on the ice playing hockey to relax.

Leave a Reply