Cool idea for object New initialization defaults

Post your Gambas programming questions here.
Post Reply
User avatar
BruceSteers
Posts: 1505
Joined: Thursday 23rd July 2020 5:20pm
Location: Isle of Wight
Contact:

Cool idea for object New initialization defaults

Post 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
If at first you don't succeed , try doing something differently.
BruceS
User avatar
thatbruce
Posts: 159
Joined: Saturday 4th September 2021 11:29pm

Re: Cool idea for object New initialization defaults

Post 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
Have you ever noticed that software is never advertised using the adjective "spreadable".
Post Reply