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. 




Visibility modifiers

In this post I try to explain the visibility modifiers available within Oxygene Pascal.

The visibility of a class is an OO way to hide the implementation of the class for other code.
The purpose of this is that other code can not influence the state of the object in a way that is unexpected within the design.

In VB.Net I had the following four visibility modifiers (ordered from most hidden to least hidden):

Private (VB.Net)Private means in VB.Net that the members and types are only visible within the class implementation itself and within the same code unit - so any implementation of any class within the same code module can see this code.
Friend (VB.Net)Friend means in VB.Net that them embers and types are visible to all code within the same project.
Protected (VB.Net)Protected means in VB.Net that the members and types are only visible within the class implementation itself, in all the classes that inherit from it and within the same code unit - so any implementation of any class within the same code module can see this code.
Public (VB.Net)Public means in VB.Net that the members and types are visible to all code, including other projects that references this assembly.
As you can see, in VB.Net is is impossible to hide code from other code within the same class.
Note: There were 2 more added recently; Protected Friend and Private Protected

With Oxygene, you can manage the visibility a lot better; instead of only four levels of visibility, Oxygene provides nine levels! As with a lot of things in the Oxygene language, the developers thought of everything possible (ordered from most hidden to least hidden):

Private
(Oxygene)
Private means that the members are only visible within the class implementation itself. And nowhere else. (also know as strict private).
You can only use this for members (fields, properties and methods), not for types.
Unit and Protected
(Oxygene)
Unit and Protected means in that the members and types are only visible within the class implementation itself, and to classes the inherit from this class as long as they are defined in the same code file.
You can only use this for members (fields, properties and methods), not for types.
Unit
(Oxygene)
Unit means that the members and types are only visible within the current code unit.
(same as Private in VB.Net)
Unit or Protected
(Oxygene)
Unit or Protected means that the members and types are only visible within the class implementation itself, to classes the inherit from this class and to all code within the same code file.
You can only use this for members (fields, properties and methods), not for types.
(same as Protected in VB.Net- but there it can be used for types also)
Assembly and Protected
(Oxygene)
Assembly and Protected means  that the members and types are only visible within the class implementation itself, and to classes the inherit from this class as long as they are defined in the same project.
You can only use this for members (fields, properties and methods), not for types.
(same as Private Protected in VB.Net)
Assembly
(Oxygene)
Assembly means that the members and types are only visible within the current project.
(same as Friend in VB.Net)
Assembly or Protected
(Oxygene)
Assembly or Protected means that the members and types are only visible within the class implementation itself, to classes the inherit from this class and to all code within the project.
You can only use this for members (fields, properties and methods), not for types.
(same as Protected Friend in VB.Net)
Protected
(Oxygene)
Protected means that the members and types are only visible within the class implementation itself and to classes the inherit from this class.
Public
(Oxygene)
Public means in that the members and types are visible to all code, including other projects that references this assembly.
(same as Public in VB.Net)

In Free Pascal and Delphi there is also the Published visibility modifier - that is used to publish properties for the form designers. This is not needed in .Net; the BrowsableAttribute is used for this.

To be exact, the Public modifier in Oxygene is analog to the published modifier in Free Pascal and Delphi. To get the Public behavior from Free Pascal and Delphi, you need to use the Browsable attribute:

public
  [Browsable(False)]
  property ....

And that was all folks.
In the next post I will talk about the method definition.

Friday, May 18, 2018

The structure of a Pascal file

First I like to talk about the structure of an Oxygene Pascal file, as it is somewhat different from other languages - it is even somewhat different from other Object Pascal dialects to fit better in the Microsoft Visual Studio environment.

In the picture below you see the structure, as you can see, the definition and implementation is strictly separated from each other. This way the structure of the class is always clear for the developer- a thing that is missing in most other languages.

Object Pascal file structure


The namespace is not a standard Object Pascal keyword. In other versions of Pascal, the keyword Unit is used here, but in .Net Unit has no meaning. That's why the namespace is used instead, as each class in .Net is in a namespace.

The keyword interface defines that the interface definitions follow - interface definitions are all type definitions within this files; classes, structures, enums, type aliases, and so on.

The uses section is a standard Object Pascal keyword, but is used for another purpose in Oxygene; In standard Object Pascal, the uses clause points to all files (units) that are needed for this unit to compile (in Visual Studio, you have the project references for this).
In Oxygen, the uses keyword is used to import namespaces, like Imports in VB.net or Using in C#. 
Other than in VB, only the types are imported, not the embedded Namespaces.
So If you have System.Collections in the uses, you can not write Generics.List ....
You have to add System.Collections.Generics, to be able to write List....

Next, a type definition follows (in this example a class). You can define as may types as you want.

After the type definitions, the implementation section begins - in this section all code will be written, and the file is finally closed with the End. (including the period) keyword.


The journey begins

In 1981 I bought my first computer; a timex sinclair 1000, coupled to a 66cm black and white television. I had the whopping memory of 2kb and a simple Sinclair Basic interpreter available, and I started programming. After as while, I bought a 16kb(!) memory extension module, and my quest to understand programming began. First I made some simple programs in Basic, but soon I went to program in Z80 machine code (no, not assembler, I had to type the hexadecimal codes) - I was 12 years old at that moment.

A few years later I changed to the Sinclair ZX Spectrum, 48kb memory with a color television(!), continued with programming, but also used it for gaming. And I loved my computer.
Then, again a few years later, the Sinclair QL came, with Super Basic, a Basic dialect that resembles current day Basic (with functions(!)) and had influences from Pascal. On this machine I really learned how to program (by then I was 17 years old).

In 1992, I finally had enough money to buy me a 80286 clone at 20Mhz with windows 3.1 and a VGA monochrome display, and soon I was playing with Visual Basic 3.0. I experimented with OS/2 2.1 and OS/2 Warp (at that time I upgraded to a 80486 40MHz). But Microsoft won the OS war, and when everyone was running Windows 95, I did not - I ran Windows NT 3.5, a true 32 bits OS with preemptive multitasking - the father of all our current windows versions.

In 1994 I got my first programming job, working in MSDOS with Microsoft Professional Development system 7.1, a compiled Basic variant. In my next job I worked with Borland Delphi, a revolutionary programming system based on Object Pascal.
Nice to know: The creator of Delphi, Anders Hejlsberg, is also the father of current day C#.

From there, I ended up programming VB versions 5 and 6, followed by VB.Net  versions 2005, 2008, 2010, 2015 and 2017.
But I always kept missing Delphi. I somehow had a click with it - even after I had not used it for more than 20 years.

As VB.Net is dying now, I went looking for another development system than VB.Net.
What I wanted in this language was:
- Case insensitive
- No curly brackets (I hate them)
- Object oriented
- Support for Windows, IOS and Android.

After tests with current day Delphi, Free Pascal, Lazarus and OmniPascal, I ended up with Remobjects Oxygene, a modern day Object Pascal development environment for .Net, Mono, Cocoa and Android. Even native compilation is supported for several development types.

I just started with this product and this blog will follow me on my adventures with this development system.

The purpose of this blog for me is to learn all in's and out's of the Oxygene product and to help others to learn about it.