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

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++.

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

Mark Haxe Class for forced extend?

Is there a compiler meta for Class declaration, that prevents creating Class instance before extending it? In other words - some sort of opposite of #:final meta.
Like so (last line of code):
class A {
// ...
}
class B extends A {
// ...
}
// ...
var b = new B(); // OK
var a = new A(); // induce compiler-error
Simply don't declare a constructor at all for class A
Both the other answers are correct (no constructor or private constructor), but there are a few more details that you may interest you:
Here's an example of no constructor. Of note is that A simply doesn't have a constructor, and B simply doesn't call super(). Other than that, everything else works as you'd expect.
Here's an example of a private constructor. You still can't instantiate a new A(), but you do still need to call super() from B's constructor.
Technicalities:
Use of some features (like a default value on a member variable) will cause A to get an implicit constructor, automatically. Don't worry, this doesn't affect constructability or whether you need to call super(). But know that it is there, and if necessary an implicit super() call is prepended to B's constructor. See the JS output to verify this.
In any case, know that you can still instantiate an A at runtime with var a = Type.createInstance(A,[]); as compile-time type checks do not limit RTTI.
Related discussion:
Aside from private/no constructor, Haxe doesn't have a formal notion of abstract classes1 (base classes not expected to be instantiated) or abstract methods2 (functions on abstract base classes with no implementation that must be implemented by a derived class.) However, Andy Li wrote a macro for enforcing some of those concepts if you use them. Such a macro can detect violations of these rules and throw compile-time errors.
1. Not to be confused with Haxe abstracts types, which are an entirely different topic.
2. Not to be confused with virtual functions, which wikipedia describes as a function which can be overridden (though various docs for various languages describe this highly loaded term differently.)
One way of achieving this is to create private Class constructor:
class A {
private function new() {
// ...
}
}
// ...
var a = new A(); // Error: Cannot access private constructor

Haxe: how to declare "static" methods in an Interface?

This question has been asked (and probably answered) in the old Haxe forums on babble ... but it appears that that entire forum system no longer functions. Therefore, I'm asking here:
In Haxe, I need to declare an "Interface" to a class which includes a static function, "instance()." But when I do so:
You can't declare static fields in interfaces
So I remove the word "static" from public function instance() [...], and I get this:
Field instance needed by [...] is missing.
Apparently a "Catch-22." But there obviously must be some easy solution. What is it?
As you stated the language doesn't allow for static fields on interfaces. The choice is intentional. Another thing that doesn't exist is inheriting static fields.
There are several ways to structure your code to avoid such usage that in my point of view it doesn't give you many advantages. A factory pattern or DI approach (I suggest the minject library) seems the most obvious.
Given the comment below go for a typedef instead of an interface:
typedef GetInstance = Void -> Void;
You can pass that typedef around the same as an interface with the advantage that you can use both static and instance methods to satisfy that signature.
Check out the Singleton library. Any class that implements Singleton will automatically declare a static "instance" variable and corresponding getter function.
Note: as of this writing, the Haxelib version (1.0.0) is out of date. Download the Git version instead.

Can one declare a static method within an abstract class, in Dart?

In an abstract class, I wish to define static methods, but I'm having problems.
In this simple example
abstract class Main {
static String get name;
bool use( Element el );
}
class Sub extends Main {
static String get name => 'testme';
bool use( Element el ) => (el is Element);
}
I receive the error:
function body expected for method 'get:name' static String get name;
Is there a typo in the declaration, or are static methods incompatible with abstract classes?
Dart doesn't inherit static methods to derived classes. So it makes no sense to create abstract static methods (without implementation).
If you want a static method in class Main you have to fully define it there and always call it like Main.name
== EDIT ==
I'm sure I read or heard some arguments from Gilad Bracha about it but can't find it now.
This behaviour is IMHO common mostly in statically typed languages (I don't know many dynamic languages). A static method is like a top level function where the class name just acts as a namespace. A static method has nothing to do with an instantiated object so inheritance is not applicable. In languages where static methods are 'inherited' this is just syntactic sugar. Dart likes to be more explicit here and to avoid confusion between instance methods and static methods (which actually are not methods but just functions because they don't act on an instance). This is not my primary domain, but hopefully may make some sense anyways ;-)
Looks like you are trying to 'override' a static method. I'm not sure what you are trying to achieve there. I'm not aware of any OO languages that support that (and not sure how they could).
A similar question in Java might help clarify Polymorphism and Static Methods
Note also that it is considered bad practice to refer to statics from an instance of the class in Java (and other OO languages). Interestingly I noticed Dart does not let you do this so is in effect removing this bad practice entirely.
So you couldn't even fool yourself into thinking it would behave polymorphically in Dart because you can't call the static from the instance.

What design pattern provides a static method to produce a class instance

I am trying to understand what design pattern I am stumbling towards... please bear with me the language I am using is Matlab and the OO is a bit weak in some areas, and I am relatively inexperienced in implementing design patterns.
I have a ComplexObject in which the constructor was becoming overly complicated. To begin with my constructor allowed 0, 1 or 2 arguments, that is an "empty" ComplexObject, a ComplexObject built from a ModelObject, or a ComplexObject built from ModelObject+ConfigObject. (The ModelObject and ConfigObject are basic file parsers).
I can't overload constructors in Matlab, so I essentially switch'ed on the class type of the input arguments to the constructor, after I while I changed some of this to static methods so that the constructor was just an empty class initializer, and static ComplexObject.createFromModel and ComplexObject.createFromModelAndConfig classes produced ComplexObjects.
I then decided that my ComplexObject code was being dominated by all this construction stuff and the business logic wasnt clear, so I wrote a ComplexObjectFactory class and basically moved the static methods into that class. Now since the static methods are in fact calling more private (static!?) methods to build the ComplexObject I have run into some confusion about calling conventions of these private static methods :(
Finally, I am now trying to add some code to write part of ComplexObject back to disk. Interestingly this is actually the same disk file that is used to build a ConfigObject... so I want something like ComplexObject.writeConfigFile... or should that be ComplexObjectFactory.writeConfigFile(myComplexObject). To further complicate things I want multiple types of "config" file formats down the track.
My current classes look something like:
classdef ComplexObjectFactory
methods (Static)
function product = createFromModel(modelObj)
product = ComplexObject()
ComplexObjectFactory.helper1(product)
end
function product = createFromModelAndConfig(modelObj, configObj)
product = ComplexObjectFactory.createFromModel(modelObj)
ComplexObjectFactory.helper2(product, configObj)
end
end
methods (Private, Static)
function helper1(product)
function helper2(product)
end
end
classdef ComplexObject
methods
function self = ComplexObject(varargin)
<init>
end
end
end
classdef ComplexObject
Not sure I completely understand your question, tell me if I'm off topic here.
Just like you wrote, design pattern that creates objects is called factory. Other functionality that you mentioned, like writing to disk should be the responsibility of the object itself.