January 29, 2021

Linking classes and properties with RDF

At its core, any RDF document is just a collection of semantic triples, recognized by any basic RDF tool. However, the call for standardization and mutual intelligibility has led to several ways to describe the schema that the data should follow, with two use cases in mind: reasoning and validation.

December 22, 2020

Describing foaf:membershipClass in OWL

I've recently discovered RDF, one of the web's rising frameworks for identifying and describing data, made for the web of linked data. It can describe people, institutions, accounts, places, events, languages, documents, and much more thanks to the vast range of standardized vocabularies for different concepts, entities, and relations. The core unit of information in RDF is the semantic triple: subject, predicate, and object. The individual concepts (resources) are identified with URIs, brining universal identification, verification, and navigation to pieces of data.

There are numerous vocabularies (ontologies) for RDF, and one of them is FOAF (Friend of a Friend), used for describing people and their online presence, as well as general groups of people. One of the properties a group in FOAF (class foaf:Group) can have is foaf:membershipClass. This states that people in a specific group can be thought of as members of a particular class, that the two sets of people are equal.

There is also OWL, an ontology of ontologies, a vocabulary for describing vocabularies. The purpose of this metaontology is assisting reasoners in deriving additional facts from data, forming a complex knowledge base. Even though there are simpler schemata that are sometimes enough (RDFS), OWL defines things like identity, equivalency of classes and properties, and constructions of anonymous classes and properties in terms of relations to other classes and properties.

There are parts of FOAF that are hard to describe using OWL, and foaf:membershipClass is one of those, since it links an individual (group) to a class. I will now try to describe it with OWL (using the Turtle language).

December 19, 2019

The four kinds of a reference

This article applies not only to C#, but also to other languages with references, like C++.

A reference is a special type that allows you to access data stored in another location separate from the variable that contains the reference. When accessing a reference variable, indirection is automatically performed, i.e. first the actual address to the remote variable is fetched, then the object stored in the variable is accessed. This behaviour is distinct from pointers, which employ the same indirection mechanisms, but are treated as normal values and so dereferencing must be explicit.

December 23, 2016

Invoking a delegate from inside a dynamic method

As always, one question at StackOverflow attracted my attention and made me program all the night. The question was actually about a way to refer to a predefined object in a dynamically emitted method in a dynamic assembly. That is actually quite an easy task, provided you aren't going to save the assembly and use it later in a different program. In this case, simply use some way to refer to the object using a number (add it to a list, or use a GCHandle) and there's nothing easier than emitting an integer in CIL.

If you want to save the assembly, this approach obviously will not work, as the object will be lost when you quit the runtime. In this case, you'd have to find an optimal way to serialize the desired object, either directly calling its constructor in method, or use a serializer and put the result in the assembly resource space.

However, for some strange reason, I didn't immediately think about those two ways, probably because it was late night. Instead, I thought about compiled lambdas in Linq.Expressions and how closures work there (mainly Expression.Constant). Behind all that emitting, it's actually quite simple - if you know how delegates work. Someone coming over from the land of C will think about delegates as wrappers for function pointers, but it's more than that. You can bind a function pointer to a specific target object, which is then internally used as the first argument to the method (you can actually even bind static methods to target objects, and they behave as expected).

LINQ Expressions work the same way - the compiled lambda is dynamically emitted, and non-primitive constants are placed in a special container, which is then used as the target object of the created delegate. The compiled method would then access the container as easily as using this in an instance method. Provided I wouldn't have to save the assembly, what if I were to bind the desired object to a delegate and then call that delegate in the dynamic assembly?

The immediate problem here is obvious - the delegate has a target object, and I still have no way (ignore the first paragraph) to refer to it from inside the dynamic method. What I would want is a way to generate a piece of code that somehow stores the delegate and its target object, and would allow me to call it as a raw function pointer. Hmm, is there something in .NET that does that?

July 24, 2016

C++/CLI type system as seen from .NET and CIL

For some time now, I have delved, out of necessity, into C++ and all its quirks and secrets. One thing that has always fascinated me in C++ is its marvelously complex type system. In C#, you can mostly just work with arrays, pointers are possible but not recommended, and also generics. C++ has loads of declarators – arrays with fixed size, pointers, references, and this all can be combined with anything else and also qualifiers – mostly const and volatile. These two keywords also exist in C#, but they have vastly different meaning.

Now you may be surprised or not, but all these constructions are actually accurately representable in Common Intermediate Language (CIL for short), the language that separates all .NET languages from native code. Though C# doesn't show the full potential of its type system (however, the newest drafts have quite appealing suggestions, like ref returns), in CIL, the type system is as rich as C++'s, maybe even richer.

C++/CLI is a beautiful and well-designed combination of C++ and .NET, and shall serve as an example of how its types are translated into CIL. If you are not familiar with C++ at all, don't worry, I'll be easy on you. The following descriptions will be mainly from the C# perspective; all in all, that's from whence I come.

Let's start with an overview of what types we'll have to consider:

July 31, 2015

The Cloneable pattern

For most languages that deal with OOP, one concept is always quite hard to approach. The cloning of objects. First of all, there are two implementational methods of cloning – deep cloning and shallow cloning. Deep cloning analyzes the whole structure of the object and the objects the instance references, and provides a complete copy, separated from the original structure. Shallow copy, on the other hand, only copies the most accessible data, the technical value of the object (in C#, values of all fields).
In C#, shallow copy of the current object is provided by the protected method MemberwiseClone, which is almost totally useless (good only for simple sealed classes). Not only it isn't accessible outside the object, but in most cases, you cannot use it to help you with implementing your own cloning, as it returns an already initialized object.
Fortunately, there is an interface which is used for this purpose – ICloneable. However, there is a commonly adressed problem about this interface: does it mean deep or shallow copy?
In turns out, neither. This is what the documentation says:
Supports cloning, which creates a new instance of a class with the same value as an existing instance.
Now what is the value of an object? The technical value are the values of all non-static fields of the instance, including references, but the semantical value depends on the semantical meaning of those fields. A field (or a property) can mean two things: association and composition (used mostly in C++). Association simply associates two objects, they reference each other, but do not depend on each other. Composition puts objects into ownership state, where one object owns other objects, which can't exist without the owner. The IDisposable pattern is similar to composition, when there are resources that are disposed if the owner is disposed (even if they are referenced outside the object).
So a field basically means two things: "I exist outside of this object, and the object only uses me", or "I am part of this object, and I can't exist without it". The second meaning is what makes the semantical value of the object.
Unfortunately, C# doesn't provide the means to differentiate between those meanings (it is similar to C++/CLI reference types with value-type semantics, like System::Object without the ^). If I have a Wall that contains a Window, it is in the ownership relation, and thus cloning it should yield a new wall with a new window. On the other hand, if the wall keeps a reference to the House it is in, cloning shouldn't create a new house.
Enough theory, how to implement it?

public class House
{
    
}

public class Wall : ICloneable
{
    public Window Window{get; private set;}
    public House House{get; private set;}
    
    protected Wall(Wall prototype)
    {
        Window = (Window)prototype.Window.Clone(); //creates a new window
        House = prototype.House; //keeps one house 
    }
    
    public virtual object Clone()
    {
        return new Wall(this);
    }
}

public class Window : ICloneable
{
    public int Size{get; private set;}
    
    protected Window(Window prototype)
    {
        Size = prototype.Size;
    }
    
    public virtual object Clone()
    {
        return new Window(this);
    }
}

This utilizes the copy-constructor technique to initialize an object from a prototype, and allows extensibility for derived classes to implement their own cloning. The copy-constructor is protected to make programmers use the Clone method instead of the constructor.
A problem with this approach is that the cloning method doesn't specify what it returns, although it it the part of the contract.

public class Wall : ICloneable
{
    public Window Window{get; private set;}
    public House House{get; private set;}
    
    protected Wall(Wall prototype)
    {
        Window = prototype.Window.Clone();
        House = prototype.House;
    }
}

public class Window : ICloneable
{
    public int Size{get; private set;}
  
    protected Window(Window prototype)
    {
        Size = prototype.Size;
    }
  
    object ICloneable.Clone()
    {
        return CloneImpl();
    }
    public Window Clone()
    {
        return (Window)CloneImpl();
    }
    protected virtual object CloneImpl()
    {
        return new Window(this);
    }
}

public class TrueWindow : Window
{
    protected TrueWindow(TrueWindow prototype) : base(prototype)
    {
      
    }
  
    public new TrueWindow Clone()
    {
        return (TrueWindow)CloneImpl();
    }
    protected override object CloneImpl()
    {
        return new TrueWindow(this);
    }
} 

There is no real way for the ICloneable interface to limit the implementing class to return itself, but at least this way it is apparent for the outside that it does so, at the cost of three methods in the base class and two methods in each derived class.
Or is there are way to limit it better? What if we introduce a generic ICloneable<T> interface to do it? Well, let's see:

public interface ICloneable<out T> : ICloneable where T : ICloneable<T>
{
    new T Clone();
}

public class Wall : ICloneable<Wall>
{
    public Window Window{get; private set;}
    public House House{get; private set;}
    
    protected Wall(Wall prototype)
    {
        Window = prototype.Window.Clone();
        House = prototype.House;
    }
    
    object ICloneable.Clone()
    {
        return this.Clone();
    }
    public Wall Clone()
    {
        return (Wall)CloneImpl();
    }
    protected virtual object CloneImpl()
    {
        return new Wall(this);
    }
}

public class Window : ICloneable<Window>
{
    public int Size{get; private set;}
  
    protected Window(Window prototype)
    {
        Size = prototype.Size;
    }
  
    object ICloneable.Clone()
    {
        return CloneImpl();
    }
    public Window Clone()
    {
        return (Window)CloneImpl();
    }
    protected virtual object CloneImpl()
    {
        return new Window(this);
    }
}

public class TrueWindow : Window, ICloneable<TrueWindow>
{
    protected TrueWindow(TrueWindow prototype) : base(prototype)
    {
      
    }
  
    public new TrueWindow Clone()
    {
        return (TrueWindow)CloneImpl();
    }
    protected override object CloneImpl()
    {
        return new TrueWindow(this);
    }
} 

Not that hard, actually. We've now introduced a contract that an object implementing ICloneable<T> clone-returns T. We can't really limit it to the actual type of the object, but this is the best we can get.
But was it really necessary?
In our attempt to get rid of a cast, we have introduced a new painful-to-implement interface, and lots of other unnecessary methods in all classes. What we really needed was a method that clones the object and casts it to its type. Extension methods to the rescue!

public static T Copy<T>(this T obj) where T : ICloneable
{
    return (T)obj.Clone();
}

The only problem left is cloning structures, which require boxing and unboxing the value. Although structures aren't usually used to represent such complex principles, we can clone them, too:

public struct WallStructure : ICloneable
{
    public Window Window{get; private set;}
    
    private WallStructure(WallStructure prototype) : this()
    {
        Window = prototype.Window.Clone();
    }
    
    object ICloneable.Clone()
    {
        return Clone();
    }
    
    public WallStructure Clone()
    {
        return new WallStructure(this);
    }
}

As you can see, it is possible and not so hard, but you shouldn't really design structures like that. As structures are passed by value, one might expect that it is the same what Clone does (although if it was, there would be no need of the public method and the copy-constructor at all). ICloneable on structures is useful only when you want to clone the boxed value, not the unboxed one.

I hope I have clarified the correct way of cloning objects, and the semantical value of objects. See you next time!