Familia Corporātus

| | Comments (0)

Is your company a company, or is your company a family?

The question has a number of rather pertinent ramifications. It's good to have an answer.

If your company is a family, then when you invade my workspace for a family activity, preventing me from getting any work done and thereby causing me to miss deadlines and slip schedules, well, that's okay. We're family. We'll deal. Pass the cake.

If, on the other hand, your company is a company, then when you invade my workspace for a family activity — preventing me from getting any work done and thereby causing me to miss deadlines and slip schedules — it's on me to make up the time. Your actions have become my problems, which is ample justification for me to be more than a little peeved.

So is your company a company, or is your company a family?

If your company is like most companies, it's both — you get to do what you want, and I get screwed with no right to be angry about it.

Here's a protip about 'most companies' — people good enough to get jobs elsewhere... do.

Damned Whippersnappers

| | Comments (0)

Remember being a teenager*?

Teenagerititude is the state of believing that everyone else in the world is phenomenally stupid — that the solution to every problem is blatantly obvious, and that everyone would be much better off if they'd just shut up and do as you say.

The interesting thing about being a teenager is that you don't actually outgrow it.

At some point a light goes on in your mind, the scales drop from your eyes, the metaphor similes upon you, whatever, and you realize you've been a teenager and you stop. You congratulate yourself on being so adult and on owning up to your past bad acts and you move on with your life.

And then a few years later you realize that you were mistaken, that you were actually still a very-slightly-more-evolved form of teenager despite that revelation, and the scales drop from your lights and you eye what you metaphor and you move on with your life.

Until it happens again.

Eventually you reach a degree of meta-awareness — you recognize that Socrates kinda had a point about the whole 'knowing you know nothing' schtick. That's when you ascend to a higher plane of existence! Then you help Teal'c and MacGuyver out a few times, and eventually you return to the show with your tail between your legs because it turns out your landlord won't accept 'art' in lieu of money. But hey, higher power. You got that going for you.

Until, damn it, it happens again.

Meta ain't enough, nor is meta-meta. Maybe there's some omega-meta state where you stop realizing that you're an idiot, and you get to draw a Batman logo on Anthro's cave wall just to reassure the idiots who didn't figure out the pattern based on Kal and Hal and whatnot. But I can't be sure of that. I think any form of personal growth boils down to suddenly recognizing what a jackass you've been and thus becoming an exciting new form of jackass.

...

So what's the moral of the story? The moral is that I'm stupid, you're stupid, he's stupid, she's stupid, and the primary differentiating point between us is our awareness of our own incompetence. So when something looks dumb to you, remember that it either is dumb, or it's smart in a way you haven't thought yet deciphered — and prudence dictates that you assume the latter until you've assembled reasonable support for the former. And even if something turns out to be legitimately dumb, don't draw conclusions from that, because oftentimes there's more to the story. It's not uncommon to find clever implementations of a piss-poor design; that may be a sign of abstractional schizophrenia, or it may be a sign of the blind leading the brilliant.


*If you currently are a teenager, shut up and get the hell off my lawn. Damned kids.

Imagine that video rental shops worked like libraries; there's a whole network of affiliated branches, and if this library doesn't have it, they can get it at the cousin library across town and deliver it for you. And as long as we're imagining, take it a step further: they can get it for you for no extra cost, absolutely instantly.

So that's the way video rentals work, and they all stock VHS cassettes, and that's that. But now a sea change occurs: somebody invents DVDs. All of the video rental shops start building their stock of DVD titles, and while doing so they take advantage of their affiliation network, so if your favored shop doesn't have Joe Dirt on DVD, they can get it from the shop across town.

But one little shop bucks the trend — even though DVD is the future, they decide to stick with VHS. And that works out okay for them, because while the other rental shops are investing heavily in building a DVD library, they're making room by selling off their VHS cassettes, and this little dark-horse shop is gobbling them up like popcorn, and their library is huge.

Now it's ten years later. Every video rental shop around the world has switched to DVD, but this little shop is still on VHS. It's impossible to buy a VHS deck in stores, so this shop rents or sells you a VHS player when you sign up for membership, but that's okay actually — some people find that kind of convenient.

But now something interesting happens — a big, new, hit movie comes out... but only for DVD. This little shop is caught-flat footed, because they simply can't compete here. So what do they do? They advertise!

This shop starts running ads, talking about how the local Blockbuster has a tiny library of titles, and it's absolutely terrible how small their library is. Now, in a sense that's true; any individual Blockbuster may have a small library available, but keep in mind the affiliate network — when you get a DVD at Blockbuster, you may be getting it from any one of dozens of DVD rental places all over the world.

---

So what does any of that have to do with anything?

Well, VHS is the creaky old CDMA digital cellular technology. DVDs are GSM, the modern cellular network architecture that almost every cellular carrier around the world uses. Our hit DVD is obviously the iPhone.

And the tiny dark-horse video shop, that's Verizon.

Now, don't read this as a defense of AT&T. Personally I haven't had all that much trouble with them, but I know plenty of people who reflexively spit upon hearing those letters, and it's pretty clear that AT&T has been using their iPhone windfall to make money hats rather than investing in their network infrastructure, and that's clearly subpar. But while I dislike incompetence and don't care for spin, I absolutely loathe deception, and that's what Verizon's 'map' ads amount to, in my opinion.

The 'Verizon map' in those ads is, by necessity, a map of Verizon-owned-and-operated coverage zones; they have to be Verizon-owned-and-operated, because nobody else is running CDMA these days, just like nobody's using VHS or Windows 95. The 'AT&T map' to which they compare themselves, meanwhile, is of AT&T-owned-and-operated coverage areas, which is not at all representative because AT&T has reciprocal carriage agreements with GSM carriers throughout the US, and roaming agreements with GSM carriers around the world.

Personally, I can't stand Verizon — they have a policy of installing Verizon-controlled firmware on every phone they support, which tends to cripple the phone by removing built-in features to encourage you to use Verizon's expensive and inferior network-based equivalents. Ever try to copy a ringtone to your Verizon phone using standard Bluetooth file transfer? If you did, I'm betting it didn't go so well. But Verizon does have a lot to offer customers, and if they want to be taken seriously they should compete by explaining the benefits of Verizon rather than deceiving people about the non-deficiencies of their competitors.

Ask each of your developers who the three best developers in the company are. Only ask the developers — managers can't answer because they're in no good position to know. Average out the votes and produce a consensus 'top three' list. Hold on to it, and repeat the survey every six month.

If over a year has passed and two of those three people are still on the list, your company is probably screwed. You might not actually have realized it yet, but that doesn't make it any less true. Your management or business metrics may actually be positive, but if your development team isn't improving, the technology underlying everything is stagnating and sooner or later the smell will reach your customers.

Unless you already employ the best programers in the world, of course.

And if you really and truly believe that you employ the best programmers in the world, then unless your company name rhymes with 'Foogle', 'Schnapple', or 'Sicromoft', you're probably really screwed.

Normal function calls are easy to write; you call DoSomething( ), it executes and returns, and you continue on your merry way.

Asynchronous function calls seem, at first blush, only a little more difficult — instead of calling DoSomething() and executing your follow-up code after it returns, you pass in a callback: BeginDoSomething( Action callback ).

So, problem solved, let's go home. Unless you need a return value, that is. But even then it seems simple; to turn a synchronous method like int CalculateSomething( ) into an asynchronous method, you just pass it a delegate that takes a parameter: void BeginCalculateSomething( Action<int> callback ).

So is that it? Nope. Because all of that is wrong.

Even though the original DoSomething( ) method had no return type, it still had a return path — it could throw an exception. Let's imagine that BeginDoSomething looks something like this:


public void BeginDoSomething(Action callback)
{
    PrepareForLongRunningOperation( );
    
    ThreadPool.QueueUserWorkItem(
        delegate
            {
                LongRunningOperation();

                callback();
            });
}

A handy way to think about this sort of thing is to figure out where a thrown exception would emerge.

If something goes wrong within the call to PrepareForLongRunningOperation, that happens in the same context as the calling code — any exceptions will throw up to the calling code and come out of its call to BeginDoSomething. The same applies to the call to ThreadPool.QueueUserWorkItem — no problem there.

But what if LongRunningOperation throws?

LongRunningOperation would throw up into whatever internal part of the ThreadPool implementation actually launched it. That exception can't come out of ThreadPool.QueueUserWorkItem, because by the time the asynchronous anonymous delegate is running ThreadPool.QueueUserWorkItem has already returned. And since the exception can't come out of ThreadPool.QueueUserWorkItem, it also can't come out of BeginDoSomething — which means there's no way for the calling code to get the exception.

There are two main approaches to this problem — error handlers and completion calls.

Error Handlers

Instead of passing your begin method one callback, pass two: a callback to be invoked if everything goes to plan, and an exception-accepting callback to which errors will be passed.


public void BeginDoSomething(Action callback, Action<Exception> errorHandler)
{
    PrepareForLongRunningOperation( );
    
    ThreadPool.QueueUserWorkItem(
        delegate
            {
                try
                {
                    LongRunningOperation();
                    callback();
                }
                catch(Exception ex)
                {
                    errorHandler(ex);
                }
            });
}

// Sample usage:

BeginDoSomething(
    delegate
    {
		// Do something now that we're done
    },
    delegate(Exception ex)
    {
		// Do something with the error
    });

There are strengths and weaknesses to this approach. The biggest strength of this model is that it forces the calling code to think about error handling — the prompt for it is right there in the method signature. Error handling tends to fall through the cracks in any sort of code, but it's especially easy to overlook in an asynchronous context (It's also a lot more dangerous in an asynchronous context, because often dropping a callback invocation will cause a process to spin forever, sucking down resources and accomplishing nothing).

Separating the success case from the failure case may be either a strength or a weakness, depending on the particular task. Sometimes it makes your code much cleaner, but it often happens that your success and error handler need to share context and implementation, which can make for some very ugly code.

Completion Calls

Instead of just invoking a parameter-less Action callback or a single-parameter Action<TReturn> callback, your code calls a single-parameter callback and passes it an Action or Func<TReturn> that the callback in turn invokes.


public void BeginDoSomething(Action<Action> callback)
{
    PrepareForLongRunningOperation( );
    
    ThreadPool.QueueUserWorkItem(
        delegate
            {
                try
                {
                    LongRunningOperation();
                    callback(delegate { });
                }
                catch(Exception ex)
                {
                    callback(delegate { throw ex; });
                }
            });
}

// Sample Usage:

BeginDoSomething(
    delegate(Action complete)
    {
        try
        {
            complete();
        }
        catch (Exception ex)
        {
            // Do something with the error
            return;
        }
        // Do something now that we're done
	})

At first blush, this seems like a much clumsier solution; you're essentially trusting the calling code to call your completion method. That's true, at least in this case.

Where completion calls really shine are for asynchronous calls returning values; instead of calling their callback and handing in an Action, you call their callback and give it a Func<TReturn>, which they then must invoke to get their result. That gives you an opportunity to throw exceptions that they can't cleverly bypass:


public void BeginCalculateSomething(Action<Func<int>> callback)
{
    PrepareForLongRunningCalculation();

    ThreadPool.QueueUserWorkItem(
        delegate
        {
            try
            {
                int result = LongRunningCalculation();
                callback(() => result);
            }
            catch (Exception ex)
            {
                callback(delegate { throw ex; });
            }
        });
}

// Sample Usage:

BeginCalculateSomething(
    delegate(Func<int> complete)
    {
        int result;
        try
        {
            result = complete();
        }
        catch (Exception ex)
        {
            // Do something with the error
            return;
        }
        // Do something with the content of result;
	})

Personally I prefer completion calls, mainly because the the pattern works so well for return values. In practice, any time you need this sort of a pattern it's because you care about return values; if you need to ensure that X happens after Y, it's generally because X depends on the result of Y. If X doesn't depend on Y, that's often a sign that you're being too linear in your analysis and that the tasks should be happening in parallel.

Microsoft seems to have collectively reached the same conclusion; IHttpAsyncHandler, the asynchronous methods off of SqlCommand, and the asynchronous forms of WebRequest all use the completion call approach.

Functional Programming

| | Comments (0)
public void BeginGetSingle(TIdentityCriteria identityCriteria, CompletionCallback<TItem> callback)
{
    TFilterCriteria filterCriteria =
        CriteriaUtilities.UpgradeCriteria<TIdentityCriteria, TFilterCriteria>(identityCriteria);

    RestClient.BeginGet<TItem>(
        CriteriaUtilities.CriteriaToUrl(
            filterCriteria,
            m_Map,
            m_ServiceUrlBase,
            r => typeof (TItem).FullName.Equals(r.OutputPayloadClass) && r.AllowedVerbs.Contains(Verb.Get)),
        completionFunction => callback(() => completionFunction().Payload));        
}

My function takes a function and when done it calls that function, passing a function that the calling function calls for the result.

Now in fact my function calls another function taking a function accepting a function to call for its result, and to that function it passes a function which when called calls the first function passing a new function that when called calls the function that was passed to the function that my function passed to the other function, thereby returning the result of that function to the function that called my function.

And they say you can't write Lisp code in C#.

Xclan Night

| | Comments (0)

Still a work in progress, but pretty cool looking already in my rarely-humble opinion. The trick is to dim the red and green components while leaving the blue intact.

Xclan screenshot 1
Xclan screenshot 2

I'm trying to decide the best way to show text bubbles. Everything's pretty scrupulously iPhone-friendly this time around (that's actually what got me started on Xclan again, figuring out how to work with UDP CFSockets in a run loop), but as I understand it uploading new text textures every few frames will bog an iPhone down pretty quickly. I'm thinking of switching my NSOpenGLView to a CAOpenGLLayer and putting a bunch of CATextLayers on top for the bubbles.

There's actually an NSTextField in a layer in the game window; on Leopard it floats above the NSOpenGLView, but in Snow Leopard (where the screen shots were taken) it's invisible. I haven't pursued it because I was planning on replacing the OGL view with a layer anyway, but it's a strange difference.

taxes.png

Just Chatting

| | Comments (1)
MCK_Feminist.png

iPhone 3GS

| | Comments (0)
The 'S' stands for 'Stupidname'.

I look at that name, and immediately it brings to mind the Apple IIGS (which stank).  That then makes me think of the Apple III, which stank to high heaven.  It's like somebody at Apple said, "hey, I know, let's give it a name evocative of our greatest corporate failures!"

Seriously, the only worse name would've been the "iPhone Performanewton: Centris Edition".  They could pair it with an eWorld membership and give it a built-in GeoPort Telecom Adapter.  

Maybe bundle an AAUI transceiver.

Okay, I'm done.