Debugging tip

Sometime when you’re debugging your application you run into a situation where you get funky behaviour.

You might do something like Javier mentioned in his recent blog post on Xojo’s blog :

Dim ASource() As Integer = Array(1,2,3,4,5,6,7,8)
Dim ATarget() As Integer
ATarget = ASource

And, as he noted, you cant figure out why when you change one array you also appear to alter the other. This can also happen with other reference types as I noted in other posts.

For instance I’ve seen

Dim d As New Date
Dim d1 As date
d1 = d

d1.month = 2

and then the question of “why did d change?” arises

Again this has been covered before and it has to do with both arrays and dates, as well as many other type, being reference types.

One way to see that in fact these are the same object is not well documented in the Xojo documentation. Its buried in the Debugging pane of the preferences – Show Object IDs in variable lists.

Once you enable this setting what you see in the debugger pane makes it much easier to see when you have two references to the same object.

When viewing the following code

Dim ASource() As Integer = Array(1,2,3,4,5,6,7,8)
Dim ATarget() As Integer
ATarget = ASource

You can clearly see that ATarget and ASource have the same objectID. In Xojo’s runtime this means they are the same object – objectsID’s are unique to every instance and the only way you get two objectID’s that are the same is when two references refer to the same object.

I’d recommend always turning this setting on when debugging.

Error handling speed

A question I was asked recently posed an interesting question about exceptions and the cost of using them as a general error handling mechanism.

Xojo uses whats know as “zero cost exception handling”. Essentially at runtime there is no penalty for having exception handling in place. It imposes no runtime overhead when NO exceptions are encountered. But, when exceptions are encountered, it can be “expensive”.

Expensive in this sense can mean it induces slowness or requires more memory. Or both.

So I put together a simple example that demonstrates the cost of using exception handling instead of error codes. Its very simple and uses a deprecated API that reported error codes instead of the newer one that raised an exception instead.

Its just a simple desktop application with a textarea on the default window and this code in the Window’s Open event

Dim f As folderitem = SpecialFolder.Desktop.Child("foo")

Dim errorcodeStart As Double = Microseconds
Dim errorCodeCount As Integer
For i As Integer = 1 To 1000
  
  Dim ts As TextInputStream = f.OpenasTextFile
  
  If f.LastErrorCode <> 0 Then
    errorCodeCount = errorCodeCount + 1
  End If
  
Next

Dim errorcodeEnd As Double = Microseconds

Dim exceptionStart As Double = Microseconds
Dim exceptionCount As Integer
For i As Integer = 1 To 1000
  
  Try
    Dim ts As TextInputStream = TextInputStream.Open(f)
    
  Catch IOX As IOException
    exceptionCount = exceptionCount + 1
  End Try
  
Next

Dim exceptionEnd As Double = Microseconds


Dim errorTotal As Double = errorcodeEnd - errorcodeStart
Dim exceptionTotal As Double = exceptionEnd - exceptionStart


TextArea1.AppendText "1000 iterations" + EndOfLine 
TextArea1.AppendText "Error Code = " + Str(errorTotal) + "ms" + EndOfLine 
TextArea1.AppendText "Exceptions = " + Str(exceptionTotal) + "ms" + EndOfLine 

In a debug run on my compute I get the following output.

1000 iterations
Error Code = 28096.87ms
Exceptions = 41711.62ms

The version using exceptions is juts about 50% slower over 1000 iterations when debugging.

In a version compiled with the DEFAULT setting the difference is less, but still present.

1000 iterations
Error Code = 28367.42ms
Exceptions = 35925.94ms

Exceptions are still about 25% slower than error codes. The Moderate optimization setting is similar

1000 iterations
Error Code = 29292.96ms
Exceptions = 34415.9ms

Aggressive settings remain similar

1000 iterations
Error Code = 28222.49ms
Exceptions = 35309.52ms

There are some advantages to exceptions. Unlike error codes they are impossible to ignore at runtime. At some point you MUST put code in place to handle them or your application will just quit with an unhandled exception error.

However, there’s nothing in Xojo that helps you make sure you have handled the possible exceptions that can be raised, and also nothing that tells you what exceptions might be raised.

So heads up before you dive into using exceptions everywhere as a general error handling mechanism in your applications. There are costs to doing this and they could manifest themselves in slower code or code that requires more memory. Or both.

More good habits

On the forum there was a suggestion that a person should use a container control that had a few controls embedded in it at design time. And then when using that container control that they should skip providing an API that the container presented and just reach inside the container and manipulate the controls it contain directly.

Personally I would recommend against this.

I’d start by saying when you create a container control ALL the controls in it should be private by default to prevent this. And that if you want to expose functionality of the controls on the container you do so by defining methods and events on the container that any code OUTSIDE the container can call or react to just as if the container control was any other single control and not a composite one like it is.

Why would I make such a recommendation ?

  1. good habits
  2. encapsulation
  3. reusability
  4. long term flexibility and maintainability

The first point is just that this is a good habit to get into. And the reason its a good habit is because of points 2, 3 and 4. Properly encapsulating and hiding the details from other bits of your code is a good thing. Code outside the container doesnt need to know HOW the container does what it does. Just that it does what is expected when you call its methods, change its properties and react to the events it exposes. Thats it. It should be a black box like the built in Xojo listbox, pushbutton, or any other built in control is. You dont need to know how those do what they do, just that they do what you expect when you call the methods, set the properties and react to their events.

And the bonus to doing this is that it makes the likelihood you, or others, can reuse your control in more places in your project or in other projects much higher because the control is self contained.

Long term it also lets you do things like completely swap out the implementation of the container for some other means and as long as you dont need to change the API nothing outside the container control even needs to be aware this has happened. This makes your own code easier to maintain since you no longer have to look through all the code outside of the container to know if you also need to alter it because something in the container changed.

These are all good things regardless of whether this code is for your own use, more general distribution or possibly for sale or to give away.

I’d encourage everyone to keep these things in mind when ever they write their own custom controls.

Of bounds and positions

Windows have two sets of properties that all relate to positioning a window.

However, they are not all quite created equally.

There are, of course, the typical top, left, width and height properties. And also the “bounds” property which is a Rect.

If you examine the bounds property for a Document window, and the top, left, width and height you will find that the Bounds.top is not the same as the top property value. Nor is the height. Now why is that ?

In the following image the BOUNDS are the area enclosed by the red rectangle. And the top, left, width and height properties describe the area in light blue.

If you only had the top, left, width and height properties to use to position a window you would have to somehow figure out what the real size of the window was and account for the title bar size and possibly the outer window frame size. There may or may not be one depending on platform and window type.

And if you add a toolbar this further complicates that. The following image is the same window with a toolbar and once again marked with a red rectangle around the bounds and the blue area is the rectangle described by the top, left, width and height properties.

If, for some reason, you want to know the height of the title bar you can use the difference between the bounds top and the windows top property to see how tall it is.

Note that you cant use this difference to know how tall the title bar and toolbar independently. And toolbars dont appear to propertly report their top, left, width, or height at runtime. 🙁

Still the difference between the bounds properties and the windows other properties will let you determine how tall the title bar + any toolbar is.

Careful with those bounds out there.

Good habits when creating custom controls

Suppose you have the need to create a custom control like I did recently

One of the things that you should do so people do not get confused about using your control is to “implement” any events in whatever you use as your base class that should not be exposed to end users of your control. If you dont inplement these events then a user could, and that might end up in surprising behaviour in your carefully crafted control.

If you dont implement the Open event for your custom control a user could put an instance on a layout and implement that event. If this causes problems than you can make it so they cannot implement the Open event simply by adding that event handler to your custom control.

There may be events, like ConstructContextualMenu, DragEnter, DragMove, etc that make no sense for your custom control and so implementing them in your class would make it so users cant.

And this should make your custom controls easier for others to use.

EmbeddedWindowControl

If you’ve ever used a container control on a layout and then tried to manipulate the controls at runtime with code like


For i As Integer = 0 To Self.ControlCount - 1
  Dim ctrl As Control = Self.Control(i)  
  // now manipulate this control or call its methods
Next

you’ve probably run into the EmbeddedWindowControl

Its what you get when you use a Container Control on a layout either by placing one at design time or dynamically adding one at runtime.

Note that you get an EmbeddedWindowControl – not an instance of the Container you placed there. So any code you use that tests if a control ISA specific instance will fail for your containers. You don’t get a reference to the instance you get this EmbeddedWindowControl instead. So you cant call any methods you have added to the container control or reference any properties of it.

Its been most annoying. There have been several requests for something to be done so the container the EmbeddedWindowControl was created from can be accessed. Like this one and this one and this one.

And today, for a project I was working on, I needed this and decided to figure out how to make this possible.

The result is this little sample program with one module that extends EmbeddedWindowControl in a way you can get the container control that the embedded window control was created from.

To make use of this simply copy the EmbeddedWindowControlExtensions module into your project. Then when you iterate a set of controls on a layout you can do

For i As Integer = 0 To Self.ControlCount - 1
  
  Dim ctrl As Control = Self.Control(i)
  
  If ctrl IsA EmbeddedWindowControl Then
    
    Dim cc As ContainerControl = EmbeddedWindowControl(ctrl).Container 
    
    If cc <> Nil Then
      // you now have an actual reference to the container control
      // so you can use its methods, properties, etc
      // but you will need to cast it first
    End If
    
  End If
  
Next

Enjoy !

Knowing if a property thats an enum has been set

Interesting question from a dev I’ve know for a long time.

If I have a property that’s an enum, how do I tell that it’s not been set?

And this is a good question.

Because an enum is, at its core, an integer when you declare one and run its always initialized to the default value for an integer – 0.

And so if you use this fact you can actually detect that its been set or cleared.

Simply make you list of enumerated values NOT use 0 as a valid value.

Public Enum myEnum
valueName1 = 1
valueName2 = 2
valueName3 = 3
End Enum

And now any time the value is 0 when your code starts to run you can tell any property that is declared to be a myEnum is or is not set by checking

Private Property someProperty as myEnum

Sub Open() Handles Open
  
  If 0 = Integer(someProperty) Then
    break
    // someProperty has never been set or has been deliberately set to 0
  End If
End Sub

Interfaces

Interfaces are one of those things in Xojo, and many other computing languages, that can really help you make your code more reusable and generic.

For instance, suppose you need a class that is a “List”. You could write a single class, called list, that you could add items to, remove items from, and generally manipulate in a “list like way”. You might go so far as to look up some other languages implementation of list and create a Xojo equivalent. But in general you would have (as wikipedia notes)

Operations
Implementation of the list data structure may provide some of the following operations:
- a constructor for creating an empty list;
- an operation for testing whether or not a list is empty;
- an operation for prepending an entity to a list
- an operation for appending an entity to a list
- an operation for determining the first component (or the "head") of a list
- an operation for referring to the list consisting of all the components of a list except for its first (this is called the "tail" of the list.)
- an operation for accessing the element at a given index.

But note that wikipedia, and most other place that have such a “spec” dont say how this is implemented. Just what the API is. And this is a perfect place to use an interface.

Now in Xojo MOST times you dont need to define the CONSTRUCTOR in an interface. You can but it is unusual and depending on what classes you intend to have implement this interface there can be restrictions on which constructors must exist (ie/ if you want a UI control like listbox to implement this interface it may need a constructor with no parameters)

So I would NOT add this to the interface.

But everything else can be specified in an interface.

an operation for testing whether or not a list is empty - possibly a method named "IsEmpty" that returns a boolean ?
an operation for prepending an entity to a list - possibly a method named "Prepend" that takes an element and adds it to the "front" of the list
an operation for appending an entity to a list - possibly a method named "Append" that takes an element and adds it to the "end" of the list
an operation for determining the first component (or the "head") of a list - maybe a method called "FirstItem" or "Head" that returned the first item
an operation for referring to the list consisting of all the components of a list except for its first (this is called the "tail" of the list.) a method called "Tail" that returns the list with the first item removed
an operation for accessing the element at a given index - a method called "ElementAt" that takes an index parameter and returns the element at that index

And that would be an interface that confirmed to Wikipedias notion of “List”

The interstingthing is that Xojo already has many classes that behave in ways that are “list like” in many ways. Listbox, popupmenu,combobx and a few others already have methods like AddRow, RemoveRow and many of the others that are “list manipulation and inquiry” type methods. You can find out if a listbox is empty (listcount = 0), you can remove and access rows at specific positions.

But Xojo doesnt define and use an interface for this class or any other that share similarties. However, you can add your own.

In order to do this you need to define the interface in a very generic way so that adding a row to a listbox, which may have 1 or more columns, still makes sense. Some input parameters might need to be variants instead of something more specific. And, for some things the right return value may have to be a variant instead of something more specific.

Still you might come up with an API for “list” like things that looks like :

Interface List
  Sub AddRow(ParamArray values() as string)
  End Sub
  
  Sub AddRowAt(ParamArray values() as string, zeroBasedInxed as integer)
  End Sub
  
  Sub FirstRowIndex() as integer
  End Sub
  
  Sub LastAddedRowIndex() as integer
  End Sub
  
  Sub LastRowIndex() as integer
  End Sub
  
  Sub RemoveAllRows()
  End Sub
  
  Sub RemoveRowAt(zeroBasedIndex as integer)
  End Sub
  
  Sub RowCount() as integer
  End Sub
  
  Sub RowTag() as Variant
  End Sub
  
  Sub RowTagAt(zeroBasedIndex as integer) as variant
  End Sub
  
  Sub RowValue() as Variant
  End Sub
  
  Sub RowValueAt(zeroBasedIndex as integer) as Variant
  End Sub
  
  Sub SelectedRowCount() as Integer
  End Sub
  
  Sub SelectedRowIndex() as integer
  End Sub
End Interface

And then you can apply this to your own classes. custom subclasses of listbox, combobox, popup menu and other controls that have list like aspects to them.

Once you do this you can then write generic methods that manipulate Lists, without regard to whether its a custom user class implementing the interface, a listbox, a popupmenu etc because all of them will return TRUE when you do

If <something that implements list> IsA List Then
End If

This is very handy and very powerful and wildly under utilised.

Computed Constants

Kind of an oxymoron. A constant should be .. well .. constant.

However there are times you want that constant to be permanent, or constant, and unchangeable but it needs to be computed at compile time.

And it turns out that in Xojo you can do that IF you define a constant in code like :

Const foo = 123
Const bar = 345
Const foobar = foo + bar

If you assigned these constants to variables so you could inspect them like

Dim iFoo As Integer = foo
Dim iBar As Integer = bar
Dim iFooBar As Integer = foobar

break

you would see that iFoo, iBar and iFooBar have the values 123, 345, and 468 as expected. So constants can be formed from other constants and literals at compile time and they are then permanent in your application.

But you cannot do this in a constant defined using the IDE’s constant editor. It does not compute the values in the same way as it does when you define the value in code as shown above.

If you try to define constants, cFoo = 123, cBar = 345 and cFooBar = cFoo + cBar you will find that cFoo and cBar are ok and are numeric. But cFooBar will not compile if you set its type to Number. The usual trick of using #ConstantName which works in other places in the IDE wont work in the default value field of a Const defined this way. This has lead me to submit a bug report.

In the mean time whats a person to do ?

As it sits right now the BEST we can do is a workaround.

Constant-ness is a behavioural thing in most respects. Basically its a value that never changes. Like the value of Pi, Avogadro’s number, or the gravitational constant. In our code we would like a value that never chnages once it’s compiled for these sorts of values.

But if its one of our own making using an expression that is computed at compile time would be really nice. Something like bit flags for error conditions is a common use.

It might be that we have

Const Error = 1
Const IsFatal = 2
Const FatalError = Error + isFatal

And so we can see that a fatal error is computed from the Error & isFatal flags.

Currently the only way to provide a computed constant, or something that behaves like it, is a Computed Property that only has its getter implemented.

We could then have

ComputedProperty FatalError as Integer
  Get
    return Fatal + IsError
  End Get
  Set
  End Set
End ComputedProperty

Semantically this would behave like a const.

The downside is that

  1. every time it’s accessed the value is recomputed (this can be worked around somewhat)
  2. every time it’s accessed there is method call overhead

While not a perfect replacement for a constant it’s what is possible today.

Making platform specific error codes generic

A few threads on the forums have commented that the URLConnection isnt quite as easy to use as many might expect. In particular there are comments about having to know what error codes a platform might return makes it harder to use than it should be.

Normally Xojo hides this level of detail from us.

I was thinking about this problem and have come up with something of a solution that makes it possible to both know the specific error code and yet still write code that is portable.

My solution relies on the fact that, at compile time, numeric constants will take on one of many possible values if you set up platform specific versions of a numeric constant. Its possible to set up a constant with a specific value for macOS, Windows, Linux, and iOS (as well as a couple that are legacy types) as follows :

If you were to compile this code on macOS the Foo constant would have the value 1, on Windows it would be 2 and so on. The nice thing is that code could simply use the symbolic constant Foo instead of having to rely on the specific value. Instead of writing

// is someVariable = Foo on macOS ?
if someVariable = 1 then
   // do whatever should be done 
end if

you could, and probably should write

// is someVariable = Foo on macOS ?
if someVariable = Foo then
   // do whatever should be done 
end if

This is has the added benefit of making your code more robust since a simple change to a constant is all thats required to instead of finding all the magic number 1’s everywhere. But how does this help us to making generic platform specific error codes (which I admit is a bit of an oxymoron ?)

An enumerated value can be set from one of several possible sources. It can have no specific value assigned, have a literal value, an enumerated value from another enum, or a constant.

IF Enum2 is is defined as

Public Enum Enum2
  value1 = 10
End Enum

Enum1 can be defined as

Public Enum Enum1
  value1 // no specific value assigned
  value2 = 99999
  value3 = enum2.value1
  value4 = kConst
End Enum

That we can use a constant is especially notable as we just saw we can make a constant platform specific. So its possible to have an enumerated value that takes on the value of a platform specific version of a constant (but be careful with this as you would not want to have many enumerated values with the same value as that makes them harder to use)

If we defined our enum as

Public Enum kDemoEnum
  value1 = kConstant
End Enum

and the constant as

Public Const kConstant as Number = -1
  OS X, default language, 1
  Windows, default language, 2
end Const  

when we compiled on macOS the value for kDemoEnum.value1 would be 1, on Windows 2 and on any other it would be -1 (the default for the enum)

So now you can make enumerations that give you the flexibility of named values without having to know the specific values AND a generic set of enumerated values that reflect platform specific values taken from constants.

Use carefully.

UPDATE ! – here’s an example