Do you want a simplified way to use shared objects, following the classic object syntax and automatically calling use/end use when needed?
Fasten your seatbelts; here come the shared classes!
Shared classes creation & management
With 4D 20 R5, we added a new concept: Shared classes.
Shared classes can only be used to create shared objects and, as such, simplify their use. To create a shared class, you just need to add the shared keyword to its constructor:
//class SharedClass
shared Class constructor()
Shared classes can’t be used to create standard objects: every time you call new() to create a new object of this class, it will be a shared object.
Extension to class functions
The keyword shared can also be used for class functions, indicating that this function modifies the object. There’s no need to call use and end use inside the function, as they are automatically called when the function is called and exited. This is obviously valid for the singleton constructor.
shared Function myFunction()
This.attribute:="whatever"
Of course, you should take care when using the shared keyword for functions that don’t need it to avoid blocking other processes that try to use the object.
Properly using shared classes and functions should allow you to manipulate your shared objects as if they were normal objects, simplifying your code.
Inheritance Considerations
One last point you need to be careful about is that Non-shared classes can inherit from shared classes, but shared classes can’t inherit from non-shared classes. So, plan your object model accordingly.
Example
Let’s say you have a long calculation to perform, and you’d prefer to use a worker to avoid blocking your important processes. But, obviously, you need to retrieve the calculation result at some point. Let’s use this CalculationResult class:
// class CalculationResult
shared Class constructor()
This.isFinished:=False
Function makeCalculation()
...
This.finished:=True
shared Function set finished($finished : Boolean)
This.isFinished:=$finished
shared Function get finished()->$finished : Boolean
$finished:=This.isFinished
To use it, you can just do:
$calculation:=cs.CalculationResult.new()
CALL WORKER("AnyWorker"; Formula($calculation.makeCalculation()))
While (Not($calculation.isFinished))
//Code that will be executed while the calculation is in progress
End while
I hope the shared classes will help you use shared objects across your application. If you have any questions, don’t hesitate to bring them to the 4D forum.