Class Interfaces: An interesting feature

This may not be new to some of you, but even though I use class interfaces quite a lot, I didn’t know about this feature. What you can do is tell a class’s method which method of an interface it actually implements. Here’s a simplyfied example:

In a project I have two classes

Class Person
  Sub Walk(fromA As Location, toB As Location)
  End Sub
End Class

Class Car
  Sub Drive(fromA As Location, toB As Location)
  End Sub
End Class

Up until now both classes were used in totally different parts of my program, there was not “touch point” between them. Today I decided it would be nice, if I could move all persons and cars in one go. So I created a class interface

Class Interface CanMove
  Sub Move(fromA As Location, toB As Location)
  End Sub
End Class Interface

Until today I would have either re-named Person.Walk and Car.Drive and all calls to them to Person.Move and Car.Move respectively. Or, more likely, I would’ve added a Move method to both classes, that then would call the existing Walk or Drive methods.

But there’s a better way. In the Navigator right-click on the definition of Person.Walk and select Show Implements from the context menu. This will add a new field Implements in the inspector. Enter CanMove.Move into that field. Do the same for Car.Drive.

Now a Person can still Walk and a Car can still Drive, but you can also do this:

dim joe as new Person
dim tim as new Person

dim ferrari as new Car
dim porsche as new Car

dim movables() As CanMove

for each movable As CanMove in movables
  movable.Move(San_Francisco, Cupertino)
next movable

If movable is a person, Person.Walk will be called, and if it is a car, Car.Drive. Neat.

I only wish there was some kind of indicator that a method implements an interface method in the Navigator. Either some badge on the method’s icon, like it is done if a method has an attribute attached to it, or in the method’s name, e.g. Walk -> CanMove.Move (which I’d prefer).

1 Like

They’ll probably not put a badge on it as those poor rows are getting horribly busy if you mark something private, and add attributes and make it external :stuck_out_tongue:
Although they could update the tooltip that is shown when you hover over a row with this

This feature is the only way you can handle the case where two interfaces define a method with the same name but you want to have two separate implementations

Suppose you have

interface ISomething 
       sub doSomething()

Interface ISomething2 
    sub doSomething()

class MyImpl 
   implements ISomething, ISomething2 
       // now what ???????

but with the capability you can do something like

  class MyImpl 
   implements ISomething, ISomething2 
       sub doSomethingOne() implements ISomething.doSomething
       end sub

       sub doSomethingTwo() implements ISomething2.doSomething
       end sub

othewise you are really stuck


Yes, that’s the use case from the User’s Guide (which I somehow never saw before today :pensive:). But my case was a little different, in that it describes a way to implement interfaces in existing classes without changing their API. Of course, in the end it’s the same technique from a slightly different point of view…

It is the same technique used in an unconventional, but not unintended, way :slight_smile:
In your case you should still be able to use either API depending on what kind of reference you have
If its a CanMove then you call “Move”
And it its a Car you can call either Drive, without a cast, or by casting to a CanMove you can call Move

That said I might have named the interface Moveable but … :slight_smile:

That’s what I was trying to describe.

Well, you’re the native speaker from the two of us :smile:

Hey name you interfaces whatever makes sense to you - not me

I know some use a set of prefixes
i is an interface
c is a class name - includes subclasses

I dont recall what bob used but I think he had guidelines that had suggestions for naming classes and interfaces

In my not insubstantial years of programming, I’ve never used interfaces.

Can someone explain what they’re for? In the example, I would have just had Person and car derive from the same subclass, and used a Move function in each.

I’ve done a bit of googling, and while I can find lots about how to implement interfaces, I can’t find out much about WHY. No offence, but it seems like it’s for fixing issues when classes weren’t designed properly at the start. However, now getting into TS, I see this topic coming up again. I’m sure there’s more to it than that, can someone help me understand the need for them?

There area couple in Xojo already

Readable is one

The upside to this is you can write a method (or class) that uses a Readable item and it can be any one of the things that implements readable and you dont care
Readable guarantees that what ever instance it is you CAN call READ and EndOfFile

Suppose you want to log incoming data
You could create a class, Logger, that reads from a file.

Class logger
        fileToReadFrom as Folderitem

       Sub Constructor( f as folderitem)
              self.fileToReadFrom = f
       End Sub

       < more methods here for logging>

Oh but what if you want to log incoming data from a IPCSocket ?
new subclass ?

OR just make your Logger take a Readable instance - ojo already has several objects that implement this interface

Class logger
        thingToReadFrom as Readable

       Sub Constructor( f as Readable )
              self.fileToReadFrom = f
       End Sub

       < more methods here for logging>

and now that constructor can be properly called with any one of BinaryStream, Serial, TCPSocket, TextInputStream

And your class can now handle incoming data from any of the built in classes that implement readable

And now, YOU can add a class of your own, that also implements Readable, and it too can be used for that constructor

1 Like

Ok, so it falls into the category of “things to use when you might re-use your code without re-compiling”…

It’s seems then that it’s benefit is for situations where you’re building something for others to expand on?

its useful in the code you write as well to let you NOT have to focus on the inner details of how classes do what they do and but just code to the API’s they present

It lets you abstract things a bit more

For instance, in my current app I have an interface called ProgressReporter
And I have several things that implement that interface

  1. a subclass of progresswheel
  2. a window with a progress bar
  3. a class that writes progress messages to the system debuglog

and in my code that I pass in one of the instances to I dont care which it is
They all adhere to the same api so I can pass one to the code that needs to report its progress and its blissfully unaware of how that occurs; because it doesnt need to know how it happens or anything
it just needs to call that api and the “progress reporter thing” will do whatever it needs to do

in my case the code is like

    Sub LongRunningTask( p as progressreporter )
    End Sub

and I can call it any one of

     dim w as new ProgressReportingWindow // this one implements ProgressReporter
     LongRunningTask( w )


      // myProgreessControl is an instance of my subclass of progresswheel
      // that subclass implements ProgressReporter
     dim c as ProgressReporter = ProgressReporter( myProgreessControl )
     LongRunningTask( c )


      dim pw as new ProgresWriter( f ) // progressWriter implements ProgressReporter & writes to a file
     LongRunningTask( pw )

Thanks Norm. Haven’t gotten the “aha” moment yet, but I’ll study some more to see if I can find a situation that this would be helpful.
Likely since I’ve been doing without for so many years, it never comes to mind as a solution for a problem. I have to find the “problem” in my code that this would help with.

Its not always that you need them - but when you do you realize it and its immensely helpful

One of the most useful I’ve run into is “Serializable” where you might have a pile of different classes in different hierarchies that you want to be able to write to some other format (disk etc)

And since all these classes aren’t necessarily from anything you can jam together in a meaningful way to have a common ancestor its nice to be able to slap an interface on them and then you can make whatever you want serializable

Gotcha. I used Serialization tons in VB.NET, but I always created my classes from a central root class so they could be serialized with the same method.

I see that there could be some uses, and I appreciate you explaining them. Remains to be seen whether I will find a need.

Right and thats not unusual
But suppose you want to serialize the state of a UI where Window and Control arent and cannot be derived from the same class since you cant insert anything into Xojo’s class hierarchy

But you could make all your Windows serializable and, with a bit or work, you could make any controls on that window also serializable.
For controls you’d have to subclass them and add the interface to the subclass then only use subclasses on your layouts when you wanted things to be serializable. You could subclass Window, implement Serializable on that new class, then make all your windows inherit from this one & voila they are all now serializable (you probably still have to write code but …)

But its doable

1 Like

I like interfaces because they force you to write the implementation of every method they define.

By way of example, let’s say I have a map of tiles. Each tile is expected to draw itself when requested, being passed a Graphics instance to do so. I could just make a class like so:

Class Tile
  Public Method Render(g As Graphics)
    // Drawing code goes here.
  End Method
End Class

This is all well and good but let’s say I make a subclass of Tile because I want a map that draws them differently. Unless I remember to override Render(), the superclass Render()method will be called and this might not draw how I want:

Class SuperTile Implements Renderable
  Method Render(g)
    // This method is added to the class by the IDE.
  End Method
End Class


Class SuperTile Inherits Tile
  // Notice I forget to override Render like a fool.
End Class

Var s As New SuperTile
// Some code...

s.Render(g) // This calls `Tile.Render()` as there is no `SuperTile.Render()` implementation.

Contrast this with using an interface. I define one called Renderable:

Interface Renderable
  Method Render(g As Graphics)
    // You can't put code here because it's an interface but classes **must**.
  End Method
End Interface

Now I can create my SuperTile class and make it implement the Renderable interface. The compiler will ensure that I write the Render() method for that class. The IDE will also helpfully populate the methods for me.

The compiler will just make sure that the method, with that signature, exists
You can still leave it empty :stuck_out_tongue:

True, although there is a checkbox in the IDE when you implement an interface that will add Pragma Error "Implement this!" (or something similar) to each one which helps a little.

Very tue - thats a “crutch” for us folks who forget :stuck_out_tongue:

It really depends on how you use interfaces
IF you happen to have an interface that a super class implements then you may not be better off as subclasses arent implementing the interface directly
IF they do thats a whole ton of work for things that may better be done in the super and then overridden in the sub

Not sure there is a way to say “oh you should always do X” as some kind of best practice