Does every Class we create in Delphi need to have destructor? - class

When I create my custom Class in Delphi Application I use standard procedure:
TCustomClass = Class
private
var1,var2 : integer/string/Real/Boolean...
procedure P1...
function F1...
public
constructor Create;
end;
...
CustomClass := TCustomClass.create;
I want to know do I always have to also create Destructor procedure or are resources automatically free when application closes?
I always use Application as owner, rarely Self or Nil and I don't remember I saw anyone declaring Destructor on classes I saw on Internet, except for one when someone used pointers.
Is the logic behind destructor same in Delphi as in C++ as described in this question:
Should every class have a virtual destructor?
Thanks in advance.
EDIT1:
As Free Consulting mentioned I forgot to say that one of the variables might be TBitmap type

It only needs to have a destructor if you need to clean up something, like allocated memory. For example, if you have used TClassname.Create(...) in the constructor, you need to free in the destructor method.
Of course there can be many different reasons to need a destructor (all the way up to informing the user that his data is about to get wiped), but this is the most common one.

Related

Is it possible to implement a module that is not a WPF module (a standard class library, no screens)?

I am developing a modular WPF application with Prism in .Net Core 5.0 (using MVVM, DryIoc) and I would like to have a module that is not a WPF module, i.e., a module with functionality that can be used by any other module. I don't want any project reference, because I want to keep the loosely coupled idea of the modules.
My first question is: is it conceptually correct? Or is it mandatory that a module has a screen? I guess it should be ok.
The second and more important (for me) is, what would be the best way to create the instance?
This is the project (I know I should review the names in this project):
HotfixSearcher is the main class, the one I need to get instantiated. In this class, for example, I subscribe to some events.
And this is the class that implements the IModule interface (the module class):
namespace SearchHotfix.Library
{
public class HotfixSearcherModule : IModule
{
public HotfixSearcherModule()
{
}
public void OnInitialized(IContainerProvider containerProvider)
{
//Create Searcher instance
var searcher = containerProvider.Resolve<IHotfixSearcher>();
}
public void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IHotfixSearcher, HotfixSearcher>();
}
}
}
That is the only way I found to get the class instantiated, but I am not a hundred per cent comfortable with creating an instance that is not used, I think it does not make much sense.
For modules that have screens, the instances get created when navigating to them using the RequestNavigate method:
_regionManager.RequestNavigate(RegionNames.ContentRegion, "ContentView");
But since this is only a library with no screens, I can't find any other way to get this instantiated.
According to Prism documentation, subscribing to an event shoud be enough but I tried doing that from within my main class HotfixSearcher but it does not work (breakpoints on constructor or on the event handler of the event to which I subscribe are never hit).
When I do this way, instead, the instance is created, I hit the constructor breakpoint, and obviously the instance is subscribed to the event since it is done in the constructor.
To sum up, is there a way to get rid of that var searcher = containerProvider.Resolve<IHotfixSearcher>(); and a better way to achieve this?
Thanks in advance!
Or is it mandatory that a module has a screen?
No, of course not, modules have nothing to do with views or view models. They are just a set of registrations with the container.
what would be the best way to create the instance?
Let the container do the work. Normally, you have (at least) one assembly that only contains public interfaces (and the associated enums), but no modules. You reference that from the module and register the module's implementations of the relevant interfaces withing the module's Initialize method. Some other module (or the main app) can then have classes that get the interfaces as constructor parameters, and the container will resolve (i.e. create) the concrete types registered in the module, although they are internal or even private and completely unknown outside the module.
This is as loose a coupling as it gets if you don't want to sacrifice strong typing.
is there a way to get rid of that var searcher = containerProvider.Resolve<IHotfixSearcher>(); and a better way to achieve this?
You can skip the var searcher = part :-) But if the HotfixSearcher is never injected anywhere, it won't be created unless you do it yourself. OnInitialized is the perfect spot for this, because it runs after all modules had their chance to RegisterTypes so all dependencies should be registered.
If HotfixSearcher is not meant to be injected, you can also drop IHotfixSearcher and resolve HotfixSearcher directly:
public void OnInitialized(IContainerProvider containerProvider)
{
containerProvider.Resolve<HotfixSearcher>();
}
I am not a hundred per cent comfortable with creating an instance that is not used, I think it does not make much sense.
It is used, I suppose, although not through calling one of its methods. It's used by sending it an event. That's just fine. Think of it like Task.Run - it's fine for the task to exist in seeming isolation, too.

Any way to trigger creation of a list of all classes in a hierarchy in Swift 4?

Edit: So far it looks like the answer to my question is, "You can't do that in Swift." I currently have a solution whereby the subclass names are listed in an array and I loop around and instantiate them to trigger the process I'm describing below. If this is the best that can be done, I'll switch it to a plist so that least it's externally defined. Another option would be to scan a directory and load all files found, then I would just need to make sure the compiler output for certain classes is put into that directory...
I'm looking for a way to do something that I've done in C++ a few times. Essentially, I want to build a series of concrete classes that implement a particular protocol, and I want to those classes to automatically register themselves such that I can obtain a list of all such classes. It's a classic Prototype pattern (see GoF book) with a twist.
Here's my approach in C++; perhaps you can give me some ideas for how to do this in Swift 4? (This code is grossly simplified, but it should demonstrate the technique.)
class Base {
private:
static set<Base*> allClasses;
Base(Base &); // never defined
protected:
Base() {
allClasses.put(this);
}
public:
static set<Base*> getAllClasses();
virtual Base* clone() = 0;
};
As you can see, every time a subclass is instantiated, a pointer to the object will be added to the static Base::allClasses by the base class constructor.
This means every class inherited from Base can follow a simple pattern and it will be registered in Base::allClasses. My application can then retrieve the list of registered objects and manipulate them as required (clone new ones, call getter/setter methods, etc).
class Derived: public Base {
private:
static Derived global; // force default constructor call
Derived() {
// initialize the properties...
}
Derived(Derived &d) {
// whatever is needed for cloning...
}
public:
virtual Derived* clone() {
return new Derived(this);
}
};
My main application can retrieve the list of objects and use it to create new objects of classes that it knows nothing about. The base class could have a getName() method that the application uses to populate a menu; now the menu automatically updates when new subclasses are created with no code changes anywhere else in the application. This is a very powerful pattern in terms of producing extensible, loosely coupled code...
I want to do something similar in Swift. However, it looks like Swift is similar to Java, in that it has some kind of runtime loader and the subclasses in this scheme (such as Derived) are not loaded because they're never referenced. And if they're not loaded, then the global variable never triggers the constructor call and the object isn't registered with the base class. Breakpoints in the subclass constructor shows that it's not being invoked.
Is there a way to do the above? My goal is to be able to add a new subclass and have the application automatically pick up the fact that the class exists without me having to edit a plist file or doing anything other than writing the code and building the app.
Thanks for reading this far — I'm sure this is a bit of a tricky question to comprehend (I've had difficulty in the past explaining it!).
I'm answering my own question; maybe it'll help someone else.
My goal is to auto initialize subclasses such that they can register with a central authority and allow the application to retrieve a list of all such classes. As I put in my edited question, above, there doesn't appear to be a way to do this in Swift. I have confirmed this now.
I've tried a bunch of different techniques and nothing seems to work. My goal was to be able to add a .swift file with a class in it and rebuild, and have everything automagically know about the new class. I will be doing this a little differently, though.
I now plan to put all subclasses that need to be initialized this way into a particular directory in my application bundle, then my AppDelegate (or similar class) will be responsible for invoking a method that scans the directory using the filenames as the class names, and instantiating each one, thus building the list of "registered" subclasses.
When I have this working, I'll come back and post the code here (or in a GitHub project and link to it).
Same boat. So far the solution I've found is to list classes manually, but not as an array of strings (which is error-prone). An a array of classes such as this does the job:
class AClass {
class var subclasses: [AClass.Type] {
return [BClass.self, CClass.self, DClass.self]
}
}
As a bonus, this approach allows me to handle trees of classes, simply by overriding subclasses in each subclass.

Checking form's existence doesn't work

I have a Form for which I coded my own constructor:
constructor Create(AOwner: TComponent; AParent: TWinControl; ASender: TMyClass;
ATab: String); reintroduce; overload;
To create such a form I use the following:
try
MyForm := TMyClassForm.Create(nil, Self.Parent, Self as TMyClass, 'FirstTab');
MyForm.ShowModal;
finally
MyForm.Free;
end;
Somewhere else, before starting a procedure, I need to check whether this form is opened or not, so I check its existence with:
if (Assigned(MyForm)) and (MyForm.Active) and (MyForm.Showing) then
// Don't do the procedure
else
// Do the procedure
Now, if I open the form and close it, and I check this conditional statement, everytime I get true, but the Form is not opened and not showing anymore, because I freed it after creating.
Any idea of what could be the problem?
You called Free on the MyForm global method, but you did not modify the reference. So, MyForm still refers to the now destroyed form. And so Assigned(MyForm) evaluates as True, and then the other two tests operate on the stale object reference. Anything could happen when you operate on a stale object reference. In the situations that you have tried, it seems that the operations both return True. But another time you might get an access violation.
You'll want to set the MyForm variable to nil after call Free. At the risk of re-starting the great religious Delphi war of our times, you might contemplate using FreeAndNil(MyForm) in place of MyForm.Free.
You might find my answer here to be instructive: Why should I not use "if Assigned()" before using or freeing things?
Init:
MyForm := nil;
User FreeAndNil(MyForm)
if (Assigned(MyForm)) then
DON'T DO THE PROCEDURE
else
DO THE PROCEDURE

VBA Referring to a container object--syntax and object-oriented methodology

This is as much a question about learning object-oriented methodology, for me, as it is about VBA syntax. Suppose I create several classes, like Car, Truck, Bus, etc. And I create another class SpeedCalculator, which instances of my vehicles will instantiate and contain. (As a newbie, let me note that this strikes me as a good time to declare a class as static and not instantiate it--which vba can't do I don't think... .) Now this speed calculator will be no simple speedometer. Rather it will calculate speed from temperature, windspeed, RPMs, etc, etc--go along with this please, just for the sake of the example.
Now the question is how for the contained object to collect its inputs, which are only available in the container objects (the vehicle objects might implement an interface (if VBA can even do that...)). "Parent." is wrong, I figured out eventually, b/c parent-child is an inheritance relation (which VBA doesn't have, again), not a containment relation, and the parent of the contained object is an Excel Application (not my object). So it seems it would be nice if there were another keyword to refer to container properties. I hope I haven't just missed something simple. Or is it more the case that that sort of reference would break object-oriented encapsultaion principles?
I guess a second approach would be to pass the container to the contained, via "Me" as an argument. But then you have to multiply all of the contained's methods, either to overload them (if VBA can even do that...), or with variously named versions--due to the different types of the containers (can we be more idealist and avoid declaring as variant or "Object"?).
And then door #3 would be the last door standing, I guess? Which would be to pass an (annoying) litany of arguments. The definition of all of which would tend to defeat the purpose of having my tidy little calculator class?
It's not clear to me from your question whether or not you already know VBA and/or OO, and are just asking how to use the object-oriented features of VBA. If you are new to both VBA and OO, see below for some thoughts on why VBA isn't a very good vehicle for learning OOD/OOP.
To address the general part of your question, VBA classes can implement interfaces. This is how you express inheritance of interface (an "is-a" relationship) in VBA. There is no direct way to express inheritance of implementation in VBA. Instead, to make one class inherit the implementation of another, you have the first implement the interface of the second, contain an instance of the second, and then delegate calls to that instance. See this answer for more:
VBA inheritance, analog of super
There is a link there, that I will repeat here, to the Visual Studio 6.0 Programmer's Guide:
http://msdn.microsoft.com/en-us/library/aa240846(v=VS.60).aspx
It's as good a short introduction as any on the "VBA way" of OOP (although it's written for VB6, not VBA).
Now, for your specific question about design: "how for the contained object to collect its inputs, which are only available in the container objects".
You need to think about what you are actually modeling here. Regardless of how you implement it, a "speed calculator" should only get to know about a very specific set of inputs, not the entire internal state of whatever vehicle is using it. In VBA, as you note, there are no static classes. Instead, use a regular code module and have a function that you call from inside your vehicle class(es):
Public Function calcSpeed(temp, windspeed, rpm)
'do calc based only on parms passed in...
End Function
If it needs to take a zillion parameters because that's how the calculation works, so be it. Don't try to hide it. Of course, you can wrap them up in a Type or in a class if there are too many.
Now, does every different kind of vehicle calculate speed in the exact same way from the exact same set of state parameters? If so, then have a speed property or method that is implemented by your "base vehicle" class and call calcSpeed from there.
But maybe it's the case that different kinds of vehicles have different state parameters, or use different calculation methods, or the calculation is the same but not every vechicle type supplies every parameter. In that case, put the speed method in the base vehicle interface, but "override" it as needed in the implementation of each subclass. (Maybe then calcSpeed is too simplistic, and you'd end up with a library of speed calculation helper functions.)
One thing I would not do, is have a generic SpeedCalculator class that takes a Vehicle argument and then interrogates it for its state in order to do the calc. The reason why not is expressed very well in these classic articles:
http://media.pragprog.com/articles/may_04_oo1.pdf
http://pragprog.com/articles/tell-dont-ask
http://www.cmcrossroads.com/bradapp/docs/demeter-intro.html
There's also this:
http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
which has a quote I like:
So, what's so bad about this code
(besides being a horribly contrived
example)? Well, lets translate what
the code is actually doing into
real-language:
Apparently, when the
paperboy stops by and demands payment,
the customer is just going to turn
around, let the paperboy take the
wallet out of his back pocket, and
take out two bucks.
I don't know about
you, but I rarely let someone handle
my wallet. There are a number of
'realworld' problems with this, not to
mention we are trusting the paperboy
to be honest and just take out what
he's owed. If our future Wallet object
holds credit cards, the paperboy has
access to those too... but the basic
problem is that “the paperboy is being
exposed to more information than he
needs to be”.
Thats an important
concept... The 'Paperboy' class now
'knows' that the customer has a
wallet, and can manipulate it. When we
compile the Paperboy class, it will
need the Customer class and the Wallet
class. These three classes are now
'tightly coupled'. If we change the
Wallet class, we may have to make
changes to both of the other classes.
ADDED AS PROMISED IN COMMENTS:
It's not that you couldn't readily have an instance of a class Speedometer contained within your Vehicles. (My example of a simple function might be too simplistic. Maybe you need a class to model the other things about speedometers - they have mass, take up space, etc.) It's how the two classes depend on each other. In this example, Vehicle needs to know about Speedometer. But why should the reverse be true? If Speedometer takes a Vehicle as a parameter, and then asks it for the particular things it needs to know to calculate speed, the code will certainly work. However, you've coupled Speedometer to Vehicle more tightly than necessary.
One of the reasons to use an OO approach in the first place is because it lets you be more exact about how concepts relate to each other. It's better to have Vehicle tell Speedometer, "Here are some facts about the world. Give me back a speed.", rather than, "Here I am, Me, the Vehicle that contians you. Ask me whatever you need to about anything related to me, and then give me back a speed." (Note that whether the "facts about the world" are raw temp, windspeed, etc., or an instance of some SpeedometerInput Type/Class isn't the issue. It's that speedometers don't need to know all about vehicles.)
Using the most exact interface you can get away with doesn't make that big of a deal in a simple example. But it becomes huge when added up over many design decisions.
Finally, If you have a choice, I wouldn't use VBA as a vehicle for learning object-oriented design or programming. You can do "OOP" in VBA, but in a Microsoft-/COM-specific way that is literally a relic from the mid-1990s. You can browse around stackoverflow for plenty of examples of things that are normally done in OO programming languages (and with their much better libraries) that are cumbersome and tricky in VBA. Here are a few off the top of my head that I've either asked or answered:
Is there a way to overload the constructor / initialize procedure for a class in VBA?
Is there a way to write an equality test for a VBA class with private members without exposing knowledge of the existence of those private members?
Restrict type in a Collection inside a class module
Excel-VBA - Is there anything like Javas Set container in VBA?
So, unless you're either constrained to learn with VBA because you can't install anything but MS Office on your machine, or you plan to be doing a lot of VBA work becuase you're using Excel, Access, etc. and have some problems where OOP can help, I'd look elsewhere. Python, .NET, or Java are all available for free on Windows and have tons of resources available for the beginner.
I'm not sure if this is what you're looking for, but I'll give it a shot. If Car class contains one Speedometer class, Car contains Windspeed and Acceleration properties, Speedometer contains a Mass property, and speed is defined as Windspeed times Acceleration divided by Mass, then here's how I would set it up.
In class CCar
Private mlCarID As Long
Private mdWindSpeed As Double
Private mdAcceleration As Double
Private mclsSpeedometer As CSpeedometer
'Getters and setters
Public Property Get CarID() As Long: CarID = mlCarID: End Property
Public Property Let CarID(ByVal lCarID As Long): mlCarID = lCarID: End Property
Public Property Get Acceleration() As Double: Acceleration = mdAcceleration: End Property
Public Property Let Acceleration(ByVal dAcceleration As Double): mdAcceleration = dAcceleration: End Property
Public Property Get WindSpeed() As Double: WindSpeed = mdWindSpeed: End Property
Public Property Let WindSpeed(ByVal dWindSpeed As Double): mdWindSpeed = dWindSpeed: End Property
'read only property to the speedometer class
Public Property Get Speedometer() As CSpeedometer
Set Speedometer = mclsSpeedometer
End Property
'create the child and set the parent property
Private Sub Class_Initialize()
Set mclsSpeedometer = New CSpeedometer
Set mclsSpeedometer.Parent = Me
End Sub
Private Sub Class_Terminate()
Set mclsSpeedometer.Parent = Nothing
Set mclsSpeedometer = Nothing
End Sub
'pass through property
Public Property Get Speed() As Double
Speed = Me.Speedometer.Speed
End Property
In class CSpeedometer
Private mdMass As Double
Private mclsParent As CCar
Public Property Get Mass() As Double: Mass = mdMass: End Property
Public Property Let Mass(ByVal dMass As Double): mdMass = dMass: End Property
Public Property Get Parent() As CCar
Set Parent = mclsParent
End Property
Public Property Set Parent(clsCar As CCar)
Set mclsParent = clsCar
End Property
Public Property Get Speed() As Double
'references to parent properties
Speed = Me.Parent.WindSpeed * Me.Parent.Acceleration / Me.Mass
End Property
In a standard module
Sub GetSpeed()
Dim clsCar As CCar
Set clsCar = New CCar
clsCar.CarID = 1
clsCar.WindSpeed = 10
clsCar.Acceleration = 5
clsCar.Speedometer.Mass = 100
Debug.Print clsCar.Speed
End Sub
You have to make sure you destroy your parent/child relationship properly or you'll get a memory leak. I use CopyMemory to set up parent properties to avoid that particular problem. It's described here http://www.dailydoseofexcel.com/archives/2007/12/28/terminating-dependent-classes/#comment-29661

Can I set the Database adapter to use permanently from within a Zend_Db_Table_Abstract Class?

I have 2 databases that my site uses including a central user database that relates to other site-specific databases.
Sometimes it is adequate to call new User(array('db'=>'adapter1')); (but never convenient); other times, though, such as when declaring relationships between tables on different databases, there is no way to do this.
Does anyone know a way to specify which database adapter to use from within the Zend_Db_Table_Abstract class?
Thanks!
Getting back to this pretty late, but none of the answers here quite did it for me. A select few of my database models needed to use 'tdb' and the following code was added to each of those classes to have that happen automatically:
protected function _setupDatabaseAdapter()
{
$this->_db = Zend_Registry::get('tdb');
parent::_setupDatabaseAdapter();
}
I thank you all for your suggestions along the way!
Zend_Db_Table_Abstract provides a static method to set the default database adapter. Do this as follows:
Zend_Db_Table_Abstract::setDefaultAdapter($adapter);
Now, all your Table objects will use your adapter by default.
Note: the online docs sometimes don't make this obvious, so your second best place to check is in the API here: http://framework.zend.com/apidoc/core/
You could set the class variable $_db to the correct adapter in the constructor.
global $adapter1; //There are better ways than using a global variable
$this->_db = $adapter1;
Assuming the adapter object can be referenced in the constructor. That doesn't seem to portable, but I believe it would work.
The init function can be used, it is not used in Zend_Db_Adapter_Abstract, can be used in your class to setup whatever needs to be done. _setAdapter accepts a string naming a Registry Key.
public function init()
{
$this->_setAdapter('tdb');
}