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

Leaky abstractions and how to plug some

Every once in a while you run into some code that tries to present a fairly abstract API to some class / module. Maybe this is in your own code or in code you have received from some other source.

But as you work with it you find that the abstraction reveals internal implementation details that really should not be known outside the class. One way to hide these sorts of details from other portions of your code is to use an API defined in an interface.

However, even that doesnt always work.

Suppose you have some set of classes where you want to make it possible for one to contain many of the others and that the internal storage mechanism should be invisible, or at least not easily guessable, from other classes. Something like you see in the IDE where you have Folders that can contain all kinds of other items, or Modules that can also contains other items.

It would make sense for the classes that represent such a Container type to implement the Xojo.Core.Iterable interface so you could use either in a For … Next loop.

Lets start by assuming we’re going to create a set up like

Class ContainerType
   Implements Xojo.Core.Iterator

   Function MoveNext() as Boolean
   End Function

   Function Value() as Auto
   End Function
End Class

Class FolderType
   Inherits ContainerType
End Class

Class ModuleType
   Inherits ContainerType
End Class

We’ll have a base ContainerType class and then two subclasses*. The names of the classes I’ve chosen don’t conflict with built in ones.

At this point you might think you could write

Dim f As New ContainerType

For Each foo As Auto In f
    
Next

but you can’t. In a for .. each you need an item that implements Xojo.Core.Iterator – not Xojo.Core.Iterable.

OK we need an iterator so we’ll add one like

Class ContainerTypeIterator
  Implements Xojo.Core.Iterator

   Function MoveNext() as Boolean
   End Function

   Function Value() as Auto
   End Function
End Class

As well we need to make our initial class implement Xojo.Core.Iterable

Class ContainerType
   Implements Xojo.Core.Iterable

   Function GetIterator() as Xojo.Core.Iterator
   End Function

End Class

Class FolderType
   Inherits ContainerType
End Class

Class ModuleType
   Inherits ContainerType
End Class

And now we can write

Dim f As New ContainerType // or new FolderType or new ModuleType

For Each foo As Auto In f
    
Next

But how do we make the Iterator itself work ? Unfortunately there don’t seem to be any Xojo code examples and the docs are kind of light on this.

The iterator isnt a “friend” of our base class so it cannot reach into its guts and grab whatever data it wants. Especially not if that data is protected or private in any way. So our Iterator needs some api to be able to get the data it needs from our ContainerType classes. So we need an API for that.

But whatever API we put on the ContainerType class is also going to be usable outside the Iterator. There’s no way straight forward simple way to restrict an API to ONLY being by one class in Xojo. (This is where “friend” classes would be handy as they could have a “special” relationship and be allowed to use some private api that no other class could – there are hacky ways to achieve this though)

And so however you implement the Iterator & its access to the individual members of each class that implements Iterable those API’s are usable by ANY other code. And so that abstraction of “iterable” and how it’s implemented leaks out to the rest of the world.

Stopping this leakage can be done – in a limited way. In a module you can have an interafce that is private to that module and then classes that are in that module can implement that interface. Only methods and other classes in that module can then use that interface.

Module Containers
  Private Interface PrivateContainerAccessors
     Function MoveNext() as boolean
     Function Value() as Variant
  End Interface

  Class ContainerType
    Implements Xojo.Core.Iterable

    Function GetIterator() as Xojo.Core.Iterator
    End Function

     Function MoveNext() as boolean
     End Function

     Function Value() as Variant
     End Function

  End Class

  Class FolderType
    Inherits ContainerType

     Function MoveNext() as boolean
     End Function

     Function Value() as Variant
     End Function

  End Class

  Class ModuleType
    Inherits ContainerType
     Function MoveNext() as boolean
     End Function

     Function Value() as Variant
     End Function

  End Class
End Module
      

And now only classes IN the module can cast the classes that implement this interface in a way they can call the interface methods. This is quite handy – but it does have a drawback. Nothing outside this module can implement that interface. And that limits its usefulness to code you write and put in that module.

Friend scope would be really handy. In the mean time this is as close as you get and can stop your Iterable abstraction and the implementation from leaking out into the rest of your code.

*This really is JUST an example and not actual Xojo IDE code for those of you who might be suspiciously minded – I can assure you the IDE is vastly different than this – this is JUST an example that you can relate to from using the IDE

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 interesting thing 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.

My time is valuable (Part Deux)

In a great factory one of the huge power machines suddenly balked. In spite of exhortation, language, oil and general tinkering it refused to budge. Production slowed down and the management tore its hair.
At last an expert was called in. He carefully examined the machine for a few minutes, then called for a hammer. Briskly tapping here and there for about ten minutes, he announced that the machine was ready to move. It did.
Two days later the management received a bill for $250—the expert’s fee. The accountant was a righteous man who objected to overcharge. He demanded a detailed statement of the account.
He received this:
To tapping machine with hammer…$1.00
Knowing where to tap ………………$249.00

https://quoteinvestigator.com/2017/03/06/tap/

There are lots of variations on this story.

In a prior post I wrote about being a better developer and learning to be curious. To explore. And trying to solve the problem on your own before asking for help because people’s time is valuable.

And if you’re like me you sell your time to others as part of your consulting work. You also happen to sell your expertise and experience and those definitely are part of the price you build into whatever rates you charge clients.

As a person who makes living selling my time & expertise to others I don’t think it’s unreasonable to ask for fair compensation when I’m asked for assistance.

I’m more than willing to help out but, since I do make a living consulting, I do expect to be compensated for the time I spend working on a project.

And sometimes I’ll give that advice for free. Or I’ll simply charge a small nominal fee that is NOT the full hourly rate I might normally charge. That’s at my discretion.

But there are those who expect that I should give advice on reasonably substantial projects for free. Not because I want to – but because I should; perhaps because I’m a nice guy and it’s only going to be one time. Really. We promise.

What this kind of request is asking me to do is value my time, possibly several hours of it, at $0 per hour.

I’m like all the rest of you. I have bills to pay just like you do. And given the option of working a few hours on something I might get a “Thank You” for versus something I’ll earn my normal rate for I can tell you which I’ll work on.

Just be aware that I often will help out for no charge but the more time I have to invest in a project to provide that help the less likely it is I will do so free of charge.

But please don’t insist that I do significant amounts of work for free “because you’re a nice guy”. I’m sure there are those who might disagree 🙂

More often than not a small bit of advice isn’t something I’m going to charge someone for. But when that bit of advice starts to turn into many hours, or even days, of effort then I just might ask for some fair compensation for my time. If it’s worth asking me for that advice it might also be worth considering that I get compensated for taking the time to provide that advice.

Late fees

I read a really good article the other day from a writer who was having issues with their clients and trying to collect on invoices that were overdue.

Now, I haven’t had to do this sort of thing in a very long time, but it seemed to me that I have run into the same sort of pushback this author got about charging lates fees.

While they had contracts in hand that said the client would pay within a certain time frame and the client missed those contractual obligations to pay on time the client was still objecting to paying a late fee (despite it apparently even being a legal obligation to do so under NY or NYC law)

I’ve run into that as well way back when I contracted to a number of large corporations. Each had stated terms in the contract to pay net 30 (ie I received the payment by 30 days) but each and every one of them simply ignored the signed contractual terms and in some cases only cut a cheque on the 30th day. Unless they physically handed it to me that day, which they usually didn’t, there was no way the mail got it to me that day. To top it off they claimed that the postmark meant that it was “paid” that day. Which was all well and good but the postmarks were always 1 to 2 days later – so the invoice was still paid late in any event. One went so far as to ignore the contractual terms and simply say “Out terms are always net 90” and with held paying me for 90 days. And then they did much the same and cut the cheque on day 90 and put it in the mail. So I’d get paid 92 days after the invoice was sent, which was 62 days after the contractual terms.

When I first sent in an invoice with “Late fees” for the previous invoice they refused to pay the late fee – again despite the contract actually having terms & conditions explicitly stated for this exact eventuality and a stated late fee. Fortunately for me the group I was working for had a manager that pushed the issue and forced the company to pay the late fee AND revise their cheque processing for a lot of contracted individuals so they were paid on time.

Anyone else have a horror story about not getting paid on time and them getting pushback on charging late fees ?

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

The default app templates

A lot of times people have common code that they want in EVERY application they start working on. And there are a number of ways people achieve this – copy & paste, svn externals, or a whole host of other means.

But there is a much simpler way to start off with all that common code.

Project Templates !

With templates you can not only create new “types” of projects, you can even override the default projects that the IDE starts with when you start a new Desktop, Web, iOS and Console project. So you dont even have to think about making sure you start new projects from your list of Templates. You can just select the Desktop, Web, iOS or Console items in the New Project dialog and your template project with all your common code will be used.

So how to make all this work ? We’ll start by creating a new Template project. Once you see how easy that is it’s a small step to make the IDE use always your template as the default.

A template project will, by design, always be for one of the specific types of Xojo projects. There’s no way to make a single project that is a Desktop, Web, iOS and Console project all at the same time (there is this feature request though). Every template you create will only create one kind of project.

With that in mind let’s create a new template that we can use for desktop projects.

A common complaint is that Desktop projects don’t move from Windows or macOS to Linux very well. Linux uses different default controls sizes and so your very carefully crafted UI that looks fine on macOS and Windows suddenly has overlapping controls and looks awful on Linux.

There is a very handy module from several forum posters who use Linux a lot that resolves this issue. It modifies the normal GTK3 CSS so that the defaults are more in line with those used on Windows & macOS so your design will look correct when run on Linux.

Having a Template would make it so your Desktop projects incorporate this particular module from the outset.

Unzip and open the ModGTK3 project in the unzipped result. The IDE is going to ask you to find the Build Automation item. Press Cancel and a new one will be created. There is no harm here and I’ve asked Jim to upload this file so this minor issues can be resolved.

Create a new Desktop project in Xojo. This will form the basis of our Template. Switch back to the ModGTk3 project and COPY the ENTIRE GTK3 folder from the MODGTk3 project and all contents. A right click on the GTK3 folder and selecting “copy” in the contextual menu works nicely to do this.
Switch back to the new desktop project you created and PASTE into your project.

Add the OPEN event to your apps App instance if it does not already exist.
If it does make the first 3 lines

modGTK3.initGtkEntryFix
modGTK3.initGtkWidgetHeightFix
modGTK3.InitGlobalGTK3Style

Now we need to save the Template. Templates need to be either BINARY or XML projects.

Navigate to the directory next to your executable copy of Xojo and Save the project as a binary or XML project named PiReadyDesktopApplication.

IF you cannot save in the Project Templates location save it to the desktop and move it to the Project Templates directory next to the Xojo IDE executable.

Close the project we just saved and start a new project.

In the dialog presented (shown above) select PiReadyDesktopApplication.

When the project opens there is the new project with all the GTK3 modifications & classes we inserted previously. And if you Save you will be prompted for a new location to save the new project so you do not accidentally overwrite the Template.

To make the IDE use this template as the default every time you select Desktop from the New Project dialog all you need to do is rename the PiReadyDesktopApplication to Default Desktop Project including the spaces (don’t change the file extension). Now every time you start a new desktop project it will be using your template.

And you can do the same for Web, iOS and Console templates.

see 
http://docs.xojo.com/UserGuide:IDE_Overview 
http://docs.xojo.com/UserGuide:Project_Types 

App vs App

App Battles ! Winner takes all. Last man standing and all that !

No – nothing quite so fun (although it can be a lot of fun)

This has to do with the App class at design time vs the App METHOD (yes it’s a method) at runtime.

The app class at design time can be renamed however you want. You could call it “MyApp”. And for most things that would have no impact. But, you’ll note I don’t say for ALL things.

If you start a new Desktop Application and rename the App class to MyApp I can demonstrate where there are differences.

In the new app’s Window1. Open event lets just do something simple like

dim s as string = App.<press tab>

What you should notice is that none of the defined constants autocomplete. The methods and properties of any Application will show. But no defined constants.

This makes sense because the constants do not exist on Application but they do exist on MyApp.

If we add a few properties to MyApp they also won’t autocomplete. Again the App METHOD, at runtime, returns an Application (or Console Application, Service Application, WebApplication or iosApplication depending on the project type)

Again none of the instances that the App method returns define any of the properties we added to our custom Application instance. And so they will not autocomplete.

What’s an App to do ?

We can definitely deal with this.

One way is to not rename the App class in your project – although this wont alleviate all issues. It will just ignore some for a while. And that is, for many uses, OK.

Or we could cast the return value of the App method to be our defined class type with code like

dim s as string = MyApp(App).<press tab>

This is ALMOST always safe – except in the handful of spots that App can actually be NIL – yay !

It may be better to write something like

dim s as string
if App isa MyApp then
  s = MyApp(App).<press tab>
end if

so a nil return from App won’t matter

Either way the confusion comes from the App METHOD and the App class in your project having the same name. This can make it very unclear whats wrong. And then, when you REALLY need to know why this is, if you’ve ignored this until now you wont know why this weirdness exists.

Unless of course you read this post 😛

Implementing the Factory pattern in Xojo

When using the “factory” pattern you should only be able to get a valid instance from the factory and NO other way. Thats kind of the point of the pattern – to reduce the number of points at which instances can be created. Normally in Xojo you might have a module with a method that can create instances, and its the only one allowed to do this. The constructors for the classes the factory method can create should be protected or private so they cannot be directly invoked using New outside the module.

Usually it might look something like (note this code will not compile)

Module People

  Public Interface IPerson
      Public Function GetName() as string
  End Interface

  Public Class Villager
    Implements IPerson
      Public Function GetName() as string
        return "Village Person"
      End Function

      Protected Sub Constructor()
      End Sub
  End Class

  Public Class CityPerson 
    Implements IPerson
      
      Public Function GetName() as string
        return "City Person";
      End Function

      Protected Sub Constructor()
      End Sub
  End Class

  Public Enum PersonType
    Rural
    Urban
  End Enum

  Public Function GetPerson(type as PersonType) as IPerson
  
    select case type
    case PersonType.Rural
      return new Villager()
    case PersonType.Urban
      return new CityPerson()
    else
        raise new UnsupportedOperationException
    end select
  End Function

End Module

An alternative would be to not use an Interface for IPerson but to make it a base class – they end result is similar.

But, you cant do either in Xojo. At least not quite like my code above shows.

If you have a factory method in the module it cannot invoke their constructors. They are only callable by items in the class hierarchy. It has no special means to access the private or protected constructors of the classes it contains.

So you cant easily restrict construction to ONLY the factory method since what you really need is a “module” or “namespace” scope. And that doesn’t exist.

What you need to do is create an INTERFACE for the various classes in the namespace you intend to expose and make the classes in your namespace implement these interfaces. In addition you need to make the interfaces PUBLIC so they can be used outside the module. As well you need to make the classes that implement the interfaces PRIVATE so you can’t actually try and instantiate them outside the module. This has the unfortunate side effect of making it so you can only use the classes in the module via their interfaces. Remember what we really wanted was just to make it so the only legal way to get an instance was to use the factory.

Note that by having to do everything via an interface this means that “properties” are exposed by pairs of getter / setter methods. Fortunately in Xojo this has little semantic impact except that you have to write the code for it.

All code not in the module must use the interfaces as that’s all you have available.

But now because the classes in the module are PRIVATE you can put as many public constructors on them as you desire. They won’t be callable by anything outside of the module so instances cannot be created in ANY way except by calling the factory method in the module.

Module scope would help reduce this work needed to implement the Factory Pattern by making it possible to implement the module’s classes with “module” scoped constructors. This way you could have the factory return any of the parent or subclass instances and you could skip all the interfaces.

A sample of the initial implementation that doesnt work and the fixed version is here