Two New Oxygene Language Features
We've added two cool new language features to Oxygene this week:
Required Properties
Properties in Oxygene can now be marked with the required
directive. The new directive addition mandates explicit initialization of the properties every time an instance of the containing class or any of its descendants is created. This enhancement directly promotes the principle of fail-fast, which allows developers to detect potential issues at the earliest stages of instantiation.
In Oxygene, when using a constructor that does not implicitly initialize the property, a clear value must be provided through a Property Initializer in the new
call, for any required
properties. Here's an example of how to apply this feature:
type
Person = class
public
property Name: String; required;
...
end;
new Person(Name := 'Wednesday');
In the above example, the Person
class has a property Name
that is required. This indicates that the property must be explicitly initialized whenever a new instance of Person
is created.
Suppose you forget to provide a value for the Name
property when you create a new Person
instance? In that case, the compiler will generate an error, preventing the inadvertent creation of objects in an invalid state.
Inline Variable Declarations in is Type Checks
A second new feature has been introduced to further streamline and simplify programming tasks: Inline Variable Declarations in is
type checks. This addition promotes not only readability but also enhances code efficiency. Essentially, the source value is type-cast to the target type, if it matches, and made available as a new named variables.
To illustrate this new feature, consider the following example:
var p: Person := FindPersonByName("Peter Parker");
if p is var e: Employee then begin
e.GiveRaise; // e is always assigned, here
end;
writeLn($'was employee? {assigned(e)}"); // e may be nil here
The above code snippet exemplifies how Inline Variable Declarations work. When the condition is checked, a new inline variable e
of type Employee
is declared. If p
is indeed an Employee
, e
gets assigned the cast value and you can immediately use it within the scope of the 'if' statement. Even after exiting the if
scope, e
remains valid but can potentially be nil
if the cast condition was not met. This example would be equivalent to a more verbose block of code:
Through the use of the new and improved is ... var
feature, Oxygene delivers a more efficient, cleaner syntax, enhancing the programming experience. This feature enhances the language's versatility, making it a more compelling choice for developers invested in crafting effective, efficient, and readable code.
Get Oxygene Now
Both new features discussed here are available in today's new build .2841 of Oxygene and Elements.