When writing a method, where do you place it? The object oriented approach says: Put it in a class.
When you want to execute the method, how do you do it? First, you need to instantiate the class by making an object. Then you can call the method by referencing the object. But then what do you do with the object? Do you keep it, so you can call the method at a later time? DataFlex does not have a garbage collector, so if it's not going to be used again, you need to think about destroying the object after using it.
Why not write a global method? For a simple method that does not have "state" (it is determined solely by its parameters), you could reason that it might as well be written as a global method. And in DataFlex, that does often seem to be the pragmatic way of doing it.
The downside is that you will then miss out on a number of object oriented features.
- When debugging, the call stack will not have a useful object to present.
- When writing unit tests, it is sometimes useful to replace objects with "dummies" (also called mocks, stubs, or fakes) - this can easily be done by changing the object reference; not quite so easily with global methods.
- Changing behavior by subclassing is not feasible with global methods.
If the method is going to be called many times, from various places in the code, we sometimes create a single instance of the object, referencing it with a global handle variable. This is a reasonable compromise - we get the benefits of object orientation, and it is trivial to call the method. But you still need to instantiate the object and define the global variable. And you need to carefully keep track of where you put it, because if you try to define it twice, the compiler will complain.
So what I would really prefer is to be able to define a static class. A static class cannot be instantiated - so when we call its methods, we reference the class itself, instead of an instantiated object.
Code example:
Code:
Class cUtilityClass Static is a cObject
Procedure DoSomethingUseful
//... or not...
End_Procedure
End_Class
Send DoSomethingUseful of cUtilityClass
OK, I'll stop writing now