Class factory

tiredofit

Well-known Member
Joined
Apr 11, 2013
Messages
1,924
Office Version
  1. 365
  2. 2019
Platform
  1. Windows
This is taken from the following article:

Code:
https://datapluscode.com/general/no-constructor-no-problem/

It talks about class factories:

Code:
Option Explicit

Dim sColour As String

Public Property Let Colour(ByVal Value As String)

    sColour = Value

End Property

Public Property Get Colour() As String

    Colour = sColour

End Property

Private Sub Class_Initialize()

    sColour = "Red"

End Sub

Public Sub PrintColour()

    Debug.Print "The Car Colour is " & sColour

End Sub

When an object is created using this class, the class internally sets the colour of the car to be red when created. If we wanted to create a Car object which was blue, we would have to set its colour property to blue after creation:

My question is: why would you want to create a car object and set its colour property to be blue BEFORE creation?
 

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"
One reason to set default properties in the Initialize event would be to avoid situations where a missing property would mess things up.
In your example, one can use class Cars and not worry that the color is "".

Another reason is if there are restrictions on the values that a property might have. Class Building might have a Height property, by setting a deault height (and by putting validation into the Property Let routine) one can confidently assume that .Height is never non-zero.

Setting up defaults is more often done when the property is an object, to avoid having to execute a If myObjectProperty Is Nothing in the code for the class.
 
Upvote 0

Forum statistics

Threads
1,223,889
Messages
6,175,226
Members
452,620
Latest member
dsubash

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top