Welcome to Scribd, the world's digital library. Read, publish, and share books and documents. See more
Download
Standard view
Full view
of .
Look up keyword
Like this
2Activity
0 of .
Results for:
No results containing your search query
P. 1
The C Object System

The C Object System

Ratings: (0)|Views: 17|Likes:
Published by Señor Smiles

More info:

Published by: Señor Smiles on May 09, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

12/23/2012

pdf

text

original

The C Object System\u2217
Using C as a High-Level Object-Oriented Language
Laurent Deniau
CERN \u2013 European Organization for Nuclear Research
laurent.deniau@cern.ch
Abstract

The C Object System (COS) is a small C library which im- plements high-level concepts available in CLOS, OBJECTIVE- C and other object-oriented programming languages:uni-

form object model(class, metaclass and property-metaclass), generic functions, multi-methods, delegation, properties, ex- ceptions, contractsand closures. COS relies on the program-

mable capabilities of the C programming language to extend its syntax and to implement the aforementioned concepts as\ufb01rst-class objects. COS aims at satisfying several general principles likesimplicity, extensibility, reusability, ef\ufb01ciency andportability which are rarely met in a single program- ming language. Its design is tuned to provide ef\ufb01cient and portable implementation ofmessage multi-dispatch andmes-

sage multi-forwardingwhich are the heart of code extensi-

bility and reusability. With COS features in hand, software should become as \ufb02exible and extensible as with scripting languages and as ef\ufb01cient and portable as expected with C programming. Likewise, COS concepts should signi\ufb01cantly simplifyadaptive andaspect-oriented programming as well asdistributed andservice-oriented computing.

Categories and Subject DescriptorsD.3.3 [C Program-
ming Language]: Language Constructs and Features; D.1.5
[Programming Techniques]: Object-oriented Programming.
General TermsObject-oriented programming.
KeywordsAdaptive object model, Aspects, Class cluster,

Closure, Contract, Delegation, Design pattern, Exception, Generic function, Introspection, High-order message, Mes- sage forwarding, Meta class, Meta-object protocol, Multi- method, Open class model, Predicate dispatch, Program- ming language design, Properties, Uniform object model.

\u2217COS project:http://sourceforge.net/projects/cos
[Copyright notice will appear here once \u2019preprint\u2019 option is removed.]
1. Motivation

The C Object System (COS) is a small framework which adds anobject-oriented layer to the C programming lan- guage [1, 2, 3] using itsprogrammable capabilities1 while following the simplicity of OBJECTIVE-C [5, 6] and the extensibility of CLOS [8, 9, 10]. COS aims to ful\ufb01ll sev- eral general principles rarely met in a single programming language:simplicity, extensibility, reusability, ef\ufb01ciency and

portability.
1.1 Context

COS has been developed in the hope to solve fundamen- tal programming problems encountered in scienti\ufb01c comput- ing and more speci\ufb01cally inapplied metrology [11, 12]. Al- though this domain looks simple at \ufb01rst glance, it involves nonetheless numerous \ufb01elds of computer science; fromlow-

leveltasks like the development of drivers, protocols or state

machines, the control of hardware, the acquisition of data, the synchronization of concurrent processes, or the numer- ical analysis and modeling of huge data sets; tohigh-level tasks like the interaction with databases or web servers, the management of remote or distributed resources, the visual- ization of complex data sets or the interpretation of scripts to make the system con\ufb01gurable and controllable by non- programmers [13, 14, 15]. Not to mention that scienti\ufb01c projects commonly have to rely on sparse human resources to develop and maintain for the long term suchcontinually-

evolving-systems(i.e.R&D). Therefore the challenge is am-

bitious but I \ufb01rmly believe that COS provides the required features to simplify the development and the support of such systems as well as a wide variety of software projects.

1.2 Principles

Given the context, it is essential to reduce the multiplicity of the technologies involved, to simplify the development pro- cess, to enhance the productivity, to guarantee the extensibil- ity and the portability of the code and to adapt the required skills to the available resources. Hence, thequalities of the programming language are essential for the success of such projects and should focus on the following principles:

1In the sense of \u201cLisp is a programmable programming language\u201d, [4].
Draft research paper for OOPSLA\u201909
1
2009/5/20
SimplicityThe language should be easy to learn and use.

The training curve for anaverage programmer should be as short as possible what implies in particular a clear and con- cise syntax. Simplicity should become an asset which guar- antees the quality of the code and allows to write complex constructions without being penalized by a complex formal- ism or by the multiplicity of the paradigms. COS can be learned within a few days by C programmers with some knowledge of object-oriented concepts, although exploiting the full power of COS requires some experience.

ExtensibilityThe language should support the addition of

new features or the improvement of existing features with- out changing signi\ufb01cantly the code or the software archi- tecture. Concepts likepolymorphism, message dispatch and

open class modelhelp to achieve good \ufb02exibilityand exten-
sibilityby reducing coupling. But they usually have a strong
impact on theef\ufb01ciency. COS dispatches messages with an
ef\ufb01ciency in the range of the C++ virtual member functions.
ReusabilityThe language should support code reusability,

namely the ability to reuse or quickly adapt existing compo- nents to unforeseen tasks. It is easier to achieve this goal if the language allows to writegeneric code, either by param- eterization, either by abstraction, to ease the componentiza- tion of design patterns [16, 17, 18]. To support the develop- ment ofgeneric components, COS provides multi-methods to handle dynamic and polymorphiccollaboration and dele- gation to handle dynamic and polymorphiccomposition.

Ef\ufb01ciencyA general purpose programming language must

be ef\ufb01cient, that is it must be able to translate all kinds of al- gorithms into programs running withpredictable resource usage (mainly CPU and memory) consistent with the pro- cesses carried out. In this respect, programming languages with an abstract machine close to the physical machine \u2014 alow-level language \u2014 offer generally better results. C is admittedly known to achieve good ef\ufb01ciency.

PortabilityA general purpose programming language must

be portable, that is it must be widely available on many ar- chitectures and it must be accessible from almost any other languages (FFI). This point often neglected brings many ad- vantages: it improves the software reliability, it reduces the deployment cost, it enlarges the \ufb01eld of potential users and it helps to \ufb01nd trained programmers. Regarding this point,

normalizedprogramming languages (ISO) get the advantage.
ISO C89 is normalized and well known for its availability
and portability.
1.3 Proposition

COS extends the C programming language with concepts [19] mostly borrowed from OBJECTIVE-C and CLOS. The choice of designing the language as a C library instead of a compiler allowed to quickly explore various object models, but R.E. Johnson\u2019s paper on the dynamic object model [20] de\ufb01nitely focused my research towards the \ufb01nal design:

\u201cIf a system is continually changing, or if you want users to be able to extend it, then the Dynamic Object Model ar- chitecture is often useful. [...] Systems based on Dynamic Object Models can be much smaller than alternatives. [...] I am working on replacing a system with several millions lines of code with a system based on a dynamic object model that I predict will require about 20,000 lines of code. [...] This makes these systems easier to change by experts, and (in theory) should make them easier to understand and main- tain. But a Dynamic Object Model is hard to build. [...] A system based on a Dynamic Object Model is an interpreter, and can be slow.\u201d.

This adaptive object model [21, 22] is actually what COS provides, but at the level of the C programming languages without signi\ufb01cant ef\ufb01ciency loss. In particular, COS has been designed to support ef\ufb01ciently two key concepts \u2014

multi-methodsand fast generic delegation\u2014 and provides

auniform object model where classes, generics and meth- ods are\ufb01rst-class objects. Incidentally, COS strengthens in- herently all the guidelines stated in [23] to build \u201c\ufb02exible,

usable and reusable object-oriented frameworks\u201d as well
as architectural pattern proposed in [24] to design\ufb02exible
component-based frameworks.
2. Overview
COS is a small framework entirely written in portable2
C99 which provides programming paradigms likeobjects,
classes, metaclasses, generic functions, multi-methods, del-
egation, properties, exceptions, contractsand closures. COS

syntax and features are directly available at the C source code level through the use of the language keywords de\ufb01ned in the header \ufb01le<cos/Object.h>.

2.1 Concepts
PolymorphismThis concept available inobject-oriented

programming languages is the heart of software extensibil- ity because it postpones to runtime the resolution of methods invocation and reduces coupling between callers and callees. Besides, if the polymorphic types are dynamic, the coupling becomes almost inexistent and code size and complexity are signi\ufb01cantly reduced. On one hand, these simpli\ufb01cations usuallyimprove the programmer understanding who makes less conceptual errors, draws simpler designs and increases its productivity. On the other hand, dynamic typing post- pones the detection of unknown messages at runtime, with the risk to see programs ending prematurely. But well tested software reduce this risk to exceptional situations.

CollaborationSoftware development is mainly about build-

ing collaborations between entities, namely objects. As soon as polymorphic objects are involved everywhere to ensure good software extensibility and reusability, one needspoly-

morphic collaborationimplemented by multi-methods. They
2Namely C89 and C99 variadic macros.
Draft research paper for OOPSLA\u201909
2
2009/5/20

reduce strong coupling that exist in the Visitor pattern (or equivalent) as well as the amount of code needed to achieve the task. COS provides message multi-dispatch with an ef\ufb01- ciency in the range of the C++ virtual member function.

CompositionThe composition of objects and behaviors is

a well known key-concept in software design. It enhances software \ufb02exibility by introducing levels of indirection in objects and behaviors. Most structural and behavioral design patterns described in [28] introduce such indirections, but at the price of an increased code complexity and coupling and hence a decreased reusability of the components built. The

delegationis an effective mechanism which allows to man-

age the composition of both, objects and behaviors, without introducing coupling. COS provides delegation with the ef- \ufb01ciency of message dispatch,seemingly a unique feature.

Re\ufb02ectionRe\ufb02ection is a powerful aspect of adaptive ob-

ject models which, amongst others, allows to mimic the be- havior of interpreters. COS provides full introspection and limited intercession on polymorphic types and behaviors, that is classes, generics and methods, as well as object at- tributes through the de\ufb01nition of properties. Since all COS components are\ufb01rst-class objects, it is trivial to replace cre- ational patterns [28] by generic functions (section 8.1).

EncapsulationEncapsulation is a major concern when de-

veloping libraries and large-scale software. COS enforces encapsulation of class implementation because encapsula- tion is not only a matter of managing coupling but also a design issue. Besides, the object behaviors are represented by generics which favors theseparation of concerns of inter- faces and reduces cross-interfaces dependencies [23]. More- over, the open class model of COS allows to extend classes

on needwithout breaking the encapsulation (i.e.without \u201cre-
opening the box\u201d) and reduces the risk of premature design.
OwnershipThe management of object life cycles requires

a clear policy of ownership and scope rules. In languages like C and C++ where semanticby value prevails, the burden is put on the programmer\u2019s shoulders. In languages like JAVA, C# and D where semanticby reference prevails, the burden is put on the garbage collector. In this domain, COS lets the developer choose between garbage collection (e.g. Boehm GC [25]) andmanual reference counting with rich semantic (section 3.5).

ConcurrencyCOS has been designed from the beginning
with concurrency in mind and shares only its dictionary of
static components. Per thread resources like message caches
andautorelease pools rely on either thread-local-storage or
thread-speci\ufb01c-key according to the availability.
2.2 Components
The object-oriented layer of COS is based on three compo-
nents (\ufb01gure 1) borrowed from CLOS which characterize the
open object modeldescribed in depth in [8] and [9].
Function/Behavior/Verb
defgeneric
function declaration
(interface)
Type/State/Noun
defclass
structure de\ufb01nition
(de\ufb01nition)
Specialization
defmethod
function de\ufb01nition
(implementation)
1
1..5
Figure 1.Roles of COS components and their equivalent C-
forms.Multi-methods are classes specialization of generics.
ClassesClasses play the same role asstructures in C and
de\ufb01ne objectattributes. They are bound to theirsuperclass
andmetaclasses and de\ufb01ne supertypes-subtypes hierarchies.
GenericsGenerics play the same role asfunction declara-
tionsin C and de\ufb01ne messages. They are essential actors of
code extensibility and ensure correctness of formal parame-
ters of messages between callers and callees.
MethodsMethods play the same role asfunction de\ufb01ni-
tionsin C and de\ufb01ne specializationsof generics. A method
is invoked if the message belongs to its generic and the re-
ceivers match its classes (multi-methods).

The similarities between COS components and their equiv- alent C-forms let C programmers with some notions of object-oriented design be productive rapidly. The open ob- ject model allows to de\ufb01ne components in different places and therefore requires an extra linking iteration to collect theirexternal symbols: link\u2192 collect3\u2192 re-link. This fast iteration is automatically performed by the make\ufb01les com- ing with COS before the \ufb01nal compilation stage that builds the executable or the dynamic library.

2.3 Syntax

COS introduces new keywords to extend the C language with a user-friendly syntax half-way between OBJECTIVE-C and CLOS. COSparses its syntax and generates code with the

help of its functional C preprocessing library4; a module of

a few hundred C macros which was developed for this pur- pose. It offers limited parsing capabilities, token recognition, token manipulation and algorithms likeeval, map, \ufb01lter, fold,

scan, splitborrowed from functional languages and working

on tuples of tokens. As a rule of thumb, all COS symbols and macros are mangled to avoid unexpected collisions with other libraries, including keywords which can be disabled.

Despite of its dynamic nature, COS tries hard to detect
all syntax errors, type errors and other mistakes at compile-
3COS mangled symbols are collected with thenm command or equivalent.
4The description of thiscpp library is beyond the scope of this paper.
Draft research paper for OOPSLA\u201909
3
2009/5/20

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->