Posts tagged: C++

The Apple Voodoo

I love the iPhone. As usual when it comes to Apple gadgets, the feeling for design and thinking outside the box produced a phone that finally made me see the point of a smart phone.

The one thing that’s always bothered me though is the App Store and conditions. A central directory of apps and central point of download is a good idea. A standardized update procedure is an even better idea, at once solving all the bullshit problems windows users have to put up with (how interested are you in updating Adobe Reader or Java all the time, really?)

The one thing I don’t agree with is the approval process. And Apple just went from tolerably bad to intolerably worse on that one. I think it’s a bad decision to restrict what you may run on the phone and how, but it’s still a decision I can respect — their rules on how you execute stuff within the context of their operating system.

However, the new terms of service for iPhone OS 4 says this:

Applications must be originally written in Objective-C, C, C++, or JavaScript as executed by the iPhone OS WebKit engine, and only code written in C, C++, and Objective-C may compile and directly link against the Documented APIs

Here’s where Apple has clearly and definitely stepped over the line. Not only must the resulting application conform to certain demands, now my development process must conform to certain demands?

Code generation is an incredibly useful technique, and they’re banning it simply to stop the Flash compiler and make a grand statement? Either way, how in the world are they planning to enforce this? Will this lead to an arms race between Apple trying to detect application code that has been compiled to C, C++ or Objective-C and a company like Adobe making a compiler that compiles Flash to those languages in a way that looks as close to human-written as possible? Unless I have to submit a full-length video of myself coding the entire thing, there is just no way to tell with a reasonable accuracy.

How much collateral damage is acceptable, Apple? How many other companies and customers will suffer over your crusade against Flash? How many developers will hate your guts before this is over? There are just so many pins the developer voodoo doll will take.

The iPhone app craze will eventually die as more people realize the gold rush is over. And at that point, Apple can keep its Objective-C Nazi corner, while the rest of us go back to using the best tools for the task at hand.

Design Fundamentals: Abstraction

Design Fundamentals is my series on code design aimed at people who may have done some code in school, but haven’t done much code design, or who haven’t read much about design before.  This is the second article of the series.

Code design is all about making sense of a system. Any software worth mentioning quickly grows larger than your brain can easily track. A good design will ensure that each piece of the program can be safely worked on in isolation — that whatever you need to do, it’ll fit within your working memory.

Abstraction is a key component to keeping the amount of details you need to remember at once at a minimum. By abstracting a piece of code, you remove the details and only have to think about the abstract interface to the code, which should be smaller (or the abstraction was a bad idea).

So exactly how does abstraction work? I’m sure you’ve done some version of it before, maybe even without being aware of it. At a low level of abstraction, the code is filled with all the details. At a high level of abstraction, code uses concepts that hide details. So in abstracting code, we lift out the details to some other place — maybe a class or a function.

When to abstract

While you can debate any kind of rules for when to abstract (just like most things in code), I’ll attempt to give you some guidelines. Adapt them as they suit you and change them if they don’t make sense in your context.

For functions, what you can keep in your head is strongly related to what you can see on your screen. As soon as a function has you scrolling up and down, you’ve got a good sign that the function is too long and that you should abstract something away. For me, the maximum length of a function that is normally reasonable is about 50 lines — the exact number will vary with personal preference and the content of the function.

For both functions and classes, the relationship with other classes or functions also matters — specifically the fan-out (amount of other classes your class uses, for instance). You want to keep the fan-out low, since otherwise you risk forgetting the details of something while working on the code (or confusing the next coder who works with it). Steve McConnell has this to say about it in Code Complete (a recommended book if you’re interested in code and design):

Low-to-medium fan-out Low-to-medium fan-out means having a given class use a low-to-medium number of other classes. High fan-out (more than about seven) indicates that a class uses a large number of other classes and may therefore be overly complex. Researchers have found that the principle of low fan-out  us beneficial whether you’re considering the number of routines called from within a routine or from within a class.

The same thing applies with the number seven as with the above line count — use your judgement, but keep in mind when the fan-out is starting to increase that you might want to look at your design again.

Common abstraction mistakes

The number one mistake people do when it comes to abstraction is to confuse the need to abstract with the interface of classes that is exposed to others. Often, when abstracting a part of a function to a new function, it doesn’t need to go into the interface of the class you’re working with at all — it can simply be placed in an anonymous namespace at the top of the file you’re working on.

Another mistake that is fairly common is to treat abstraction as a simple cut and paste activity, where a number of lines of code are simply moved to another place. Stop to consider where to make the cut — what part of the code you’re working on is a logical unit that does something reasonable? If you end  up with a function named partOfMyOtherFunction() or something similar, you haven’t really achieved anything.

Keep thinking about your abstracted functions — do they share characteristics? Often you might find yourself creating helper functions that would fit better grouped together in a helper class. This class can also reside in the same file — there’s nothing which forces you to create a new header file and source file in order to abstract code.

Building abstract code

If possible, build your code in abstract layers from the start. Consider what parts you might need when implementing your functionality, and make sure implementation details are well partitioned off. Especially things like system differences and interfaces towards the operating system is good targets for an abstraction layer.

Encapsulate the system functionality in order to not have to bother with details everywhere in the code. This is especially useful when interfacing with badly designed APIs, to ensure that this doesn’t spread to all of your code. This lets the rest of your code think about the system functionality at a higher level, without the details.

Design Fundamentals: Encapsulation

EncapsulationEncapsulation is one of the core design patterns of Object Oriented programming. The point of encapsulation is to split a large program into a number of smaller, independent parts to reduce complexity. In a sentence, encapsulation is hiding the implementation details of a module from its user.

The point of doing this is that it’s easier to use a module with a well defined interface and it’s easier to change the implementation if fewer things depend on it. If you expose the implementation of a module to its user, you can bet the user is going to end up in some way or other dependent on the implementation details. This means that the risk of breaking something increases every time you make a change to the module.

Why does this not become an apparent problem for a new programmer? There are two major contributing factors. One is that new programmers tend to write small to medium sized programs, and that dependency-based problems tend to become apparent only in large applications. In a small application, you’ll have a few users of your module, and when you break the implementation dependency, maybe one of them breaks. You fix the error and move on. Simply put: You don’t need design skills to write “Hello, World!” applications.

Experienced Software Engineers tend to write large to massive program systems. If you have a lot of things dependent on the implementation details you’re changing, chances are a lot of things will break, and maybe some of the errors won’t be apparent until much later. Even better, if all your components are dependent of implementation details of others, every change you make is virtually guaranteed to break something.

The second reason initiate coders fail to notice the need for encapsulation is that the errors that spring from this are delayed. There’s nothing immediately wrong with your code — it works. That’s why this is a question of design, not of code.

So how do you properly encapsulate code? Start by looking at your interface for the class. How does one interact with it? Consider what it means — does the interface tell you what it’s doing, or how it’s doing it? If you find it’s telling you anything at all about how it does things, consider what you could do to hide it.

Another useful way to think about a class interface in terms of encapsulation is “how could I break this object’s functionality“? If you find you could break it, something’s wrong with your encapsulation. A properly encapsulated object guarantees the consistency of its own state at all times. This way of thinking about a module leads to robust interfaces and code.

A good starting point for encapsulation is to make all your internal data private, and to expose only retrieval methods for those things the outside world has any business knowing about (languages with Properties like C# avoid this, but without them you’re better off doing this). Remember, one point of encapsulation is that you should be able to change the implementation without changing the interface, and if your internal variable are public, you can’t change how you store data.

There’s a tendency to expose other complex objects that your class owns by direct accessor functions as well. This is usually a mistake. In essence, you’re giving up control over these objects, which means you can no longer guarantee your internal state is consistent and you can’t switch to a different kind of object.

Consider an example of a logging facility that has an output stream. There might be a temptation to do something like this:

log.getOutStream() << "Testing, testing";

This is where you break encapsulation, becaue suddenly you have no idea what’s being done to the log stream. Maybe someone saved a reference to it somewhere? Is it safe to delete it? Did someone start a row and leave it unfinished (like I did above)? Dunno.

Also, you’re now stuck unable to change to logging over a network, onto a printer, into a GUI or whatever else could be useful to do (unless you want to derive your own iostream, which I wouldn’t recommend).

An option is to encapsulate the logging service fully, and only provide an interface to do things with (log text):

log.addTextRow("Testing, testing");

This way, whatever you do in addTextRow() is your own business, as long as logs get made.

As with most design issues, getting the design right when it comes to encapsulation is hard the first time around. You’ll almost never get it right the first time around. That doesn’t mean you shouldn’t try your best though — the reason you get it right the second time is that you notice what happened the first time you tried.

Many new coders tend to mix up project process with design process. Hearing about waterfall (and it’s negative sides), they say “I’m not doing waterfall”, which to them means not to do any design up front. This is a big mistake — think about your design all the time. When you sit down to write a new class, you should have a design idea in mind — trying to nail on design onto a kludge of code is a lot harder than to rework a bad design into a good one.

What does this have to do with encapsulation? It means you should make your variables private from the start, and immediately start thinking about your interface. That way, you’re not going to have to realize halfway through that you’ve missed encapsulating things. Nearly always, the key to getting the design right is to start thinking about the design.

When I recently sat down to implement a new feature of a side project I’m working on, the first thing I did was create 10 empty files, because I’d already thought the design through enough to know I’d need those classes. That doesn’t mean you should do all your design up front, and never touch it again (waterfall-style), it just means there’s nothing wrong with thinking about design before you start coding. In fact, I very much encourage it.

Design Fundamentals

I’ve been working on a new side project with a friend of mine. I’m thrilled to have found something that’s both an interesting challenge and something good to have on the side. It’s already teaching me new things that I would probably never have the opportunity to explore at work, for various reasons.

One of these things I’ve learned is that there are many things that I use in my coding are things that I take for granted but that are not natural or obvious to initiate coders. My friend is a coder who’s got some experience of coding through College, but I’ve realized that going from initiate coder to Software Engineer takes a lot of experience and that there are many things I’ve picked up along the way.

I got my share of that experience by creating a game engine in a startup, and doing a lot of other mildly complicated things. I had the fortunate position of having a colleague with whom I could discuss all design decisions to the bitter end, and the time to make a fair few mistakes and figure out how to turn them into successes.

What your path to getting that experience is, I can’t tell. Only you can walk that path, but at least I can set up some signs along the way to help. I’ll be starting a new series of posts called Design Fundamentals, where I’ll explore design concept that are fundamental to wrap your head around. Hopefully even experienced coders can gain something from these posts.

The posts will try to gather in one place only what a given design technique or pattern means, but also how to use it, why it’s useful and various tips and trips.

I’ll be using C++ as the language for these posts, as it’s my language of choice. Much of the information may benefit you if you’re coding in another language, and in fact the only recommendations I have for you when it comes to languages is pick one, and make it your native one. Become an expert in one language, don’t try to go wide. There’s a good point in learning to code in a few languages — but don’t make it your focus to become as good in all of them.

This post will serve as an index — all future posts in the series will be linked from here.

But Bad Programmers Will Abuse It!

I recently had an interesting argument with some collegues about the merits of properties as a language-supported construct. If you haven’t heard of the property (or “smart field”) concept before, here’s a quick intro:

A property is a class field that acts like a variable, but encapsulate get and set methods. This means that from the outside, you can do something like:

a.field = 10;

but what actually happens is that the method “field set()” runs:

public int field {
    set {
        m_field = value;

If you want a more exhaustive look at properties there’s a good explanation of C# properties at C# Station.

Ever since my days long ago coding Visual Basic (ugh), I’ve been a fan of the property concept. In my view, it provides language support for something we do anyway — providing accessor methods for private data fields, doing away with something that breaks the natural expectation of how to do things… normally I assign a value using the assignment operator, now I have to call a set function.

Worse, without properties you’re in a situation where you have to either provide set and get methods for all fields for consistency, or start out with public data fields and be ready to change all calling code if you need to do some additional checking on the value being set. Nearly everyone goes with option 1, so we end up doing the tedious extra work of typing out default get and set methods, or using refactoring tools to write them for us. Either way, the code gets cluttered with stuff we didn’t really have a specific use for.

So coming back to the discussion we had about properties, what are the reasons that people don’t like them? The argument can basically be summed up as this: “But people can put all kinds of stuff in that method. If I assign a variable, I assume it’s only going to save a value, not do something heavyweight.”

So essentially, bad programmers will abuse the feature, thus it’s bad. Well… we already do this, it’s just not built into the language. Someone can calculate the next unknown digit of π or brute force a solution to a 1024-bit RSA key in your setField() method just as they can in the field set() method. In both cases, you’re going to expect a simple value assignment, possibly with some safety checks.

The bottom line is, no language is going to protect you from the abuse done by unskilled programmers. Funnily, the argument tends to come from coders who work primarily in C++, which must be the best language possible if you’re looking to set traps for yourself. You can do really horrible things to your fellow C++ coders using operator overloading, but that doesn’t make operator overloading a bad feature.

WordPress Themes