Logtalk user manual
Categories
Contents > User Manual > Categories

# Categories

Categories are fine-grained units of code reuse and can be regarded as a dual concept of protocols. Categories provide a way to encapsulate a set of related predicate declarations and definitions that do not represent a complete object and that only make sense when composed with other predicates. Categories may also be used to break a complex object in functional units. A category can be imported by several objects (without code duplication), including objects participating in prototype or class-based hierarchies. This concept of categories shares some ideas with Smalltalk-80 functional categories [Goldberg 83], Flavors mix-ins [Moon 86] (without necessarily implying multi-inheritance), and Objective-C categories [Cox 86]. Categories may also complement existing objects, thus providing a hot patching mechanism inspired by the Objective-C categories functionality.

## Defining a new category

We can define a new category in the same way we write Prolog code: by using a text editor. Logtalk source files may contain one or more objects, categories, or protocols. If you prefer to define each entity in its own source file, it is recommended that the file be named after the category. By default, all Logtalk source files use the extension `.lgt` but this is optional and can be set in the adapter files. Intermediate Prolog source files (generated by the Logtalk compiler) have, by default, a `_lgt` suffix and a `.pl` extension. Again, this can be set to match the needs of a particular Prolog compiler in the corresponding adapter file. For instance, we may define a category named `documenting` and save it in a `documenting.lgt` source file that will be compiled to a `documenting_lgt.pl` Prolog file.

Category names can be atoms or compound terms (when defining parametric categories). Objects, categories, and protocols share the same name space: we cannot have a category with the same name as an object or a protocol.

Category code (directives and predicates) is textually encapsulated by using two Logtalk directives: `category/1-3` and `end_category/0`. The most simple category will be one that is self-contained, not depending on any other Logtalk entity:

    :- category(Category).
        ...
    :- end_category.

If a category implements one or more protocols then the opening directive will be:

    :- category(Category,
        implements(Protocol1, Protocol2, ...)).
        ...
    :- end_category.

A category may be defined as a composition of other categories by writing:

    :- category(Category,
        extends(Category1, Category2, ...)).
        ...
    :- end_category.

This feature should only be used when extending a category without breaking its functional cohesion (for example, when a modified version of a category is needed for importing on several unrelated objects). The preferred way of composing several categories is by importing them into an object. When a category overrides a predicate defined in an extended category, the overridden definition can still be used by using the `alias/2` predicate directive.

A category may explicitly complement one or more existing objects, thus providing hot patching functionality similar to Objective-C categories:

    :- category(Category,
        complements(Object1, Object2, ....)).
        ...
    :- end_category.

This allows us to patch existing functionality or add new functionality to existing objects without requiring access or modifications to their source code. Common uses are adding logging or debugging predicates to a set of objects. Complementing categories may also be used to define aliases for complemented object predicates. Complemented objects need to be compiled with the `complements` compiler option set `allow` (to allow both patching and adding new functionality) or `restrict` (to allow only adding new functionality).

An unfortunate consequence of allowing an object to be patched using a complementing category is that it disables the use of static binding optimizations for messages sent to the object as it can always be later patched, thus rendering the static binding optimizations invalid.

Categories cannot inherit from objects. In addition, categories cannot define clauses for dynamic predicates. This restriction applies because a category can be imported by several objects and because we cannot use the database handling built-in methods with categories (messages can only be sent to objects). However, categories may contain declarations for dynamic predicates and they can contain predicates which handle dynamic predicates. For example:

    :- category(attributes).

        :- public(attribute/2).
        :- public(set_attribute/2).
        :- public(del_attribute/2).

        :- private(attribute_/2).
        :- dynamic(attribute_/2).

        attribute(Attribute, Value) :-
            ::attribute_(Attribute, Value).          % called in the context of "self"

        set_attribute(Attribute, Value) :-
            ::retractall(attribute_(Attribute, _)),  % retracts clauses in "self"
            ::assertz(attribute_(Attribute, Value)). % asserts clause in "self"

        del_attribute(Attribute, Value) :-
            ::retract(attribute_(Attribute, Value)). % retracts clause in "self"

    :- end_category.

Each object importing this category will have its own `attribute_/2` private, dynamic predicate. The predicates `attribute/2`, `set_attribute/2`, and `del_attribute/2` always access and modify the dynamic predicate contained in the object receiving the corresponding messages (i.e. self). But it's also possible to define predicates that handle dynamic predicates in the context of this instead of self. For example:

    :- category(attributes).

        :- public(attribute/2).
        :- public(set_attribute/2).
        :- public(del_attribute/2).

        :- private(attribute_/2).
        :- dynamic(attribute_/2).

        attribute(Attribute, Value) :-
            attribute_(Attribute, Value).            % called in the context of "this"

        set_attribute(Attribute, Value) :-
            retractall(attribute_(Attribute, _)),    % retracts clauses in "this"
            assertz(attribute_(Attribute, Value)).   % asserts clause in "this"

        del_attribute(Attribute, Value) :-
            retract(attribute_(Attribute, Value)).   % retracts clause in "this"

    :- end_category.

When defining a category that declares and handles dynamic predicates, working in the context of this ties those dynamic predicates to the object importing the category while working in the context of self allows each object inheriting from the object that imports the category to have its own set of clauses for those dynamic predicates.

## Finding defined categories

We can find, by backtracking, all defined categories by using the `current_category/1` Logtalk built-in predicate with a non-instantiated variable:

    | ?- current_category(Category).

This predicate can also be used to test if a category is defined by calling it with a valid category identifier (an atom or a compound term).

## Creating a new category in runtime

A category can be dynamically created at runtime by using the `create_category/4` built-in predicate:

    | ?- create_category(Category, Relations, Directives, Clauses).

The first argument should be either a variable or the name of the new category (a Prolog atom, which must not match with an existing entity name). The remaining three arguments correspond to the relations described in the opening category directive and to the category code contents (directives and clauses).

For instance, the call:

    | ?- create_category(ccc,
                         [implements(ppp)],
                         [private(bar/1)],
                         [(foo(X):-bar(X)), bar(1), bar(2)]).

is equivalent to compiling and loading the category:

    :- category(ccc,
        implements(ppp)).

        :- dynamic.

        :- private(bar/1).

        foo(X) :-
            bar(X).

        bar(1).
        bar(2).

    :- end_category.

If we need to create a lot of (dynamic) categories at runtime, then is best to to define a metaclass or a prototype with a predicate that will call this built-in predicate in order to provide more sophisticated behavior.

## Abolishing an existing category

Dynamic categories can be abolished using the `abolish_category/1` built-in predicate:

    | ?- abolish_category(Category).

The argument must be an identifier of a defined dynamic category, otherwise an error will be thrown.

## Category directives

Category directives are used to define category properties, to document a category dependencies on other Logtalk entities, and to load the contents of files into a category.

### Dynamic categories

As usually happens with Prolog code, a category can be either static or dynamic. A category created during the execution of a program is always dynamic. A category defined in a file can be either dynamic or static. Dynamic categories are declared by using the `dynamic/0` directive in the category source code:

    :- dynamic.

The directive must precede any predicate directives or clauses. Please be aware that using dynamic code results in a performance hit when compared to static code. We should only use dynamic categories when these need to be abolished during program execution.

### Category documentation

A category can be documented with arbitrary user-defined information by using the `info/1` directive:

    :- info(List).

See the documenting Logtalk programs section for details.

### Loading files into a category

The `include/1` directive can be used to load the contents of a file into a category. See the objects section for an example of using this directive.

## Category relationships

Logtalk provides two sets of built-in predicates that enable us to query the system about the possible relationships that a category can have with other entities.

The built-in predicates `implements_protocol/2-3` and `conforms_to_protocol/2-3` allows us to find which categories implements which protocols:

    | ?- implements_protocol(Category, Protocol, Scope).

or, if we also want inherited protocols:

    | ?- conforms_to_protocol(Category, Protocol, Scope).

Note that, if we use a non-instantiated variable for the first argument, we will need to use the `current_category/1` built-in predicate to ensure that the returned entity is a category and not an object.

To find which objects import which categories we can use the `imports_category/2` or `imports_category/3` built-in predicates:

    | ?- imports_category(Object, Category).

or, if we want to know the importation scope:

    | ?- imports_category(Object, Category, Scope).

Note that a category may be imported by several objects.

To find which categories extend other categories we can use the `extends_category/2` or `extends_category/3` built-in predicates:

    | ?- extends_category(Category1, Category2).

or, if we want to know the extension scope:

    | ?- extends_category(Category1, Category2, Scope).

Note that a category may be extended by several categories.

To find which categories explicitly complement existing objects we can use the `complements_object/2` built-in predicate:

    | ?- complements_object(Category, Object).

Note that a category may explicitly complement several objects.

## Category properties

We can find the properties of defined categories by calling the built-in predicate `category_property/2`:

    | ?- category_property(Category, Property).

The following category properties are supported:

`static`
  The category is static
`dynamic`
  The category is dynamic (and thus can be abolished in runtime by calling the `abolish_category/1` built-in predicate)
`built_in`
  The category is a built-in category (and thus always available)
`file(Path)`
  Absolute path of the source file defining the category (if applicable)
`file(Basename, directory)`
  Basename and directory of the source file defining the category (if applicable)
`lines(BeginLine, EndLine)`
  Source file begin and end lines of the category definition (if applicable)
`events`
  Messages sent from the category generate events
`public(Predicates)`
  List of public predicates declared by the category
`protected(Predicates)`
  List of protected predicates declared by the category
`private(Predicates)`
  List of private predicates declared by the category
`declares(Predicate, Properties)`
  List of properties for a predicate declared by the category
`defines(Predicate, Properties)`
  List of properties for a predicate defined by the category
`includes(Predicate, Entity, Properties)`
  List of properties for an object multifile predicate that are defined in the specified entity (the properties include `number_of_clauses(Number)` and `line_count(Line)` with `Line` being the begin line of the multifile predicate clause)
`provides(Predicate, Entity, Properties)`
  List of properties for other entity multifile predicate that are defined in the category (the properties include `number_of_clauses(Number)` and `line_count(Line)` with `Line` being the begin line of the multifile predicate clause)
`calls(Call, Properties)`
  List of properties for predicate calls made by the category (`Call` is either a predicate indicator or a control construct such as `^^/1` with a predicate indicator as argument; note that `Call` may not be ground when the control construct is `::/2` and the object argument is only know at runtime; the properties include `caller(Caller)` and `line_count(Line)` with `Caller` being a predicate indicator and `Line` being the begin line of the predicate clause or directive making the call)
`number_of_clauses(Number)`
  Total number of predicate clauses defined in the category (includes both user-defined clauses and auxiliary clauses generated by the compiler or by expansion hooks)
`number_of_user_clauses(Number)`
  Total number of user-defined predicate clauses defined in the category

Some of the properties are only available when the category is defined in a source file compiled with the `source_data` flag turned on.

## Importing categories

Any number of objects can import a category. In addition, an object may import any number of categories. The syntax is very simple:

    :- object(Object,
        imports(Category1, Category2, ...)).
        ...
    :- end_object.

To make all public predicates imported via a category protected or to make all public and protected predicates private we prefix the category's name with the corresponding keyword:

    :- object(Object,
        imports(private::Category)).
        ...
    :- end_object.

or:

    :- object(Object,
        imports(protected::Category)).
        ...
    :- end_object.

Omitting the scope keyword is equivalent to writing:

    :- object(Object,
        imports(public::Category)).
        ...
    :- end_object.

## Using category predicates

Category predicates can be called from within an object using either the message sending mechanisms or a direct call. Consider the following category:

    :- category(output).

        :- public(out/1).

        out(X) :-
            writeq(X), nl.

    :- end_category.

Using the message sending mechanisms, the predicate `out/1` can be called from within an object importing the category by simply sending a message to self. For example:

    :- object(worker,
        imports(output)).

        ...
        do(Task) :-
            execute(Task, Result),
            ::out(Result).
        ...

    :- end_object.

This is the recommended way of calling category predicates as it supports the specialization/redefinition of the category predicate in a descendant object (as the predicate declaration and definition lookups will start from self). Messages to self usually imply the use of dynamic binding as the actual object that will receive the message is only known at runtime. This translates to a small performance penalty when compared with calls to local object predicates.

It is also possible to perform direct calls to predicates from imported categories without using the message sending mechanisms with the `^^/1` control construct. For example:

    :- object(worker,
        imports(output)).

        ...
        do(Task) :-
            execute(Task, Result),
            ^^out(Result).
        ...

    :- end_object.

This alternative should only be used when the user knows a priori that the category predicates will not be specialized or redefined by descendant objects of the object importing the category. Its advantage is that, when the `optimize` compiler flag is turned on, the Logtalk compiler will try to optimize the calls by using static binding. When dynamic binding is used due to e.g. the lack of sufficient information at compilation time, the performance is similar to calling the category predicate using a message to self (in both cases a predicate lookup caching mechanism is used).

## Parametric categories

Category predicates can be parameterized in the same way as object predicates by using a compound term as the category identifier and by calling the `parameter/2` built-in local method in the category predicate clauses. Category parameter values can be defined by the importing objects. For example:

    :- object(speech(Season, Event),
        imports(dress(Season), speech(Event))).

        ...

    :- end_object.

Note that access to category parameters is only possible using the `parameter/2` method from within the category. Calls to the `this/1` built-in local method from category predicates always access the importing object identifier (and thus object parameters, not category parameters).