"Class Modules" (Create Instances of a Module)
Posted: Wed Nov 25, 2015 10:52 am
Context: Lunasole's post inspired me to create a separate thread so that his great suggestion doesn't get buried:
I just tried to think of a PB-close syntax for this exiting new feature (only one new keyword and function!):
I think Lunasole's idea and my proposed syntax is quite neat and perfectly fits in the existing world of PureBasic. What do you think?
(And please, because I know it often leads to a heated debate, let's keep this topic focused on this particular concept/suggestion of "class modules". General thoughts on object-orientated programming can be posted elsewhere. Thanks.)
It's funny because when "basic OOP" was first mentioned I had the exact same idea in mind: Why not simply allow multiple instances of a module? (When I first looked at PB's modules I was kind of bummed because I actually expected it. It still feels strange not being able to use a separate instance.)Lunasole wrote:[...] In other words, those classes in VB6 are exactly just like modules in PB, but they also allow to dynamically create and destroy multiple instances of them each separated from others.
I just tried to think of a PB-close syntax for this exiting new feature (only one new keyword and function!):
Code: Select all
; It's surprisingly similar to existing module concepts, the handling of lists/arrays/maps and structured variables:
; 0. Regular declaration and implemenation of module "MyModule"
; [...]
; 1. Definition and instantiation
Define.MyModule NewModule module1, NewModule module2
; 2. As soon as NewModule is called the module's code gets executed (separately) to be able to simulate a constructor call
; 3.1. Accessing a particular module instance
module1::SetString("abc")
module2::SetString("def")
; 3.2. Some syntactical sugar
With module1
Debug ::GetString() ; Outputs "abc" (not "def"), great!
EndWith
; 4. Destruction
FreeModule(module1, @MyModule::MyDestroy())
FreeModule(module2) ; Automatically calls MyModule::Destroy() of that instance
; Of course known usage works as before:
; Alternative A: As another instance
MyModule::SetString("xxx")
Debug MyModule::GetString() ; Outputs "xxx"
Debug module1::GetString() ; Still outputs "abc"
; Alternative B: As some kind of "static module" (more intuitive?)
MyModule::SetString("xxx")
Debug MyModule::GetString() ; Outputs "xxx"
Debug module1::GetString() ; Outputs "xxx" as well (like module2)
(And please, because I know it often leads to a heated debate, let's keep this topic focused on this particular concept/suggestion of "class modules". General thoughts on object-orientated programming can be posted elsewhere. Thanks.)