Monday, June 11, 2018

Record definition

You can see a record as a simple class, without inheritance.
As a class is living on the heap, a record is living on the stack - making it a limited, but simpler and faster entity than a class. Just as classes, records can have constructors, finalizers, methods, fields, properties and constants, but a record can not be disposable as it can not implement interfaces.



Record visibility
The most simple class definition you can write:
The code above defines the record MyRecord.
The visibility of the record is not defined and will be Unit (see Visibility modifiers).

We can make the record public accessible by adding the visibility modifier Public:


Record modifiers
With a record modifier you give a hint to the compiler of how to compile this record:
partialA partial record definition is a record that can be defined over more than one code file.
readonlyWhen a record is marked readonly, all variables and properties are readonly. This means that they can only be set from within a constructor of the record.

Example of the usage of a class modifier:



Record constructors
When a record is instantiated, the constructor is executed. A constructor is a special kind of method that initializes the record (makes it ready for use) and is the only place where you can initialize read only fields.
A record can have more than one constructor .

To define a constructor, you use the constructor keyword:
 

In the example above, two constructors are added to the record, one without and one with parameters. You can add as much constructors as you want / need to the record.


Record destructors or finalizers
When a record is being destroyed (GC or reference counting), the finalizer is executed to clean the state of the instance.
A finalizer is always executed from an unknown thread - so the code should be thread safe!
The code of the finalizer is a last resort to clean up - it should already been done before the finalizer executes; with the use of the dispose pattern (.Net or Java only) or within the state handling of the record code.
A finalizer is defined with the Finalizer keyword:

A record can only have one finalizer and the finalizer is a method without any parameters. The implementation:


Interface inheritance
Interface inheritance is only available for .Net and Java - Other platforms do not support this.

A record can inherit from multiple interfaces - all of those interfaces have to be implemented (unless the interface has a default implementation, in that case the interface implementation is not mandatory).
The syntax to inherit from an interface is exactly the same as the syntax to inherit from a base class. Multiple interfaces to inherit from are separated by comma's.
To use the interface, we have to implement all methods and properties within the interface (in this case only the method Dispose):
When you implement more interfaces that have conflicting names, or you have reason to use another name than the standard name, you can use another name and the implements modifier to tell the compiler which interface is being implemented:

The implementation methods do not have to be public - they can also be private (or any other visibility), but as soon as you cast the object to the interface, the interface methods will be public and the methods will have their original names.




Inline arrays
To use this you need the UnSafe option - otherwise this won't compile.
A record is living on the stack, but reference to arrays are still pointers that point to a location on the heap where the object is stored. For use with P/Invoke it might be needed to inline an array, so it will be within the record on the stack.



Class definition

In contrast to most languages, with Oxygene (and all other Pascal variants), a class is first defined and then implemented. Within the class definition you define the structure and interface of the class, and this is where you define the visibility of each method, property, field or constant. The compiler directives as inlining and locking are also defined here.
Properties, fields and constants are completely defined in the class definition, methods (including property implementation methods) are defined here, but implemented later in the implementation section.

Class Visibility
The most simple class definition you can write:
The code above defines the class MyClass that inherits from Object (a class alwaysI inherits from another class, if you don't specify the bas class, Object will be used as base class).
The visibility of the class is not defined and will be Unit (see Visibility modifiers).

We can make the class public accessible by adding the visibility modifier Public:

Class modifiers
With a class modifier you give a hint to the compiler of how to compile this class:
abstractabstract means that the class must be inherited before it can be used.When a class definition has abstract methods defined, the class must be abstract too.
partialA partial class definition is a class that can be defined over more than one code file. By example used for the designer code of a winforms definition.
readonlyWhen a class is marked readonly, all variables and properties are readonly. This means that they can only be set from within a constructor of the class.
sealedA sealed class can not be inherited.
staticA static class can not be instantiated and all methods and properties within the class are marked static. You can see this as a module from VB.Net.
extensionThe following text literally copied from the Oxygene website:
Defines an extension type, a type which extends another type on Cocoa, called a category on Cocoa.

Example of the usage of a class modifier:


Class inheritance
Oxygene uses a single inheritance model, where every class inherits from only one other class - multiple inheritance, like in C++, where one class can inherit from multiple base classes, is not supported.

With inheritance, the new class has all methods, properties, fields and constants available that are defined in the base class, as long as the visibility of those items is Protected or less (for assembly and protected, the inheritance must be done in the same project and for unit and protected, the inheritance must take place in the same file to be able to see those class items).
 To inherit your class from another class, you have to write:
With this statement you create the class MyClass that is a subclass of baseClass, and baseClass is the superclass of MyClass (that is why inheritance is also often referred to as subclassing).


Class constructors
When a class is instantiated, the constructor is executed. A constructor is a special kind of method that initializes the class (makes it ready for use) and is the only place where you can initialize read only fields.
A class can have more than one constructor - and can even have a parameter-less static constructor that is executed just before the first time that a static member of the class is called.

To define a constructor, you use the constructor keyword:
In the example above, two constructors are added to the class, one without and one with parameters. You can add as much constructors as you want / need to the class.
A constructor should always call the (a) constructor of the base class, to make sure that the inherited functionality is initialized properly. Constructors can call each other with the constructor keyword:


Class destructors or finalizers
When a class is being destroyed (GC or reference counting), the finalizer is executed to clean the state of the instance.
A finalizer is always executed from an unknown thread - so the code should be thread safe!
The code of the finalizer is a last resort to clean up - it should already been done before the finalizer executes; with the use of the dispose pattern or within the state handling of the class code.
A finalizer is defined with the Finalizer keyword:
A class can only have one finalizer and the finalizer is a method without any parameters. The implementation:


Extending the class
The newly created class can be extended by adding methods, properties, fields and constants to it. This is called extending because the class inherited all methods, properties fields and constants from its base class - and you can extend the class by adding more of them:
As an example; the code above extends the class with the public property NewProp - if the base class had a public property OldProp, this is still available in the newly created class MyClass.



Re-introduction and overriding
Existing methods and properties can be re-introduced or overridden with a new implementation - only methods and properties that are labeled with the virtual modifier in the base class can be overridden, all others can only be re-introduced.

So what is the difference between re-introduction and overriding? The difference between the two are small, but can have a big impact within the execution of your program.

With a re-introduction, the subclass defines a completely new method or property with the same name of a method or property in the superclass. This seems no problem, but when a class is cast to it's ancestor, the original method or property is called instead of the re-introduction.
An example:

When you call SomeMethod in baseClass, it returns 4 and when you call it in MyClass it returns 2. But when you cast MyClass to baseClass (or a parameter of a method is of type baseClass while you supply an instance of MyClass), the result will be 4.

If you override the method instead of re-introduce it:
Now, when you call SomeMethod in baseClass, it still returns 4 and when you call it in MyClass it still returns 2. But when you cast MyClass to baseClass (or a parameter of a method is of type baseClass while you supply an instance of MyClass), the result will be 2 instead of 4, meaning that the overridden method is used instead of the original.

The same is explained in the post Method modifiers.


Interface inheritance
Where a class can only inherit from one baseclass, it can inherit from multiple interfaces - all of those interfaces have to be implemented (unless the interface has a default implementation, in that case the interface implementation is not mandatory).
The synatx to inherit from an interface is exactly the same as the syntax to inherit from a base class. Multiple interfaces to inherit from are separated by comma's:
The example above inherits from the interface IDisposable.
To use the interface, we have to implement all methods and properties within the interface (in this case only the method Dispose):
When you implement more interfaces that have conflicting names, or you have reason to use another name than the standard name, you can use another name and the implements modifier to tell the compiler which interface is being implemented:
The implementation methods do not have to be public - they can also be private (or any other visibility), but as soon as you cast the object to the interface, the interface methods will be public and the methods will have their original names.







Monday, May 21, 2018

Property definition and implementation

You can see properties as fields with an implementation; within the implementation context they behave as variables, but the real implementation (that can be a storage field, a get or set method, or a combination) is hidden from the implementation.
A property is defined with the "property" keyword.

Simple properties
The simplest property you can write is:
This is a property that on completely behaves like a field; the property is read / write and the value is stored in a (hidden - compiler generated) field.
 
Just like a field, the property can be initialized with a default value:
The read only variant:
This read only property without initialization can only be initialized from the constructor.

Properties with explicit storage
Instead of the compiler generated storage field, you can define your own storage field.
To add a specific storage field for the property add the read and write modifiers:
The property above reads and writes to the field propstorage, and because this field is initialized to 5, the property is also. To create a read only property you can skip the write part, to create a write only property just skip the read part:

Functional properties
A property can also be defined with a get and a set method, where the function property implementation is defined:

In this case the set method is executed when the code writes to the property and the get method is executed when the code reads from the property.
Of course you can create read only and write only properties this way too:
Or combine the field storage and get or set method :

Parameterized or indexed properties
A property can also have one or more indexes (and because these indexers can be of any type, I call them parameterized properties). The get and set methods of the property must be changed to reflect those parameters:

Visibility modifier
Because a read/write property exists of two separate actions, we need a modifier to give them different visibility. By example, if you want a property that can be publicly read, but has to have a private setter you can write:
The first property uses a compiler generated field that has private write access, the second uses an explicit defined field with private write access. The same is true for functional properties; the methods itself have the visibility of the section that they are defined in, but the property still has only one visibility as long as the correct visibility is not defined in the read or write part of the property definition.


Instance and static properties
Just as with methods and field,  a property is a static property when the "class" keyword is used and
an instance property when it is not used.


The functional modifiers
These modifiers specify functional behavior of the property:
lockedThe locked modifier changes the behavior of the property in such a way that it becomes thread-safe; only one thread at a time can call this property. If more threads want to call this property simultaneously, the threads have to wait for each other.
locked on <expression>The locked on modifier behaves the same as locked, but works on an expression. If more properties or methods use the same expression than only one thread can run one of these properties or methods at once.
notifyThe notify modifier will make sure that there is a notification event raised when this property has been written. The way this functions varies between the different platforms.
defaultOnly for parameterized properties: The default modifier makes this property the default property of the object, so you can call MyObject[...params...] instead of MyObject.Propname[...params...].
Only one property in a type can have this modifier.


The compiler-hint modifiers
These modifiers help the compiler to generate the correct code for this property:
implements Form of implements IInterfaceName.PropertyName:
This compiler hint implements IInterfaceName.PropertyName tells the compiler which interface property is being implemented here.

Form of implements IInterfaceName:
This compiler hint tells the compiler that the property points to a type that implements the complete interface.
LazyOnly for initialized properties; tell's the compiler to initialize the property on first access instead of during execution of the constructor. A lazy property that isn't been called won't be initialized.
unsafe.Net only.
Tells the compiler that this property is doing unsafe operations like pointer operations. This modifier makes sure that the heap is not being compressed or garbage collected during the execution of this property.

And that was all there is to know about the properties.
The Generics will be explained in the next post.

Sunday, May 20, 2018

Field and constant definition

In this post I will explain how to define fields and constants with Oxygene Pascal.

Field definition
A field is a storage variable within a class or structure, a constant is alike, but immutable.
Local variables and constants within a method implementation work exactly the same (with a few exceptions), so everything that is explained here is also valid for that (the exceptions will pointed out).


A field is defined with the keyword "var", followed by the name of the field and the type of the field:
This is an uninitialized variable, which has the initially the default value for the used type.
A field can be initialized as following:
Both field definitions are the same; at the first I added an explicit type, at the second one the type is inferred from the assigned value - but it is still strong typed.

It is also possible to define multiple fields of the same type at once:
With this syntax it is not possible to initialize the variables to another value than the default of the type.

A field can also be defined as read only:
All three fields are read only, the first to with an assigned value in the field definition, the third must be assigned in the class constructor (the only place where this is allowed for a read only variable) as it has no value in the definition.

Field modifiers
Besides the "readonly" modifier that we already talked about, there are three more:
readonlyThe readonly modifier declare the field as read only, the field can only be initialized within the field definition or in the constructor of the type.
For variables: a read only variable must be initialize within the variable definition.
unsafe
     /
pinned
The unsafe modifier (only for fields) defines that the field is an unsafe pointer - this means that the field may not be moved within memory.
Pinned - only for variables: means that the variable may not be moved within memory
volatileFields only. The volatile modifier makes the field thread safe and all reads and writes to it will be atomic. A volatile field is always accessed directly in memory and won't be cached by the CPU (preventing out of date CPU caches).
implementsFields only. With the implements modifier you tell the compiler that this field points to a method that implements a specific interface method.

Instance and static fields 
(This does not apply to variables)
A field can be defined as an instance field (with var, as I did above in the examples) or as a static field that is the same for all instances with "class var".

Field visibility
(This does not apply to variables)
The visibility of the field is determent by the section of the class where the field is declared, see Visibility modifiers for more information.

Constant definition
A constant is always static and never instance specific.
A constant definition is identical to an initialized variable definition, but is initialized with = instead of := (because this is technically speaking not an assignment) :
The difference between a read only variable and a constant is that a read only variable can be assigned in the constructor and a constant can not. Further, each use of a constant is replaced by the constant itself during compile. So in a compiled binary the constant does not exist anymore.

And that is all I can tell about fields, variables and constants.
Next I will tell about properties, which need both the method and fields.

Method implementation

The methods are implemented within the Implementation section of the pascal file (see  The structure of a Pascal file).

The implementation
To generate an empty implementation from the method definitions press Ctrl + Shift + C.
The generated method looks like this:

You see that that method name has been prefixed by MyClass. and a begin / end; block is appended.
The MyClass. prefix tells the compiler to which class the method belongs - this is needed because you can define more than one class in the file.

Between the begin and end; statements you can write your implementation, by example when this method has to:
  - return the string representation of the result of 100 divided by the integer parameter
  - but only when the parameter is bigger than zero (otherwise a custom error is thrown)
  - and only when the result is bigger than 10 (otherwise a custom error is thrown)

The implementation will be:

The first line checks if p is bigger than zero, and if it is, the second line is executed where the calculation is done. The third line checks if the result is bigger than 10 and if so, the fourth line is executed where the string representation of the result is returned to the caller.
When the result was smaller than 10 or when the parameter smaller or equal to zero, a custom exception (error) is thrown.

Note that, when you use the keyword Exit, the function exits immediately - any code following it won't be executed anymore. And when an exception is raised, the method is also immediately terminated - without result, and the exception should be catched by an error handler that is defined in the calling chain - if not, the program will terminate with this exception.
Exception handling is a topic for a future post where I will explain it further.

Contracts
When the check p > 0 is a requirement to run this method, in other words when a call to this method with a value of p <= 0 is considered as a bug then a contract should be used.

A contract specifies the expected state of the parameters (and or other class states) that are required to run this method. The example above with an implemented contract for the parameter p looks as following:
When a debug build is executed, the "require" check is executed to find the bugs during development; an assertion is raised when the method is called with invalid parameters or when it is called in combination with a class state that does not allow this.

If a result smaller or equal to 10 is also considered a bug then we can check this in a contract too:
The "ensure"check is executed before the method returns to the caller and an assertion is raised when the check do no pass. And as you see, the resulting code is very small and readable.

In this example I use the result variable instead of Exit. The result variable is always available in any function and has the same type as the return type of the function.
When the function completes without an exit statement, the value of the result variable is returned to the caller.

Because the result will be smaller than 10 as soon as p > 10, we could also have written:

You see that the boolean check in the require contract exists out of 3 values instead of 2 as normal. This is the way you can write a boolean between test anywhere in Oxygene.

One thing that I did not show is that you can use the old value of the parameters (this is the value that the parameters had on method entry) and also use the current value of these parameter, making the following check  possible:

You can add as may checks as you want to both the require and ensure checks - all checks must be in the form of a boolean expression and an assertion is raised when one or more checks do not pass.

The require and ensure checks are not executed in a release build making sure that the checks do no slow down the released version, but are only used during the development and debug stage.

I personally find the contracts really awesome!
Next post will be about the Field definitions and constants - see you there.





Method modifiers

The method modifiers are appended to the method definition and give information to the compiler of how these methods should behave. There are three kind of modifiers; OO modifiers, functional modifiers and compiler-hint modifiers.

The Object Oriented modifiers
The OO modifiers specify the inheritance behavior of the method:
abstractabstract means that the method will not be implemented in this class implementation; the class should be specialized with inheritance where this method should be overridden. An abstract method is per definition also a virtual method.
virtualvirtual means that a descendant class can override (or in other words: re-implement) this method.
overrideoverride means that this method re-implements the virtual method of an ancestor class.
finalfinal means that this virtual method can not be overridden in any descendant class anymore.
reintroduce reintroduce means that the method is not re-implemented, but replaced in this descendant class (this is the Shadow modifier in Visual Basic).

Behavior  differences between an overridden method and a reintroduced method
We have two classes; parent and child. Child inherits from parent.

In the parent class, the following method is defined:
This method always returns 1 (how the implementation works is the subject of the next post).

1. Results with override
In the child class we override this method and implement it so it will return 2:

When we create an instance of parent and call the method, it will return 1.
When we create an instance of child and call the method, it will return 2.
 
And when we cast the instance of child to parent, and call the method it will return 2.
This works because child replaced the virtual method with it's own implementation.

2. Results with reintroduce
In the child class we override this method and implement it so it will return 2:

When we create an instance of parent and call the method, it still returns 1.
When we create an instance of child and call the method, it still returns 2.
 
And when we cast the instance of child to parent, and call the method it will now return 1.
And that is because the method in the parent implementation is not replaced by the new implementation in the child class.

The functional modifiers
These modifiers specify functional behavior of the method:
emptyempty means that the method will not be implemented in this class implementation, but in contrast to the abstract modifier, this empty method can be called and is not virtual by default.
asyncthe async modifier marks the method as an asynchronous method that will run in the background.
lockedThe locked modifier changes the behavior of the method in such a way that it becomes thread-safe; only one thread at a time can call this method. If more threads want to call this method simultaneously, the threads have to wait for each other.
locked on <expression>The locked on modifier behaves the same as locked, but works on an expression. If more methods or properties use the same expression than only one thread can run one of these methods or properties at once.
iteratorThe iterator modifier marks the method as a dynamic iterator (that has to yield it's results).
Async, locking and iterators will be the subject of future posts where I will explain them further.


The compiler-hint modifiers
These modifiers help the compiler to generate the correct code for this method:
implements When this method implements an interface method - but has another name than expected within the interface.
The compiler hint implements IInterfaceName.MethodName tell's the compiler which interface method is being implemented here.
inlineThe inline modifier tels the compiler to inline this method instead of generating a function call.
partialThe partial modifier is used in partial classes. if one partial class has a method defined as partial; empty; then a second partial class of the same class can implement this method with the partial modifier.
externTells the compiler that this method is implemented in an external library.
raisesJava caller only.
Tells the java caller which exceptions could be raised by this method.
unsafe.Net only.
Tells the compiler that this method is doing unsafe operations like pointer operations. This modifier makes sure that the heap is not being compressed or garbage collected during the execution of this method.
Partial classes, external libraries and unsafe code will be the subject of future posts where I will explain them further.

The next post will cover the method implementation.


Saturday, May 19, 2018

Method definition

I try to explain the method syntax of Oxygene Pascal in this post.

Methods are the named code parts where a small part of the functional problem that the application handles is solved.

In other Pascal dialects, the keyword Function is used for methods that return a value, while the keyword Procedure is used for methods that do not return a value. While Oxygene Pascal supports this syntax, the it is preferred  to use the Method keyword for both.

Methods are declared within the class definition (see  The structure of a Pascal file).
The visibility (see Visibility modifiers) of the method is determent by the visibility section where it is declared.


Method declaration
The most simple form of a Method declaration:
The name of this method is MethodName, it has no return value (so, a procedure) and no parameters.

To add a return value, simply add ": type" to the declaration:
This function will return a string when it is called.


Tuples
Oxygene Pascal has also support for Tuples, a way to return more than one return value:
In this case the function returns three distinct values.


Instance and static methods
In the above examples, we were writing instance methods. Instance methods are only available in an instance of the class. To create a static method, the method must be prefixed with the "class" keyword:

A static method can be called without an instance being created - just simply call the method in the form of classname.methodname.


Parameters
Next we can add parameters to the method.
There are four different kinds of parameters available; by value, by reference, output and constant parameters:
The parameters work as following:
by value
(no prefix)
For value type variables:
The variable is copied to the method but never copied back.
When the variable is changed within the implementation of the method, the original variable will not be changed.

For reference type variables:
The pointer to the variable is copied to the method but never copied back
If the variable is re-assigned in the method implementation, the original variable is not changed, but when properties or fields of the reference type are changed, these will change in the original too, because the copied pointer points to the same memory.
by reference
(var prefix)
For value type variables:
The variable is copied before the method is called and copied back to the original variable when the method exits;when the variable is changed within the implementation of the method, the original variable will be changed too.

For reference type variables:
The pointer to the variable is copied to the method and copied back to the original variable when the method exits - if the variable is re-assigned in the method implementation or when properties or fields are changed, the original variable is changed too.
output
(out prefix)
The variable used to call the method is not copied to the method, but the variable has a value of Default<type> when the method starts. This means that the value is nil for reference types or the default of the used value type at the start of the method implementation. When the method exits, the new content of the out variable is copied back to the calling variable.
constant
(const prefix)
For value type variables:
The variable is copied before the method is called but never copied back. The variable is immutable within the method implementation.

For reference type variables: 
 The pointer to the variable is copied to the method but never copied back. The  pointer to the variable itself is immutable and cannot be re-assigned within the method implementation. But when properties or fields are changed, the original these changes are reflected in the calling variable too.

A method can have more parameters, they are separated with a semicolon:

Default value for a parameter
Further, a parameter can have a default value. This default value is used when the parameter is omitted when the function is called:
When this function is called without the s parameter  MethodName(i); s will have the value of  "the default value" at the start of the method implementation.


Parameter arrays
With a parameter array, the method gets an unending amount of parameters with all the same type.
It is defined as:
the parameter type is always an array of <type>, in this case an object, so any type can be used in the call. When, by example, using an array of string as type for the parameter, only strings can be passed.

Multi part methods
A multi part method has its parameters between the name of the method, to create a very readable syntax. Take the following standard method:
This is not very readable. But when we use a multipart method, everything becomes clear:

And I think that these multipart methods are a beautiful end to this post.