Page 1 of 1

Cool idea for object New initialization defaults

Posted: Thursday 9th March 2023 1:09pm
by BruceSteers
I just had a cool idea that i thought was worth sharing for when creating a new object instance.

I added this for my _new() method...
Public Sub _new(Optional Init As Collection)
  
  If Init Then 
    For Each sVar As Variant In Init
      Object.SetProperty(Me, Init.Key, sVar)
    Next
  Endif
  
End



the class in question is called ExternalTool.class and has these properties...
Property Text As String Use $sText
Property SaveBefore As Boolean Use $bSaveBefore
Property UseTerminal As Boolean Use $bUseTerm
Property Mode As Integer Use $bMode
Property CopyToClipboard As Boolean Use $bCopyToClip

New with that _new() method i am free to configure any and all properties upon initializing.

Like this..
Dim hExt As ExternalTool 
hExt = New ExternalTool(["SaveBefore": True, 
                         "CopyToClipboard": True, 
                         "Mode": ExternalTool.Insert])


That just struck me as very useful and worth sharing.
It saves adding lots of individual optional parameters to the _new() method

Re: Cool idea for object New initialization defaults

Posted: Tuesday 19th December 2023 8:30am
by thatbruce
I think I like this.
What happens if you give it a property that does not exist?
hExt = New ExternalTool(["SaveAfter": True, 
                         "CopyToClipboard": True, 
                         "Mode": ExternalTool.Insert])


The way I have always done this type of thing is via a static "Create" method. i.e.
Static Function Create(somedata as whatever) as ThisThing
(if that is in anyway clear?)

rgrds
b