How to declare type for a class method in Delphi? - class

How to declare type for a class procedure, for example
type
TTest = class
procedure Proc1;
class procedure Proc2;
class procedure Proc3; static;
end;
TProc1 = procedure of object;
TProc2 = ???;
TProc3 = ???;

TProc2 = procedure of object;
A class method still has a Self pointer. It's the class rather than the instance.
An interesting consequence of this is that it provides a way to implement event handlers without having to instantiate an object. For instance, you could use a class method of a class that that is never instantiated as a way to provide event handlers for the global Application object.
TProc3 = procedure;
A static class method has no Self pointer. It is assignment compatible with a plain procedural type.
Static class methods can be used as an alternative to globally scoped procedures. This does allow you to put such methods in a namespace, that of the class, and so avoid polluting the global namespace.
Take care when implementing static class methods that you do not call virtual class methods. Such calls are bound statically at compile time because the lack of a Self pointer means that dynamic polymorphic binding at runtime is not possible. Rather disappointingly the compiler fails to warn of this and so you do need to keep your wits about you.

Related

Why does nesting a class give the containing class access to the child class' protected data?

The question may be a bit confusing, and is best illustrated by an example:
unit Test
interface
type
TestClass = class()
Splitter1: TcxSplitter;
procedure SomeMethod();
end;
implementation
uses
cxSplitter;
// Locally-declared child type
type
TcxSplitterAccess = class(TcxSplitter);
procedure TestClass.SomeMethod()
var
pos: integer;
begin
// Access to protected field FPositionBeforeClose by casting
pos := TcxSplitterAccess(Splitter1).FPositionBeforeClose;
end;
Notice in the implementation section that there is a type TcxSplitterAccess being declared as a child of the TcxSplitter class. In the method SomeMethod(), belonging to the class TestClass, a TcxSplitter object is cast to the locally-declared TcxSplitterAccess class, and then a protected field is accessed on that object.
This is surprising to me as someone coming from a background of languages like Java, C++, C#, etc. In those languages, it is possible to access protected data in an object so long as you are doing it from within that object's type or an inherited type. For example, a method inside of a class ClazzA can access the private fields of other ClazzA objects since access is enforced at the type level rather than the instance level. Declaring a class locally in these languages would not give the containing class access to the local class' protected data (edit: As pointed out in the comments, this is actually not true at least for Java).
In this example, however, the type TestClass is directly accessing a protected field on the TcxSplitter object by first casting to the TcxSplitterAccess type. I am having trouble finding documentation on why this "trick" works. Does Delphi handle access levels fundamentally differently to Java-like languages and allows this sort of thing? Regardless, why does this trick work?
While I stumbled onto this behavior by using a nested, inherited class in order to access fields on the parent class (which breaks encapsulation, and I shouldn't do), the use of inheritance here is unnecessary. If the nested class did not inherit from a class, but instead had its own protected fields defined, TestClass would still be able to access those protected fields.
A unit has implicit-friendship semantics within itself. Types declared in the same unit are "friends" of each other (similar to friend in C++), and so can access each other's private and protected members (but not strict private or strict protected members).
So, in this case:
TcxSplitterAccess derives from TcxSplitter, so TcxSplitterAccess inherits all of the protected (but not private) members of TcxSplitter via normal class inheritance.
TestClass is declared in the same unit as TcxSplitterAccess, so TestClass has access to all of the protected members of TcxSplitterAccess, including the protected members of TcxSplitter (and the protected members of its ancestors).
FPositionBeforeClose is protected in TcxSplitter.
So, that is why TestClass.SomeMethod() is able to access FPositionBeforeClose when type-casting the Splitter1 object to TcxSplitterAccess.
This is covered by the Delphi documentation:
Private, Protected, Public, and Published Declarations
Classes and Objects (Delphi): Visibility of Class Members

Interface or class as method (or constructor) parameter

Why do I have class or interface passed as a method parameter in a class? I don't get that concept. For example:
Declaration:
public void doSomething (Class yourClass){}
Calling the method:
doSomething(yourClass);
What is the benefit? Is there an alternative? I can't call methods for yourClass anyway, for example: doSomething(yourClass.someMethod()) or doSomething(yourClass) and then yourClass.someMethod() are both invalid.
There's several possibilites, depending on the particular language. doSomething(Class) could...
Instantiate and return a Class generator.
Create an object or service to track or otherwise interact with one or more Class objects.
Return useful information about Class (e.g. via reflection).

Swift: class func .... why use this instead of func when creating a method inside a class?

I'm new to coding, apologies for dumb question.
Am following a tutorial to build a note taking app using Swift in Xcode.
Within a class definition I have been defining methods using the keyword func myMethod etc. At one point the instructor decides to define a Class method (within the existing class) using class func myMethod.
Why would you do this?
Thanks in advance for any feedback.
By defining a class method it means that you don't need an instance of that class to use the method. So instead of:
var myInstance: MyClass = MyClass()
myInstance.myMethod()
You can simply use:
MyClass.myMethod()
The static (class) function is callable without needing an instance of the class available; it may be called without having to instantiate an object.
This can be useful for encapsulation (avoiding placing the function in the global namespace), or for operations that apply to all objects of a given class, such as tracking the total number of objects currently instantiated.
Static functions can be used to define a namespaces collection of related utility functions:
aDate = Utils.getDate()
aTime = Utils.getTime()
Another common use is for the singleton pattern, where a static function is used to provide access to an object that is limited to being instantiate only once:
obj = MySingleton.getInstance()
obj.whatever()
One answer is namespacing. If a function is only relevant to a certain class there is no need to declare the function globally.
This is Swift's take on static methods:
Static methods are meant to be relevant to all the instances of a class (or no instances) rather than to any specific instance.
An example of these are the animation functions in UIView, or the canSendMail function from MFMailComposeViewController.

what is the meaning of `Class of ` type declaration?

While going through one of my code, I am stuck on one statement which is as below.
TMyObjectClass = class of TMyObject;
I am a bit confused, and wondering what is the meaning of this statement.
As TMyObjectClass has no declaration above the statement.
and TMyObject is having declaration as below:
TMyObject = class(TObject)
private
//some private member declaration
Public
// some public variables
end;
So, my question is what is the meaning of the statement
TMyObjectClass = class of TMyObject;
and How TMyObjectClass works?
I am a bit new to Delphi, so please help me to get some idea about these type of declaration and there workarounds.
This is a Class Reference.
They are used to work with meta classes. The canonical example is the Delphi streaming framework which uses
TComponentClass = class of TComponent;
This allows for dynamic binding to virtual constructors. The TComponent constructor is virtual. The streaming framework needs to instantiate classes derived from TComponent. It does so something like this:
var
ComponentClass: TComponentClass;
Component: TComponent;
....
ComponentClass := GetComponentClassSomehowDoesntMatterHow;
Component := ComponentClass.Create(Owner);
Now, because TComponent.Create is virtual, this is bound in a polymorphic fashion. If TComponentClass is TButton, then TButton.Create is called. If TComponentClass is TPanel, then TPanel.Create is called. And so on.
The most important thing to realise is that the class that is constructed is determined only at runtime. Note that many languages lack this capability, most notably C++.

Injecting with Gin into instance created by GWT.create

I have a custom deferred binder (rebind implementation) that instantiates objects. I would like to have some dependencies (#Inject annotated setter methods) within the instance returned by GWT.create() fulfilled by GIN. Is this possible?
So, given code such as:
Foo foo = GWT.create(Foo.class);
if foo's final implementation has:
#Inject
public void setBar(Bar bar) {
...
}
how do I get bar injected into the returned foo instance automatically by GIN?
Your Ginjector can have methods added to it for the purpose of injecting objects created in some other way. These must take one argument, and should specify the most specific type possible. For example, if MyViewImpl extends BaseView, and both types have dependencies to inject, but you declare
void injectBaseView(BaseView view);
in your ginjector, only the fields/setters declared on BaseView will be dealt with.
EDIT: Also, if no binding is declared, GWT.create will be used to create an instance, so you can have your cake and eat it to. One exception to that as far as I can recall, is when you want to GWT.create one type, but return another (see RPC interfaces for an example).