Home > Articles > Programming

What Language I Use for… Creating Reusable Libraries: Objective-C

David Chisnall tells you why his language of choice for creating reusable libraries is Objective-C.
Like this article? We recommend

Like this article? We recommend

When most people think of Objective-C, they think of it as "that language that you use for programming iPhones (or possibly Macs)." I write a lot of Objective-C code, but I run very little of it on an Apple platform.

The original version of Objective-C didn't have a standard library of its own. It was intended for packaging up C libraries into late-bound modules that could be reused, so its standard library was the C standard library. The idea was that you'd use C for the core of the implementation, and then use Objective-C on the edges of the library to expose functionality and for combining library code into an application.

This is increasingly important. Most applications today are more than 90% shared library code. In a sense, this is a very positive reflection on our industry because it means that code reuse is no longer just a good idea but a fact of deployment. It does, however, mean that if you want to stay competitive, you need to think about all the code you write in terms of how it can be reused in the future.

Today, Objective-C does have something akin to a standard library: the Foundation framework (sometimes called the Foundation Kit). This library was standardized in 1992 by Sun and NeXT in the OpenStep specification, and is implemented by Apple on OS X and iOS - and by GNUstep everywhere else. There are also some cut-down implementations of Foundation for systems with smaller resource footprints.

This library includes all the standard features that you'd expect from a modern language: basic data types such as strings; collections (arrays, dictionaries, sets and so on); ways of interacting with the system (file handles, sockets); an event-driven runloop model; and so on.


Don't Miss These Related Articles Also by David Chisnall

Learn more about David Chisnall


Interface vs. Implementation

When you're creating a library, the most important consideration (sadly missed by most LLVM developers and, indeed, many open source projects) is that users of your library don't want to have to rewrite their code to be able to use a new version.

In fact, most users don't want to have to recompile their code, either. This even applies to open source software being shipped as binary packages, where it's trivial for the packaging system to recompile everything. As an end user, I don't want to have to download new versions of every package that depends on a particular library just because a new version of the library has been released.

The key to this is ensuring that the library's interface is stable and does not depend on any implementation details that are likely to change over time. C++, for example, is particularly bad at this. Consider the following trivial C++ class interface:

class point
{
        int x, y;
        virtual int getDistanceFromOrigin();
};

If you add or remove any of the fields, you've changed the class' binary interface so that any subclass or anything that allocates an instance of the class on the stack will need to be recompiled. Worse, if you add any (virtual) methods to the class, you've changed the vtable layout, which is part of the class' binary interface and so will force anything that might contain subclasses of this to be recompiled.

There are a few ways around this in C++. You can have a pure-virtual superclass. This superclass works around the problem of allocating the object on the stack (because it's no longer possible), but it still means that adding a new method will change the ABI. You can avoid that with the pImpl (pointer to implementation) pattern, which uses non-virtual functions for the public interface and has each of those call the corresponding (possibly virtual) function in the implementation object. The public class then just has a single field, which is a pointer to the real implementation.

By this point, you've almost got Objective-C semantics, but you've had to fight the language every step of the way. In contrast, this class in Objective-C would have its implementation and interface written like this:

@interface Point : NSObject
- (int)distanceFromOrigin;
@end

@implementation Point
{
        int x;
        int y;
}
- (int)distanceFromOrigin
{
        return sqrt(x*x+y*y);
}
@end

If you decide to change the class to use double-precision floating-point polar coordinates internally, the interface remains the same. If you want to add some methods (or even reorder the existing ones to make the header more readable), this has no effect on the binary interface.

Late Binding

A related idea to the separation of interface and implementation is that of late binding. The point example applies even if someone subclasses the Point class. The two instance variables are not part of the interface, so they can't be accessed by subclasses unless they go via the introspection mechanisms. Objective-C objects can't be allocated on the stack, and the offsets of instance variables are defined by the runtime library at load time, so you can make a superclass larger or smaller without breaking any of its subclasses.

In Objective-C, when you call a method, it is looked up based on its name (and in the GNUstep implementation, the types of its arguments, which avoids some stack-corruption issues in Apple's version of the language), independently of the class hierarchy. You can override any method in a class or even replace one with a proxy or something with an entirely different implementation.

This makes it very easy to refactor code in significant ways without impacting users of a library. With a small amount of care, you can produce adaptors that implement old interfaces, even when these no longer have any relationship to how the implementation really works.

This also means that the coupling between classes in Objective-C tends to be very loose. It's the only language I've ever used where it is common to write a class for one application and then pull it, unmodified, into another where it interacts with a very different set of classes.

Interfaces to Other Languages

The point of writing a shared library is for people to use it. This means that they must be able to call into your library. There are Objective-C bridges from a number of scripting languages; for example, in Python you can take an Objective-C object, subclass it, and use it as if it were a Python object. The LanguageKit framework that I've written also allows me to compile domain-specific languages and even dialects of Smalltalk and JavaScript to share an object model with Objective-C. The Java Interface to GNUstep (JIGS) allows you to expose Objective-C objects to a JVM.

Perhaps more importantly, however, it's trivial to integrate Objective-C with C and C++. You can automatically generate C wrappers for Objective-C classes, if you need to be callable directly from C and C is the lingua franca of modern languages. It's hard to find a programming language that doesn't have some way of calling C code.

This is actually how the GNUstep implementation of some parts of CoreFoundation works: a set of wrapper functions that were automatically generated to invoke Objective-C methods. Doing this is similar to using the pImpl pattern in C++, but it has the advantage that you need to do it only for languages that don't have a native bridge.

Static Compilation

One of the other advantages of Objective-C over other late-bound object oriented languages is its compilation model. Objective-C code is ahead-of-time compiled and requires only a lightweight runtime library to work.

This is not just an advantage for writing shared libraries; it also makes deploying applications that use them easier. Dependencies on large scripting language systems or virtual machines are often a serious barrier. Especially if you need to depend on a specific version - I've had to use machines with five different versions of Python installed because of different packages requiring different versions, and this quickly becomes an administrative nightmare.

This isn't always an advantage. For example, quite a lot of companies use GNUstep to port iOS applications to Android and, because it requires the use of the NDK, end up with an application that doesn't run on MIPS, restricting them to only 99.9% of the Android market. That's not really a problem today, but it might become one if MIPS (or even x86) smartphones become common. Of course, supporting these platforms is typically just a recompile away...

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020