B4J Question What is the B4 equivalent of a Xojo Interface or a Swift Protocol?

Markus Winter

Member
Licensed User
What I am missing is a high-level introduction for people coming from other languages.

Even something like a simple table showing what is equivalent or can be used instead of would be helpful, eg

Swift - Xojo - B4
Var - Dim / Var - Dim
Let - Const - Const
Protocol - Interface - ???

Does this exist somewhere, and I'm just too blind to find it?

And what is the B4 equivalent to a Protocol / Interface? I was looking through the booklets but could not find whether B4 has something like Protocols or Interfaces.
 

Computersmith64

Well-Known Member
Licensed User
Longtime User
Thanks for the welcome. I'm still undecided if I go for B4 or jump straight to Java. B4 should be easier, but Java is more widespread and potentially more powerful (though I heard you can use Java and ObjC code in B4). My problem is that currently I have no feeling for where the strengths and limitations of B4 are - which is something you need to know when you make a decision.
Hi Markus - I've been using B4X (mainly B4A, but also some B4J & B4R) for almost 10 years & while I initially started with B4A as part of my first foray into mobile app development, I now find I almost exclusively use Android Studio (Kotlin) & Xcode (Swift) for new development. I even used Unity for one of my apps. I started using Xcode before Erel brought out B4i & when B4i did become available I had learned enough (Obj-C at the time) such that it didn't really make sense to switch.

The main reason I've moved away from B4A is because I've found its lack of native support for Android SDKs to be very limiting in some cases. This is something I've commented on a few times over the years as it can be very frustrating to get halfway through a project only to find that some functionality you need isn't available. Maybe the apps I develop are atypical or something, but in the end I found it happening more often than not. To give you a couple of examples:

* Early on in the process of developing my first app (a game), I wanted to take advantage of Google Play Games Services for leaderboards, achievements, etc... At that time, one of the B4X community members had written a library with limited support for GPGS - but enough for me to do what I wanted. When I wanted to take that further & add multiplayer, there was nothing available. It did get implemented in a later update to the GPGS library, however that library hasn't been updated for a long time since then & I would guess is now almost non-functioning at any useful level.

* I also have several projects that use Firebase Firestore. There was briefly a B4A library available for Firestore, however it no longer exists.

There are ways around this - like writing your own libraries (I've dabbled, but never really got far) or using JavaObject to directly access SDK functions - but neither of these options is a "quick answer" (especially for a complex SDK), so for me it was a better use of my time to just teach myself Swift & Kotlin & then have access to all the functionality available on Android & iOS platforms straight out of the box. If you're still in the undecided stage, I'd advise you to think about what functionality you're going to need in your apps & then search the forums to see if you're going to be able to achieve what you want with what's available. Erel is always adding new features & functionality to the range of B4X tools, but not everyone's priorities & wish lists are the same - so that one functionality you need might prove to be elusive. :)

I'd have to say that one area B4A really beat AS hands down in the early days was in putting layouts together, but the later versions of AS are much easier to use & I don't really see that B4A advantage any more. Same with Xcode (although Interface Builder is still pretty crap) & now you have SwiftUI as an option too.

Don't get me wrong - I think B4X tools are great in certain circumstances (I love B4R for my ESP8266 projects), but like many situations you need to pick the best tool to suit your needs. I mean you wouldn't use a shifter (adjustable wrench) to undo the wheel nuts on your car, would you? ;)

- Colin.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
But Erel's answer to look at Sophisticated sorting with B4XComparatorSort has me puzzled as it has nothing to do with what I asked. Same happened with his answer to my other question in this thread, so I guess he is currently very distracted / stressed … which given the situation in the outside World would be very understandable.
I gave it as an example of duck typing. Go over the example and you will see that you implement something that is very similar to interfaces in many other programming languages. Just without the interface declaration.
 
Upvote 0

ivanomonti

Expert
Licensed User
Longtime User
@Markus Winter in tanti anni che ho usato realbasic poi realstudio e ora xojo non ricordo il tuo nick name, cmq in tutta questa discussione chiedi cosa ?

Per le cose complicate ti conviene scrivere nella sezione domanda inglesedove anche @Erel fondatore di questo strumento (gratuito tra l'altro) può darti una possibile, cosa che tengo a dirtichere e lecito e rispondere e cortesia. quindi non dire che il gruppo italiano non e gentile, si è scorbutico :) e lo dico io che ho rotto le palle un anno fa a ritmo di moglie scassamaroni (suocera) ma è un bel gruppo .

Volevo solo dirti di non fermarti alle apparenze, io ho abbandonato Xojo quando vidi questo, perchè non aveva un bug come quelli di xojo che ha portato avanti bug per anni interi dove ancora oggi sono presenti. con b4x mi sono divertito e ho assegnato in piccoli strumenti e grandi lavori senza troppa fatica, devi solo entrare senza pretese e fartelo tuo, ho torna usare ad xojo o ipercard o filemaker o ... insomma ci siamo capiti. ma ricordati che la prima differenza sta nelle licenze b4x costa una donazione o gratis tutti gli altri non meno di $$$,$$$ ;-)

non serve la risposta era solo un modo per dire al gruppo Italia che sono tornato a rompere i maroni :)
 
Upvote 0

Markus Winter

Member
Licensed User
n tanti anni che …

DeepL translation:

In the many years I have been using realbasic then realstudio and now xojo I don't remember your nick name,
I don't have a nickname - I was Markus Winter on the REALbasic forum, on the Xojo forum, on the IfNotNil forum, and on here, because I believe that if you have something to say then you should (a) tell it to people's faces, (b) put your name to it, and (c) stand by what you are saying.

however in this whole discussion you ask what?
I would have thought the topic was quite clear … :rolleyes:

… but as topics have a way of doing: they drift and people ask questions.

For complicated things it's better to write in the English question section where even @Erel founder of this tool (free by the way) can give you a possible, what I want to tell you is lawful and answer and courtesy. So do not say that the Italian group is not nice, it is grumpy :) and I say that I broke my balls a year ago to the rhythm of wife scassamaroni (mother-in-law) but it is a good group.
Germans think they are straight-talking, other nationalities think we are rude. There is a saying that nicely encapsulates that: "The English are too polite to be honest, and the Germans are too honest to be polite".

Sometimes that gets me into trouble, sometimes I make a mistake - and if I do then I also apologise publicly and don't do it in secret in a private message to "keep face".

There were even people who thought they can bribe or threaten me - they can't.

So let me say this straight: You have the right to disagree, and you have the right to voice your own opinion.

But don't tell me what I can and can not do or say - because quite simply, you do not have the right to do that.

If you want to be offended by that, then that is your prerogative.

It is also the truth.

no need for an answer it was just a way to tell the Italy group that I'm back to busting my balls
I think they moved over there … ➡️
 
Upvote 0

ThorstenStueker

Member
Licensed User
Sure do - it's your fault I'm pestering people here … 😁

Thanks for the welcome. I'm still undecided if I go for B4 or jump straight to Java. B4 should be easier, but Java is more widespread and potentially more powerful (though I heard you can use Java and ObjC code in B4). My problem is that currently I have no feeling for where the strengths and limitations of B4 are - which is something you need to know when you make a decision.

So I'm going to ask a lot of stupid questions, and as I like teaching might write some tutorials or even a book aimed at beginners like me at some point - and I find comparisons between languages useful as each have their strengths and weaknesses, and the comparisons can teach you a LOT about the language that you might never realise otherwise (eg looking at Swift has changed my whole perspective regarding Xojo - the MapKit alone is as big as the whole of Xojo).

As I learn best when trying to solve a problem, I might just start with one of my many pet ideas and start digging into it.

P.S. Markus with a k - the German spelling ;)
And I thought it is also a bit my fault....:)
:)
 
Upvote 0

Markus Winter

Member
Licensed User
P.S. I'm currently on my fourth ban from the Xojo forums for being too critical. This time pretty much because I wrote a critical article in xDev where I
  • summarised the history of Xojo
  • analysed the effect that the introduction of the Rapid Release Model had by looking at feedback cases (eg the appearance of emergency releases to fix showstopper bugs that should never have been in a release)
Fig 2 Effects of Rapid Release Model.png
  • showed that more bugs were introduced than were fixed in each release by analysing the feedback cases
Fig 5 Feedback cases new vs done.png
  • and while many Pro users have left the number of new users had dropped massively (as judged by statements in Xojo's press release on the number of users, the number of registered forum users, and Google trends)
Fig 4 Xojo forum user stats.png


Google trends: REALbasic in Red, Xojo in blue
Fig 3 Google Trends REALbasic and Xojo worldwide.png

But I was not only critical, but importantly in my article I also gave a way out of the mess Xojo got itself in to.

So to summarise: I will just be as open and critical with B4X - because I think that is the only way to improve a tool.

And from what I have seen Erel (unlike Geoff) actually appreciates and listens to good arguments.
 
Upvote 0

MicroDrie

Well-Known Member
Licensed User
Sorry but with the mentioned balls and the Italian rhythm of wife scassamaroni (mother-in-law) 🤫 in this post I lost 🤔 the connection with the subject of this post "Protocols of Interfaces in B4X" even after three great 😍 holidays times in Italy and a mother-in-law who knows nothing about computers 😉.
 
Upvote 0

Markus Winter

Member
Licensed User
I gave it as an example of duck typing. Go over the example and you will see that you implement something that is very similar to interfaces in many other programming languages. Just without the interface declaration.
My apologies if I misunderstood, but on the webpage you simply have a global method defined for comparing objects, and have as an example a string sort OR a person sort in your code. There is no composition shown so of course I couldn't see any.

I downloaded the example and on trying to run the example I get:

B4J Version: 9.30
Parsing code. Error
Error parsing program.
Error description: Unknown type: b4xcomparatorsort
Are you missing a library reference?

Ah - silly me. Works now. Needed the updated B4XCollections.b4xlib. Would have been useful if
B4XCollections v1.13 includes a new sorting feature named B4XComparatorSort.
instead of having me search for it would have included a link
B4XCollections v1.13 includes a new sorting feature named B4XComparatorSort.
One mantra of mine: don't make thousands of people do the same thing (like searching for the updated library) when you can save that waste of time by doing it just once.

As an example: every second that Microsoft Office could be quicker would save about 32 YEARS of user time!

Looking at the code example the composition is actually not shown in the code, but is with the method in the library - so it is not obvious to a beginner what is going on. I think it would be better to have more comments and two different sorts implemented (eg both the string sort and person sort from the website) to demonstrate composition.

What I am still unclear on: with Interfaces /protocols different classes implementing the interface are now all OF THAT INTERFACE TYPE (in the same way that all different persons implementing the CanPlayGuitar interface are now guitar players), so all members of a collection containing different objects like a car, a person, a building, a festival, an accident, etc that implement the MapLocation interface / protocol can be shown on a map with (pseudo-code):

B4X:
for each obj as object in myCollection
if obj is a MapLocation then
obj.showOnMap
next

I used to use that sort of thing a LOT (eg have all my classes implement the CanDrawItself interface for display in a table or on a Canvas), and in most cases where people use a subclass they would be better off using an interface.

Is something like this possible with the way B4x uses composition?
 
Last edited:
Upvote 0

ivanomonti

Expert
Licensed User
Longtime User
Non ho un nickname - ero Markus Winter sul forum REALbasic, sul forum Xojo, sul forum IfNotNil e qui, perché che se hai qualcosa da dire dovrebbe (a) dirlo ai volti delle persone, (b) metteteci il tuo nome e (c ) restate fedeli a ciò che dite.
Essere critico va bene purchè sia costruttivo, quando metti un riferimento tipo "interfaccia CanDrawItself" e non metti un codice e come dire "la signora pinco pallo", cioè il nulla :) per questo ho citato la "suocera", parli molto dicendo di essere più semplici ma nelle tue parole non vedo semplicità ma ma non del codice da porre in esame, grafici andamento google che a mio dire non servono se non per scrivere o additare o analisi flusso di interesse, ma non serve allo sviluppo, parli schietto , ma a mio dire non utile al tuo obiettivo se non per far notare qualcosa che non ho capito io e credo anche altri. .

Ora detto questo credo sia più opportuno che tu inserisca un'idea di quello che vuoi ottenere, che si abbia il modo di darti la soluzione (sempre richieste se esiste), ho trovare altre alternative, credo che @Erel ha tutto il piacere di leggere e di implementare cose nuove ma non così se è bravo come DIO a fare miracoli, magari ci sono altri membri che possono trovare ed osare qualche utile soluzione Scusa se mi permetto, bisogna anche essere capaci di criticare dando degli esempi concreti e non solo, perchè il tuo mondo non è per tutti...(le tue idee) Scrivi e metti esempi concreti e magari salta fuori la tua risoluzione .
 
Upvote 0

alwaysbusy

Expert
Licensed User
Longtime User
With Composition it's sometimes easier to think in a way of HAS-A, opposed to inheritance IS-A. Like, a car has an engine, a person doesn't.
You can still check if a object is a car or a person with the Is keyword. We can use CallSub/CallSub2/CallSub3 to find out it an object has something.

Here is a mixed example where I check if the object in the Map is a car or a person. No matter what it is, we check if it has an engine. If so we start the engine.

engine:
B4X:
Sub Class_Globals
   
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize
   
End Sub

public Sub StartEngine()
    Log("Engine started")
End Sub

car (which has an engine):
B4X:
Sub Class_Globals
    Dim name As String
    Dim myEngine As Engine
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(n As String)
    name = n
    myEngine.Initialize
End Sub

public Sub TypeOfCar()
    Log(name)
End Sub

public Sub SayHello()
    Log("Hello, I'm a car")
End Sub

public Sub GetEngine() As Engine
    Return myEngine
End Sub

person:
B4X:
Sub Class_Globals
    Dim name As String       
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(n As String)
    name = n   
End Sub

public Sub SayHello()
    Log("Hello, I'm a person")
End Sub

public Sub WhatsMyName()
    Log(name)
End Sub

main:
B4X:
Sub Process_Globals
    Dim m As Map
End Sub

Sub AppStart (Args() As String)
    m.Initialize
   
    Dim George As Person
    George.Initialize("George")
   
    Dim Honda As Car
    Honda.Initialize("Honda")
   
    m.Put("George", George)
    m.Put("Honda", Honda)   
               
    For Each key As String In m.Keys
        Dim obj As Object = m.Get(key)
       
        ' for a common method, we do not need to cast it
        CallSub(obj, "SayHello")
       
        ' for a method specific for that class we can cast it if one likes to
        If obj Is Person Then
            Dim pers As Person = obj
            pers.WhatsMyName
        End If
        If obj Is Car Then
            Dim ca As Car = obj
            ca.TypeOfCar           
        End If   

       ' this would also work      
        If obj Is Person Then
            CallSub(obj, "WhatsMyName")
        End If
        If obj Is Car Then
            CallSub(obj, "TypeOfCar")           
        End If    
       
        ' if the class has an engine. If 'GetEngine' does not exists (like with a person), Eng will be null.
        Dim Eng As Engine = CallSub(obj, "GetEngine")
        If Eng <> Null Then
            ' the object has an engine, so start it
            Eng.StartEngine
        End If
    Next
End Sub

It is all just example to show the possibilities. Normally, if we know it is a car, we could as well just start its engine:
B4X:
If obj Is Car Then
      Dim ca As Car = obj
      ca.myEngine.StartEngine           
End If

To go back to your example, it would be something like this:
B4X:
For each key as String in myCollection.Keys
     Dim obj as Object = myCollection.get(Key)
     If obj is MapLocation then
         Dim ml as MapCollection = Obj
         ml.showOnMap
     End If
Next

 ' or even, as it will only run the mehod showOnMap if it exists
For each key as String in myCollection.Keys
     Dim obj as Object = myCollection.get(Key)
     CallSub(obj, "showOnMap")
Next

Alwaysbusy
 
Last edited:
Upvote 0

MicroDrie

Well-Known Member
Licensed User
Ah - silly me. Works now. Needed the updated B4XCollections.b4xlib. Would have been useful if
B4XCollections v1.13 includes a new sorting feature named B4XComparatorSort.
instead of having me search for it would have included a link
B4XCollections v1.13 includes a new sorting feature named B4XComparatorSort.

A nice support of the IDE is that the latest version number is how a simple warning is given that it is time to update your library. The difference between the 2.53 and 2.54 version is a sign that my version 2.53 must be updated to the newer version 2.54 by clicking on the blue 2.54 link to the latest version.

1648544897124.png
 
Upvote 0

ivanomonti

Expert
Licensed User
Longtime User
Forza, fai parte del forum da dieci anni. Sicuramente capisci che questa è la parte inglese del forum.
certo che lo so ma volevo una critica, poi con il tasto dx scegli la lingua che più di piace ;-)
of course I know but I wanted a criticism, then with the right button choose the language you like best ;-)
natürlich weiß ich aber ich wollte eine kritik, dann wähle mit dem rechten knopf die sprache die dir am besten gefällt ;-)
 
Upvote 0

ThorstenStueker

Member
Licensed User
even after three great 😍 holidays times in Italy and a mother-in-law who knows nothing about comput
In my understanding he wanted to show why he needs to go away from Xojo and wants to move to B4x. Yes, it is a weird way to do it but...it is like it is. We can support to help ro find the needed connections to have the needed entrance. I believe that critics never helping when there is no solution.
 
Upvote 0
Top