Yeah. 42. I know that answer 🙂
So far what we have is
Module PictureMimicry
Class MyPicture
Function MyGraphics() as MyGraphics
End Function
End Class
Class MyGraphics
End Class
End Module
And now, for the answer, on how to make it so we can make the compiler catch the attempts to create a new MyGraphics.
First we ABSOLUTELY put a protected constructor on MyGraphics. That will prevent EVERY attempt to create a new MyGraphics with the NEW operator. But now how does MyPicture create one to return it ?
It doesnt 🙂
Remember we can set the SCOPE of items in a way that they can ONLY be used by code in the module. And since Xojo IS an OO language and support inheritance and polymorphism we can use that to our advantage.
In such a language every subclass of a class IS also its parent class type.
What we’re going to do is add a private subclass whose sole purpose is to allow us to create new instances. And we can return that subclass and the code outside the module will ONLY be able to use it as the parent class type because the subclass type is not know outside he module.
The end result is this set up
Module PictureMimicry
Class MyPicture
Function MyGraphics() as MyGraphics
return new MyGraphicsSubclass
End Function
End Class
Class MyGraphics
Protected Sub Constructor()
End Sub
End Class
Private Class MyGraphicsSubclass
Inherits MyGraphics
Public Sub Constructor()
End Sub
End Class
End Module
and now in the App Open event from the previous post
dim p as MyPicture
dim g as MyGraphics
p = new MyPicture
g = new MyGraphics
The compiler will complain about the last line not being permitted. Exactly as we wanted.
And this code
Dim p As MyPicture
Dim g As MyGraphics
p = New MyPicture
g = p.MyGraphics
Works exactly as we intended.
You can now freely add methods to MyGraphics and MyPicture and know that none of your own code can accidentally create a MyGraphics in a way that you did not intend to permit.
Code in a way the compiler can help you write code the way you intended it to work. Not just by convention or habit. But by design.
Code for your own safety and sanity. Get the compiler to help you when it can.
Isn’t that what I posted as “my” solution as well?
I definitely need to improve how to express my thoughts 😉
Pretty much _ I just didnt say so because then whats the point of my follow up for everyone else ? 😛
😀