Menu
Sign In Search Podcasts Charts People & Topics Add Podcast API Pricing
Podcast Image

Develpreneur: Become a Better Developer and Entrepreneur

Constructors And Initializers In Object-Oriented Design

31 Mar 2021

Description

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.

Audio
Featured in this Episode

No persons identified in this episode.

Transcription

This episode hasn't been transcribed yet

Help us prioritize this episode for transcription by upvoting it.

0 upvotes
🗳️ Sign in to Upvote

Popular episodes get transcribed faster

Comments

There are no comments yet.

Please log in to write the first comment.