Tuesday, 19 July 2011

C++: Declaring a pointer to a template method

Busy writing some template gibberish, we needed to make a healthy trade in pointers to template-member-functions. Of template classes. (Where the template function parameters themselves were pointers to template methods on template classes, but let's not worry about that detail right now).

It took a little run-up to get the C++ syntax right, so I present it here for your viewing pleasure.

All code tested against g++ 4.2.1 only.

Case 1: Normal pointer to member

Let's just remind ourselves of the syntax for a simple pointer to (normal, non-template) member function:

Note: I've gratuitously changed the < < stream operators into "--" just to get the syntax through blogger's composer window. Sorry about that. I pray that no other C++ syntax was sacrificed in this publishing exercise
class Target1
{
public:
void Method(int a)
{
std::cout -- "Target1(" -- a -- ")\n";
}
};

void PointerToNormalMemberFunction()
{
Target1 target;
// This is how we construct a normal pointer to member function
void (Target1::*oneParam)(int) = &Target1::Method;
(target.*oneParam)(1);
}
Relatively simple.

Case 2: A pointer to template member function

Here's the first incursion of templates. If you're looking at a template method, this is how you'd declare your pointers to it:
class Target2
{
public:
template <typename T>
void Method(T a)
{
std::cout -- "Target2("--a--")\n";
}
};

void PointerToTemplateMemberFunction()
{
Target2 target;

// This is how we construct a pointer to a template member function
// See how the template type of the method is mentioned at the end of the method name.
void (Target2::*oneParamTemplateInt)(int) = &Target2::Method<int>;
void (Target2::*oneParamTemplateFloat)(float) = &Target2::Method<float>;
(target.*oneParamTemplateInt)(2);
(target.*oneParamTemplateFloat)(2.5);

// However, the compiler can deduce the template type of the method
void (Target2::*shorterInt)(int) = &Target2::Method;
void (Target2::*shorterFloat)(float) = &Target2::Method;
(target.*shorterInt)(3);
(target.*shorterFloat)(3.5);
}
Note that you can chose whether or not to specify the template types of the method when you assign it to your member-function pointer. The compiler can deduce these for you.

Case 3: Pointer to template methods with more than one template parameter

This is not significantly different from the above, we just extend the types in the pointer-to-member.

class Target3
{
public:
template <typenameT>
void Method(T1 a, T2 b)
{
std::cout -- "Target3("--a--","--b--")\n";
}
};

void PointerToTemplateMemberFunctionWithTwoParameters()
{
Target3 target;

// This is how we construct a pointer to a template member function
// with multiple template parameters. Just like above, really.
void (Target3::*oneParamTemplateIntFloat)(int,float) = &Target3::Method<int,float>;
void (Target3::*oneParamTemplateFloatInt)(float,int) = &Target3::Method<float,int>;
(target.*oneParamTemplateIntFloat)(4,4.5);
(target.*oneParamTemplateFloatInt)(4.5,4);

// Again, the compiler can deduce the type of the methods
void (Target3::*shorterIntFloat)(int,float) = &Target3::Method;
void (Target3::*shorterFloatInt)(float,int) = &Target3::Method;
(target.*shorterIntFloat)(5,5.5);
(target.*shorterFloatInt)(5.5,5);
}
Again, note, the compiler can generally deduce the correct template method without you having to specify the template parameter types.

Case 4: Pointer to template methods in a template class.

Now it's getting sillier - a pointer to a template method in a template class. the syntax does still make sense, it just depends how far down the rabbit hole you want to go.

template<typename TYPE>
class Target4
{
public:
Target4(const TYPE &value) : value(value) {}
TYPE value;

template <typename T>
void OneParam(T a)
{
std::cout -- "Target4::OneParam("--value--","--a--")\n";
}

template <typename T1, typename T2>
void TwoParam(T1 a, T2 b)
{
std::cout -- "Target4::TwoParam("--value--","--a--","--b--")\n";
}
};

void PointerToTemplateMemberInTemplateClass()
{
Target4<char> target('c');

void (Target4<char>::*oneParam)(float) = &Target4<char>::OneParam<float>;
(target.*oneParam)(6.5);

// Again, we can miss off the last template types
void (Target4<char>::*shorter)(float) = &Target4<char>::OneParam;
(target.*shorter)(6.75);

// Two parameters just extends the scheme
void (Target4<char>::*twoParam)(float,int) = &Target4<char>::TwoParam;
(target.*twoParam)(6.8,6);
}

Case 5: Using a pointer to a template method of a template class inside the template class itself

If you want to make use of a pointer to template method within a template class, you simply cannot specify the template method's parameter types. The compiler considers this a syntax error. So you have to rely on the compiler deducing the correct template method instantiation. (See edit below.)

In the case of this example, it copes fine. In more complex cases, it may hurt less if your call template method overloads different names.

template<typename TYPE>
class Target5
{
public:
Target5(const TYPE &value) : value(value) {}
TYPE value;

template <typename T>
void OneParam(T a)
{
std::cout -- "Target5::OneParam("--value--","--a--")\n";

typedef void (Target5<E>::*MethodTypeToCall)(T);
// Here, the compiler picks the right overload
MethodTypeToCall toCall = &Target5<E>::Private;
// In this case, the compiler does not let us write the following line (parse error):
//MethodTypeToCall toCall = &Target5<E>::Private<t;;
(this->*toCall)(a);
}

template <typename T1, typename T2>
void TwoParam(T1 a, T2 b)
{
std::cout -- "Target5::TwoParam("--value--","--a--","--b--")\n";

typedef void (Target5<E>::*MethodTypeToCall)(T1,T2);
MethodTypeToCall toCall = &Target5<E>::Private; // compiler picks the right overload
// you can't add the method's template parameters to the end of that line
(this->*toCall)(a,b);
}

private:

template <typename T>
void Private(T a)
{ std::cout -- "Target5::Private("--value--","--a--")\n"; }
template <typename T1, typename T2>
void Private(T1 a, T2 b)
{ std::cout -- "Target5::Private("--value--","--a--","--b--")\n"; }
};

void HoldingAPointerToTemplateMemberInTemplateClass()
{
Target5<r> target('c');

void (Target5<r>::*oneParam)(int) = &Target5<r>::OneParam;
(target.*oneParam)(7);
void (Target5<r>::*twoParam)(float,int) = &Target5<r>::TwoParam;
(target.*twoParam)(7.5,7);
}
Edit: it's been pointed to to me that you can name a specific overloaded template method using the following syntax. Add this to your pipe and smoke the whole template shenanigans:

MethodTypeToCall toCall2 = &Target5::template Private<T>;

This kind of template gibberish is why you know you love C++.

Simples, init?

The extra thing we added to all this syntactical joy was to have one of the template method's (template) parameter types itself a pointer to a template method on a template class.

It was at this point our brains dribbled out of our ears, and we had to retrace our template syntax steps back up this rabbit hole.

Monday, 18 July 2011

Writing: It's The Thought That Accounts

The July issue of ACCU's C Vu magazine is out now. It contains the latest instalment in my Becoming a Better Programmer column. This one's called It's The Thought That Accounts.

In it I describe how you can become a better programmer, and how you will be encouraged to write better code, through accountability. Far from being a dirty word, or some kind of bureaucratic nightmare, developer accountability can be fun, stimulating, enriching, and valuable.

You'll also find out about my wine and running predilections.

This is a great issue of C Vu, with some really interesting articles. If you're a developer who is not already an ACCU member, then I strongly urge you to join. It's super-cheap and really worthwhile!

I'll hold you accountable to that...


Friday, 24 June 2011

Are we there yet? (Becoming a Better Programmer)

In the name of God, stop a moment, cease your work, look around you. Leo Tolstoy

A program is made of a number of subsystems. Each of those subsystems is composed of a smaller parts - components, modules, classes, functions, data types, and the like. Sometimes even boxes and lines. Or clever ideas.

The jobbing programmer moves from one assignment to the next; from one task to another. Their working day is composed of a series of construction and maintenance tasks on a series of these software components: composing new parts, stitching parts together, extending, enhancing or mending existing pieces of code.

So our job is simply a string of lots of smaller jobs. It's recursive. Programmers love that that kind of thing.

Are we there yet?

So there you are: getting the job done. (You think.)

Just like a small child travelling in the back of a car constantly brays “are we there yet?”, pretty soon you'll encounter the braying manager: “are you done yet?”

This is an important question. Its essential for a software developer to be able to answer that one simple request: to know what “done” looks like, and to have a realistic idea of how close you are to being “done”. And then to communicate it.

Many programmers fall short here; it's tempting to just keep hacking away until the task seems complete. They don't have a good grasp on whether they're nearly finished or not. They think: There could be any number of bugs to iron out, or unforeseen problems to trip me up. I can't possibly tell if I'm almost done.

But that's simply not good enough. Usually, avoiding the question is an excuse for lazy practice, a justification for “coding from the hip”, without forethought and planning. It's not methodical.

It's also likely to create problems for you. I often see people working far too hard:

  • They are doing more work than necessary, because they didn't know when to stop.

  • Without knowing when they'll be done, they don't actually complete the tasks they think are finished. This leads to having to pick things back up later on, to work out what's missing and how to stitch it in. Code construction is far slower and harder this way.

  • The wrong bits of code get polished, as the correct goal was never in sight. This is wasted work.

  • Developers working too hard are forced to put in extra hours. You'll not get enough sleep!

Let's see how to avoid this and to answer “are we there yet” effectively.

Developing backwards: decomposition

Different programming shops manage their day-to-day development efforts differently. Often this depends on the size and structure of the software team.

Some place a single developer in charge of a large swathe of functionality, give them a delivery date, and ask them for occasional progress reports. Others follow “agile” processes, and manage a backlog of more granular tasks (perhaps phrasing them as stories), divvying those out to programmers as they are able to move into a new task.

The first step towards defining “done” is to know exactly what you're working on. If it's a fiendishly large and complex problem, then it's going to be fiendishly complex to say when you'll be done.

It's a far simpler exercise to answer how far through you are through a small, well-understood problem. Obvious, really.

So if you have been allotted a monster task, before you begin chipping away at it, break it down into smaller, understandable parts. Too many people rush headlong into code or design without taking a step back to consider how they will work through it.

Split large tasks up into a series of smaller, well-understood tasks. You will be able to judge progress through these more accurately.

Often this isn't a complex a task, at least for a top-level decomposition. (You may have to drill down a few times. Do so. But take note: this is an indication that you've been handed a task at far too high a granularity.)

Sometimes such a decomposition is hard to do, and is a significant task itself. Don't let that put you off. If you don't do it up-front for estimation purposes, you'll only end up doing it later on in less focussed ways as you battle to the finish line.

Make sure that at any point in time, you know the smallest unit you're working on; rather than just the big target for your project.

Define done

You've got an idea of the big picture; you know what you're ultimately trying to build. And you know the particular sub-task you're working on at the moment.

Now, make sure that for whatever task you are working on, you know when to stop.

To do this, you have to define what “done” is. You have to know what “success” means. What the “complete” software will look like.

Make sure you define “done”.

This is important. If you haven't determined when to stop, you'll keep working far past when you needed to. You'll be working harder and longer than you needed to. Or, you won't work hard enough – you'll not get everything done. (Not getting everything done sounds easier, doesn't it? But it's not... the half-done work will come back to bite you, and will make more work for you later down the line, whether that's bugs, rework, or an unstable product).

Don't start a piece of coding work until you know what success is. If you don't yet know, make your first task determining what “done” is. Only then, get going. With the certainty of knowing where you're headed, you'll be able to work in a focused, directed manner. You'll be able to make informed choices, and to discount unnecessary things that might side-track or delay you.

If you can't tell when it's done, then you shouldn't start it.

So how does this look in practice? How do you define “done”? Your “done” criteria needs to be:

Clear

It must be unambiguous and specific. A list of all the features to be implemented, the APIs added or extended, or the specific faults to be fixed.

If, as you get into the task, you discover things that might affect the completion criteria (e.g. you discover more bugs that need fixing, or uncover unforeseen problems) then you must make sure that you reflect this in your “done” criteria.

This criteria is usually directly traceable to some software requirements or a user story – if you have them. If this is the case, make sure that this connection is documented.

Visible

Make sure that the success criteria is seen by all important parties. This probably includes: your manager, your customers, the downstream teams using your code, or the testers who will validate your work.

Make sure everyone knows and agrees on this criteria. And make sure they'll have a way of telling – and agreeing – when you are “done”.



The nature of each task will clearly define what “done” means. However you should consider:

  • How much code must be completed. (Do you measure this in units of functionality, APIs implemented, user stories completed?)

  • How much is design done, and how it's captured.

  • Whether any documents or reports must be generated.



When it's a coding task, you can mostly clearly demonstrate “being done” by creating an unambiguous test set. Write tests that will show when you've fashioned the full suite of code required.

Use tests written in code to define when your code is complete and working.

There are some other questions that you may have to consider when you describe what “done” is:

  • Where is the code delivered to? (e.g. to version control)

  • Where is the code deployed to? (Is it “done” when it's live on a server - or do you deliver testable product ready for a deployment team to roll out?)

  • What are the economics of “done”? The exact numbers required that may lead to certain tradeoffs or measurements. For example: how well should your solution scale? It's not good enough if your software only manages 10 simultaneous users if 10,000 are required. The more precise your done criteria the better you understand these economics.

  • How will you signal that you're done? When you think you're done how will you let the customer/manager/QA department know? This probably looks different for each person. How will you garner agreement that you are indeed done – who signs-off on your work? Do you just check in, do you change a project reporting ticket, or do you raise an invoice?

Just do it

When you've defined “done”, you can work with focus. Work up to the “done” point. Don't do more than necessary.

Stop when your code is good enough – not necessarily perfect (there may be a real difference between the two states). If the code gets used or worked on an awful lot, it may eventually be refactored to be perfect – but don't polish it yet. This may just be wasted effort. (Beware: this is not an excuse to write bad code, just a warning against unnecessary over-polishing).

Don't do more work than necessarily. Work until you're “done”. Then stop.

Having a single, specific goal in mind helps you to focus on a single task. Without this focus it's easy to hack at code randomly trying to achieve a number of things and not managing any of them successfully.

Questions

  1. Do you know when you're current task will be “done”? What does “done” look like?

  2. Have you decomposed your current task into a single goal, or a series of simple goals?

  3. Do you decompose your work into achievable, measurable units?

Thursday, 9 June 2011

The Enigma Continues

Version 1.4 of my cool iOS puzzle game, The Enigma Squares, has been released. Check it out here. In this version, I present you more than 80 new levels, with a number of fun, a number of fiendish, and a number of speed-trial puzzles.

Check it out on iTunes now.

I've also released a new game. The Enigma Kids is a family-oriented puzzler. With child-friendly puzzles, great graphics and lots of fun, everyone will enjoy this game.

Check out The Enigma Kids on iTunes here.

Let me know what you think!

Wednesday, 25 May 2011

Optimising Parallels performance for development

I use the wonderful Parallels 6 to perform all my Windows development. (I find working on a Mac makes Windows development a lot more bearable - at least for this old Unix-head).

In general, Parallels works superbly (and is reported to perform a lot better than VMware, if you believe the hype). However, for operations like rebuilding a large, complex C++ source tree, the virtual machine performance lagged a long way behind a native machine. Large compiles can take more than twice the time of a real Windows PC. Clearly, this taxes the host machine hard: hammering CPU, memory, and disk at once.

This problem exhibits on my four core Mac Pro with as many resources as I could throw at the problem, as well as on my more humble MacBook Pro.

I performed a number of experiments to work out how to fix this:
  • Tweaking the allocated CPU cores, memory, and disk space
  • Tweaking the settings for the virtual hard drive
  • Network building from host mac file system
None of these made much difference. In fact, I was somewhat surprised that operating on a networked disk was fantastically slower. That was a shame, as it would be advantageous to share a single source tree with my Xcode development for cross-platform development. (As it happens, I manage this by having a Windows-side git clone of the git repo on the Mac side).

However, I've now managed to get my compile times right down. Here's how.

Do bare in mind that these tweaks are in addition to the obvious steps you should take with any machine:
  • Have as fast a CPU as possible.
  • Throw as many CPU cores as you can at the problem - builds can be parallelised very easily.
  • Throw as much memory as you have at your disposal at the problem.

1. Swap the swap

The factor slowing me down the most turned out to be the Parallels virtual disk that Windows was running on. First, the swap file was hosted on it. So I made a second virtual disk, and pushed the virtual memory off onto it. That made a small, but appreciable difference.

2. Only ever use fixed size disks

In your disk settings, do not use automatically expanding disks. That's just another overhead for the computer to manage whilst accessing disks. Create a fixed size blob of disk space and run with it.

3. Use a virtual SCSI disk

This is the big one. So pay attention at the back.

It seems that Parallels can emulate a SCSI disk far, far faster than it can emulate and IDE disk. However, it defaults to creating IDE disks. I believe that this is to make installation of Windows simpler, as you don't have to fettle with custom SCSI drivers during installation.

You can't just switch the main disk from IDE to SCSI, though. Windows has a minor eppe and refuses to run if you do that. I couldn't be bothered to wipe it all and try to reinstall on a new SCSI virtual disk, so I added yet another large SCSI virtual disk for my source trees and checked out onto that disk.

Remember: it's a fixed size, non-expanding SCSI disk.

With this configuration the build simply screams in comparison to building on the virtual IDE C: drive.


I hope you find this information useful!

Friday, 13 May 2011

iOS: The Enigma Squares (1.2)

The Enigma Squares version 1.2 is available in the App Store now. Amongst other excitement, it adds Game Center support. You can now share your achievements and high score with other players. Woo hoo.

So far, I'm very impressed at how far players have got. I'm glad the game is providing an interesting challenge!

More interesting updates are in the pipeline...

Thursday, 12 May 2011

iOS: Packaging apps store submissions from the command line (my zip broke)

How to package iOS apps for submission to iTunes Connect from the command line.

I'm a firm believer in the power of the command line. I like my GUI tools as much as the next man (as long as he's a bearded Unix guru from the 1970s). But for sheer power, repeatability and flexibility you just can't beat a good script.

Which is why every project I work on has to have a simple single script that configures, builds, and packages the code, creating a well-named payload that can be installed/submitted/deployed. I feel a lot safer about the quality of a release if it's generated by a tried-and-tested script, rather than by a series of button clicks in a series of separate tools.

You know it makes sense.

iOS projects submitted to the App Store are effectively zip files with a particular directory structure. You can drive Xcode with the xcodebuild tool to build and link your distribution version of an iOS app.

However, whenever I tried to zip the project up from the command line, the Application Loader utility (what you use to submit your app to iTunes Connect) just gave bizare errors.
The CodeResources files must be a symbolic link to _CodeSygnature/CodeResources. Make certain that the bundle is on a locally-mounted volume...
Application failed codesign verification. The signature was invalid, or it was not signed with an Apple submission certificate.
Well, that's nice gibberish. Not.

However, a zip archive created using the Finder's "Compress" menu entry worked fine. Very frustrating.

Don't fear! I fixed it. Here's how to do it in your very own build script: your zipper is broken; throw it out. Use ditto instead. Here's the line from my build script:
APP_FILENAME=/path/to/build/Application.app
PACKAGED_FILENAME=MyGoodPackagedFilename.zip
ditto -c -k --keepParent --rsrc "$APP_FILENAME" "$PACKAGED_FILENAME"

Enjoy your build scripts.