Making a constructor sometimes illegal to call

Suppose you write a control subclass that you want people to be able to add to a window layout OR be able to create on the fly. But you want to make sure that when an instance is constructed in code it MUST have a parameterized constructor. However, in order to put an instance on a layout by drag and drop it has to have a no parameter constructor. These two design goals seem very much at odds.

So how do you make this happen ?

Such a control might be like :

Class myControl
  Inherits Canvas

  Sub Constructor()
  End Sub

  Sub Constructor(name as string)
     self.mName = name
  End Sub

  Computed Property MyName as string
    Function Getter() as string
       return mName
    End Function
    Sub Getter(value as string)
       mName = value
    End Sub
   
  protected mName as string
end class

We’ll assume that MyName has been exposed as part of the Inspector Behaviour.

But the class definition above would definitely allow you to write code that called either constructor. How to make it so the no parameter constructor can only be used by instances on a layout that, as part of initializing the layout, basically does the following

dim c as new myControl
c.MyName = "whatever value the user set in the inspector"

But there is a trick you can use to know how you have been called. An exception exposes the call stack to you and you can examine that to know if there is a window being initialized that has resulted in your no parameter constructor being called. And so you can make it so a window being initialized can use the no parameter version. In fact to make it so your control can be placed on a layout in the IDE designer it MUST have a no parameter constructor if it has any constructors.

If we make that no parameter constructor read as follows we can make this raise an exception when used improperly outside of a window being constructed. Sorry can’t make the compiler reject it (THAT would be awesome)

Try
  Raise New NilObjectException
  
Catch noe As NilObjectException
  Dim stack() As String = noe.Stack
  
  // IF this is an instance created on a layout we should find a 
  // Window.__Init%%o<Window> in the stack above the call to this Constructor
  For i As Integer = 0 To stack.Ubound
    If stack(i) = "Window.__Init%%o<Window>" Then
      Return
    End If
  Next
  
  // and if we do not then raise an UnsupportedOperation error
  Raise New UnsupportedOperationException
End Try

A window, when being created, calls __Init and so we can tell if we were called by a window being created or not by walking up the call stack. If there is no Window.__Init in the stack then we definitely were not and so can raise an exception to let the coder know that this usage, without a parameter, is only for Layouts and nothing else.

Sampling with a delay

MacOS terminal is a useful tool to know for a few really handy things.

One is getting a sample of a process after some delay so you can start doing whatever it is you want to sample.

Trying to do this in Activity monitor is not possible

But at the command line you can delay the start of the sample so you have a chance to set up the sampling and then switch back to Xojo to do the task you want sampled.

So how ?

Open Terminal

Once there enter

sleep 5; sample Xojo  -file ~/Desktop/Sample2019r1.1macOS12.6.txt

The number after SLEEP is how many seconds to wait before starting to sample

The SAMPLE command takes several parameters. We’ve told it to look at any process containing “XOJO” and to put the output file on our desktop with a specific name.

This handy bit of bash makes it easy to sample something to send to Xojo as part of a bug report.

Why shadowing should be avoided

We’ll create a sample project to demonstrate why its a bad thing to do.

Start a new desktop project.

Add a new Class that is a subclass of ”CancelButton” by dragging a CancelButton from the library to the Navigator.

Name this new class “myPushButton”

Add a property  to it – enabled as boolean

Make sure the property is public

Now on Window1 add an instance of this new button subclass.

Name it “MyPb”

Now add a bevel button and name it bevTestSubclass.

Change its Caption to say “bevTestSubclass”

In its action event put

myPb.enabled = Not myPb.enabled
myPb.invalidate

Add a second bevel button and name it bevTestBaseClass

Change its Caption to say “bevTestBaseClass”

In its action put

PushButton(myPb).enabled = Not PushButton(myPb).enabled
PushButton(myPb).invalidate

Save (if you care to) and Run

If you push the bevTestBaseClass button the button enables & disables on each push. And it does this visibly.

But if you click the bevTestSubclass button nothing happens.

Why not ?

Properties are not virtual. Quite literally there are two “enabled” properties and they are not the same one. The custom subclass contains one. And the base class contains one.

So when the code knows you are referring to the subclass type the “Enabled” property that is used is the one in the subclass instance. And the framework doesn’t look at this one at all.

So the framework looks at the one in PushButton and redraws with whatever Enabled state that one says.

And its not the same as the one in the subclass.

But when you press the bevTestBaseClass button you do get the change you expected because the cast makes the code refer to the Superclass version of enabled.

This specific use where a cast is involved isn’t so hard to find with a search and replace. But it’s also not the only way that shadowed properties cause problems. The really tricky ones are where the declared type of a variable is the superclass type and then you get much the same behaviour as with the casts. And this one is NOT easy to find.

We’ll demonstrate by adding additional code to the project so far.

First lets define a new method – FlipSubClass – that takes a myPushbutton as a parameter.

Public Sub flipSubclass(button as myPushButton)
  button.enabled = Not button.enabled
  button.invalidate
End Sub

And for good measure we’ll add a new method – FlipSuperClass – that takes a Pushbutton as a parameter

Public Sub flipSuperClass(button as PushButton)
  button.enabled = Not button.enabled
  button.invalidate 
End Sub

The only difference between these two is the type of the parameter.

Now lets add two more bevel buttons to use these new methods.

Add a bevelbutton and name it bevDimSubClass and set the caption to bevDimSubClass.

In this bevel buttons action event put

  flipSubClass(myPb)

Add a second bevel button named bevDimSuperClass and set the caption to bevDimSuperClass

And in this action event put

  flipSuperClass(myPb)

And run.

Note this time there is NO explicit cast required and we can safely pass a myPushButton to a method that takes a PushButton because a subclass IS always also the super class type (isA would be true if you checked myPb isa PushButton)

And yet the bevDimSubclass button has no effect on the buttons appearance but the bevDimSuperClass button does.

Its the exact same issue as before but this time it’s even harder to detect because what natters here is not the actual type or the instance but the DECLARED type of the parameter. 

Since shadowing can cause such hard to track down bugs it better to avoid it.

Now IF you cannot and really to require a subclass have its own “Enabled” property that actually works you should add it as a COMPUTED PROPERTY that in the getter simply casts SELF to the super type and returns the’s supers property value. And in the getter again cast to the super type and set the supers property to that value given.

And here’s a sample that shows the bad version and how to make it work as expected

Follow up on what type am I ?

Back when I was still at Xojo I wrote a blog post about what type of variable am I ?

This is a follow up on that to maybe help explain things more.

The particular difficulty is arrays. They are simple and can cause deceptive an hard to find bugs BECAUSE they are so easy to use and the Xojo language appears to do what you intend (but I don’t think it is doing the wrong thing).

Its why its important to know the difference between a value type and a reference type.

The set up for this is simple. A new Class in a desktop project cleverly named Class1. That class has one public property, values() as variant.

The rest of the code is in the Window1.Open event in a desktop project.

It’s important that you turn on Preferences > Debugging > Show Object IDS in variable lists.

The rest of the code is simply this 

Dim theClassInstance As New class1

Dim emptyarray() As Variant

theClassInstance.values = emptyArray // <<< THIS LINE IS WHAT CAUSES THE HAVOC !!!!
// Because arrays are "reference types" this line does not copy each value in the 
// array into a new array
// it simply sets "theClassInstance.values" to refer to the same array as 
// "emptyarray" refers to
// so altering one looks like it alters the other

// for this example turn on Preferences > Debugging > Show Object IDS in variable lists

Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

theClassInstance.values.append ( "123" )
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

Redim emptyarray(-1)
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

emptyarray.append ( "123" )
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

Redim theClassInstance.values(-1)
Break
// now look at the object ID of emptyarray and theClassInstance.values
// they _should_ be the same which means they are the same object so 
// changing one will appear to change the other

If you run this code at each break point you can see that if you check the array that was NOT touched in code you will see it has also changed to mimic the other.

This is because arrays are reference types and the line

        theClassInstance.values = emptyArray 

copies the REFERENCE – not the values in the array 

Be careful with your references out there !

Simple but really useful alternate menus

macOS supports the notion of Alternate menus. One that even once you have opened the menu you can toggle between their textual description and short cut by pressing the Option Key or another modifier like Shift or Control.

And you can even set up several so pressing Shift is one, Shift + Ctrl is another, and Option is yet another.

And this is achievable in Xojo quite easily.

I’ve posted a small project that demos this 

Enjoy !

My departure

Originally published on my old blog March 12, 2019

After Joe Ranieri quit* & moved to a new job I think everyone felt stressed. I know I did. It felt like so much more was expected of an ever smaller group of developers.

By Dec of that year I’d had enough of the forums and some of the general dumping on Xojo as a product. I’d made a post, I forget about what, and decided later to remove it. And I removed a bunch more of my posts.

And that lead to https://forum.xojo.com/44831-norman-s-posts

So my account was altered so I could read but not post delete etc

Fast forward to last week.

Internally we had a Slack question about how everyone learned to code.

I replied as did Dana and others.

Dana mentioned that she’d learned HTML and CSS (I think)

I replied that they aren’t for application coding and and while lots of devs know them those aren’t quite the same.

And there was a reply about how it was expected that maybe a customer might do this “gatekeeping” it wasn’t expected of someone internal.

I replied to the effect “nm forget I said anything”

Later I decided that post was not suitable, nor the gatekeeping one so I removed them. And I was editing my previous one about how I got started and managed to delete the thing. Not sure how but I did. Maybe having a granddaughter around when you’re at your computer is a bad idea. I don’t honestly know but Slack really needs UNDO (maybe it has one and I don’t realize it?)

Anyway it was gone and I didn’t think it was a big deal as I could repost how I learned if necessary and the other two did not need to be revived.

Monday morning I got up. Grabbed a coffee. Sat at my machine. And since I had slept in a bit started Slack preparing for the usual morning meetings we have. 

And there was a message from Travis asking “Hey you there?”

Now he NEVER pings a person before the morning huddle. And I mean never. So this was weird.

I answered him and he called. Right from the outset I had a bad feeling as his tone and what he said made it obvious this was a “Bad Day”

We talked a bit – but it was obvious the decision was already made and out of his hands. I truly had to laugh at the … pettiness … not sure thats the right word .. the sheer insanity of being fired for removing a few posts that I had come to realize probably should not have been posted in the first place. The was a passing mention of “abrasive to customers” or something along those lines but it was obvious that wasn’t THE core issue.

And that is why I’m no longer at Xojo. Deleting posts that I realized probably should have been posted in the first place.

At least thats how I understand things.

Things will, eventually be ok here.

At Xojo I don’t know as the IDE code base, never mind everything else, is large complex and can be very hard to move in any particular direction and NOT break a lot of things along the way.

*Joe continued to work for Xojo on contact for a few months after this because his work on Android wasn’t finished.

An extensible class factory

Some times you want to make a nice generic class that a user can extend via subclassing.

However, one issue arises with this.

How can a factory method in the super class create instances of the subclasses ? This is especially troublesome if the classes you have are encrypted so you cant change the source or in a plugin.

However, it IS possible to create an “extensible factory method” so the factory can create instances of the subclasses users provide.

Lets look at how you can do this.

Usually a class factory method looks something like

Class MySuperClass
  Private Sub Constructor()
  End Sub

  Shared Function CreateNew()
    return new MySuperClass
  End Function
End Class

The private constructor makes it so no one can create an instance without using the factory.

So how do you make this basic pattern extensible so the factory can create instances of the correct subclasses ?

If you had the source code you could change the factory method to

  Shared Function CreateNew(name as string)
    select case name
    case “MyCustomSubclass”
       return new MyCustomSubclass
    else
      return new MySuperClass
    end select
  End Function

But there are some real problems with this

the superclass has to be alterable – if you dont have source code you cant do this. So distributing code to other people to uses becomes a real problem

every time you add a subclass you have to remember to alter the superclass

What do you do if this is a plugin written in C++ ?

As the author of a class thinking about how to solve these issues is really important. And this one is solvable. For pure Xojo code and for plugin authors.

Recall that Introspection allows you to look at a class, and its constructors. As well you can invoke one and get back a new instance.

So lets create a mechanism to let the superclass know about subclasses, and then use that knowledge to create the right instances when we need them.

First lets add the “way to know about subclasses”

At runtime the way to “know” about other classes is .. introspection !

And that knowledge is a typeinfo object.

So our superclass needs a way to get the typeinfo’s of subclasses and hang on to it for later use.

Holding on to it for later is easy – an array of Introspection.TypeInfo objects will suffice.

  Dim mSubTypes() as Introspection.TypeInfo

Now how do we get all the info about subtypes ? 

We cant just go through all the objects that exist at runtime because if there are no instances of subtypes yet then we would not find any. So we need some way to “register” the subtypes with the superclass so it can use this information later.

So a method like

  Shared Sub RegisterSubType( subType() as Introspection.TypeInfo)

that adds to the array we defined earlier should suffice

Our class now looks like

Class MySuperClass
  Private Sub Constructor()
  End Sub

 Shared Function CreateNew(name as string)
    select case name
    case “MyCustomSubclass”
       return new MyCustomSubclass
    else
      return new MySuperClass
    end select
  End Function

  Shared Sub RegisterSubType(
         subType as Introspection.TypeInfo)
    mSubtypes.Append subType
  End Sub

  Private Dim mSubTypes() as Introspection.TypeInfo

End Class

And now all we really need to fix is the CreateNew method so it can return a subtype properly

We’ll leave the parameters as is for now – so we create “by name”

This has some implications, like if you make a typo you wont get back the instance you asked for, but we can fix that later.

The first thing I’ll do is slightly alter the method signature so it has a default parameter.

 Shared Function CreateNew(name as string = “”)

And that’s if for changing the method signature

This allows us to do a tiny bit of optimization AND makes writing code a tiny bit easier

So first things first – if NO name is supplied we just return a new instance of the superclass.

  if name = “” then
    return new MySuperClass
  end if

And after this we have to find the right “TypeInfo” and create an instance from that. And should we find no match we should return nil – which can be used as an error check to find any issues.

Each TypeInfo object has a NAME property.

So we an iterate through our list of registered TypeInfo objects, find the one with the right name, and invoke its Constructor.

  For i As Integer = 0 To mSubTypes.Ubound
    
    // find the type info with the right name
    If mSubTypes(i).Name = subtype then
    
    // found it so get a list of its constructors
    Dim cInfo() As Introspection.ConstructorInfo =
                               mSubTypes(i).GetConstructors
    
    // and find the 0 param constructor
    // since out factory does not pass along any params
    For j As Integer = 0 To cInfo.Ubound
      Dim pInfo() As Introspection.ParameterInfo = 
                                 cInfo(j).GetParameters
      
      // has no params ?
      If pInfo.ubound < 0 Then
        // yes - invoke this one & return the result
        // which will be an instance of the right type
        Return cInfo(j).Invoke
      End If
      
    Next
    
  End If
  
  Next

  // if we reach here we will be default return a nil 
  // or we could explicitly return nil

And there we go – a superclass with a factory method that can be extended by anyone – with or without source code !

The end result is a class as follows

Class MySuperClass
  Private Sub Constructor()
  End Sub

  Shared Function CreateNew(name as string = “”)
    if name = “” then
      return new MySuperClass
    end if

   For i As Integer = 0 To mSubTypes.Ubound
    
      // find the type info with the right name
      If mSubTypes(i).Name = subtype then
    
      // found it so get a list of its constructors
      Dim cInfo() As Introspection.ConstructorInfo =
                               mSubTypes(i).GetConstructors
    
      // and find the 0 param constructor
      // since out factory does not pass along any params
      For j As Integer = 0 To cInfo.Ubound
        Dim pInfo() As Introspection.ParameterInfo = 
                                 cInfo(j).GetParameters
      
        // has no params ?
        If pInfo.ubound < 0 Then
          // yes - invoke this one & return the result
          // which will be an instance of the right type
          Return cInfo(j).Invoke
        End If
      
      Next
    
    End If
  
    Next

    // if we reach here we will be default return a nil 
    // or we could explicitly return nil
  End Function

  Shared Sub RegisterSubType(
         subType as Introspection.TypeInfo)
    mSubtypes.Append subType
  End Sub

  Private Dim mSubTypes() as Introspection.TypeInfo

End Class

Something you might do is to make the factory NOT take a string but a typeinfo so that there’s no “typo’s” to debug at runtime. Using a typeinfo would mean most typo issues would be caught at compile time.

That’s left as an exercise for the reader.

Code for safety

Lots of time you see code like

static flag as boolean 
if flag then return

flag = true

// rest of method

flag = false

In a simple method/event with only a handful of lines there’s probably nothing wrong with this

But what do you do when the method spans into hundreds or thousands of lines ?

And if you use the philosophy of “bail early” ?

Then your methods/events start to look like

static flag as boolean 
if flag then return
flag = true

if condition then
  flag = false
  return
end if

if condition2 then
  if condition3 then
    flag = false
    return
  end if
else
    flag = false
    return
end if

flag = false

And following all those returns & making sure you reset the flag correctly in every one is tedious.

So what if you could make it so you NEVER had to worry about the flag remaining set when you returned ?

Remember that objects get destroyed when the last reference to them is removed – they automatically get cleaned up.

At first glance it seems that you should be able to do

static flag as date
if flag <> nil then return
flag = new Date()

// rest of method
return

and then when the method ends the date object would go out of scope, get destroyed and the world would be happy & safe for not forgetting to flip that flag.

Sadly because the variable is a static this wont happen – the static persists across calls and so it wont get destroyed.

So the trick is how to make the variable persist across method calls AND also get destroyed when things go out of scope.

But that doesn’t mean we’re stuck.

One issue we do have is that in the way we’ve set up our flag property its a value type which means other code can’t hold on to a reference to it to do anything later.

And because its a static declared in a method other code outside this method cannot touch it to flip its value.

So we need to deal with both these issues.

The second one is easiest to deal with – we can simply move the static from being declared in the method to a property on the class that is only used by this method (although its much more usual to see such a blocking action like this happen in several methods or events rather than just a single one)

So we’ll change

static flag as date

to a similarly named property on this class / window 

By simply doing this we make it possible to use an object that, when created and then goes out of scope makes it so we can use the constructor & destructor to change out flag so things get blocked & allowed as needed.


So how do we have something flip the flag when we need ?

In theory we want our code to look like

if flag then return // remember flag is a private 
                    // or protected property on the class

dim flipper as new FlagFlipper( ???????? )

// rest of method

So what does this “Flipper” thing looks like & how does it work ?

We’ll create a class – FlagFlipper. 

And this class needs to then be able to know how to set and clear the flag we set up. But we really don’t want this new class to have to reach inside other classes to do this.

And this is where delegates come into play.

A delegate is a “type safe function pointer” which means that

it’s a function you can pass around like any other parameter

 it’s type safe – you can’t just pass any old function 

So our new class is going to look something like

Class FlagFlipper
  Constructor( ?????????? )
    // flip the flag in the target class somehow

  End Constructor

  Destructor()
    // flip the flag in the target class somehow
  End Destructor
End Class

To this we’ll add 2 delegates

Delegate SetFlag()
Delegate ClearFlag()

Note that we do not put code in these.

Recall we do not want the flag flipper to know the innards of a class to know how to do its work.

So we need to “pass” the right “function” to the flipper so it can call them without having to know anything more than the two delegates.

So how do we do that ?

Well … addressof CREATES an instance of a delegate

So that seems like we need to use that somehow

We want the actual management of the flag to be in our original class.

So the methods to set and clear the flag should be part of that class (and it really doesn’t matter if this is a class/layout/ etc) Lets suppose we were originally using a Window – so we’ll add code to the Window

In my example so far things look like

Window Window1

  Event Open
    foo
  End Event

  Method foo
    if flag then return

    dim flipper as new FlagFlipper( ??????????? )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Method

  Private Property flag as boolan

End Window

And as stated we’re going to add two methods – setflag and clear flag

Now things look like

Window Window1

  Event Open
    foo
  End Event

  Sub foo
    if flag then return

    dim flipper as new FlagFlipper( ??????????? )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Sub
  
  Private Sub SetFlag()
    flag = true
  End Sub
  Private Sub ClearFlag()
    flag = false
  End Sub

  Private Property flag as boolan

End Window

Now how do we have to make the Constructor & set up of the instance look so the right setflag / clearflag methods are called ?

Well … delegates & address of !

If we make the constructor look like the following 

Class FlagFlipper
  Constructor( setFlagMethod as SetFlag, 
                 clearFlagMethod as ClearFlag )
    // flip the flag in the target class somehow
    setFlagMethod.Invoke
    mSetFlag = setFlagMethod
    mClearFlag = clearFlagMethod 

  End Constructor

  Destructor()
    // flip the flag in the target class somehow

  End Destructor

  Delegate SetFlag()
  Delegate ClearFlag()

  Private mSetFlag as SetFlag
  Private mClearFlag as ClearFlag 

End Class

Note that it holds on to a reference to the method to call to set or clear the flag

And the set up in the method that originally needed the flag looks like

Window Window1

  Event Open
    foo
  End Event

  Sub foo
    if flag then return

    dim flipper as new FlagFlipper( AddressOf SetFlag,
                      AddressOf ClearFlag )

    foo // to make it so we can see the 
        // second call to foo is blocked

  End Sub
  
  Private Sub SetFlag()
    flag = true
  End Sub

  Private Sub ClearFlag()
    flag = false
  End Sub

  Private Property flag as boolan

End Window

And now, by using an object that when it goes out of scope automatically cleans up after itself we’ll no longer have to worry about “did I clear that flag ?”

Here’s the completed project