Timerless Debounce in JavaScript

I wanted a debounce-like function today, but with a twist. Rather than waiting for a timeout, I wanted to wait until any current running instance of the function being debounced had finished.

Here’s a simple version of what I came up with:

function debounce2(func) {
    let isRunning = false;
    return function () {
        let context = this;
        let args = arguments;
        if (!isRunning) {
            isRunning = true;
            func.apply(context, args);
            isRunning = false;
        }
    };
};

As you can see, it’s just watching a boolean flag, that is set only while the function is running.

I needed support for Promises/Deferred, so my final version is this:

function debounce2(func) {
    let isRunning = false;
    let done = () => {
        isRunning = false;
    };
    return function () {
        let context = this;
        let args = arguments;
        if (!isRunning) {
            isRunning = true;
            let result = func.apply(context, args);
            if (result && result.hasOwnProperty("then")) {
                result.then(done, done);
            } else {
                isRunning = false;
            }
        }
    };
};

Hope this turns out to be useful. I’m not sure it’s technically a “debounce” or not, so if anyone has suggestions for a better name, please let me know in the comments.

LinkedIn is dead to me

Dear LinkedIn.

You don’t realise this, but your site is dying. It’s suffering from the social media equivalent of an auto-immune disease. The problem is recruiters. Recruiters who hassle us and pretend they’re our friends or prior connections, when in fact they are not.

I no longer use LinkedIn because I can’t – most of the activity is recruiters spamming me and the signal/noise ratio is impossible to overcome. I’m only keeping my account open so no-one takes over my name somehow.

The solution? Recruitment-specific functionality. Functionality that allows those of us not “open to new opportunities” to opt-out, and instead maintain a professional network with those we’ve actually done work with. Functionality that allows recruiters to actually connect with people who are looking for work. Keep that separate from the typical “network”, which ought to accurately represent my professional connections, not a bunch of lazy recruiters whom I’ve never done business with.

Yours regretfully,

A consternated user.

Testing URLs with PowerShell

Most people have heard of curl, but on Windows we haven’t always got that to hand. Well, the PowerShell team have thought of that.

If you just want to see whether a particular URL is working it’s as simple as:

$url = 'http://www.google.com/'
Invoke-WebRequest $url

They’ve even created curl as an alias for it. Neat.

Sometimes you’ll want to test against a web app on your intranet that requires credentials. That’s easy, too:

$url = 'http://www.google.com/'
$cred = Get-Credential 'domain\username' # Will show dialog asking for password.
curl $url -credential $cred

And of course you can perform all the usual lovely PowerShell piping greatness:

1,2,3 | %{ curl 'server$_.mydomain.com' }

PowerShell: Take care with null arguments and SilentlyContinue…

I just had an excellent gotcha at work that took down one of our test servers.

I’m using PowerShell scripts as part of an msdeploy process to stop a service in the presync command so that the files can be updated, followed by yet more PowerShell starting the service back up again in the postsync command.

My script looked like this:

Get-Service $serviceName -ErrorAction SilentlyContinue | Stop-Service

I made two mistakes here and learned two valuable lessons.

Lesson 1 – Don’t misuse SilentlyContinue

For reasons I won’t bore you with, $serviceName wasn’t defined. Normally the interpreter would’ve halted proceedings and prevented anything from happening, but since I was eating all the errors it just went along and passed $null into Stop-Service. Which of course stopped all the services.

Yes, all of them.

Even Parental Controls. PARENTAL CONTROLS! THINK OF THE CHILDREN!

Since I wanted one specific service, I’ve now chosen to do something more like this:

$service = Get-Service | ?{ $_.ServiceName -eq $serviceName } | select -First 1

if ($service) {
$service.Stop()
}

This isn’t very “functional” and PowerShell experts will have more elegant and PowerShell-like ways to resolve this, but at least I’m not eating exceptions any more.

Lesson 2 – Be careful with null arguments

In that first example, what if $serviceName was defined, but was currently null? Run this for yourself and see:

Get-Service $null

That’s right, no error, and it returns ALL your services. Which in my case would’ve been piped into Stop-Service…

This is obvious when you think about it. “Get-Service $null” is exactly the same as “Get-Service”. The default behaviour for which being to return all services.

So beware when using variables as arguments – think about what the default behaviour is if those values are null.

Lesson 3 – Scripts are software too

I said there were 2 lessons, but I just thought of this one so I threw it in. I should have known better than to eat all the exceptions. I’d never do this in C#, for example:

try
{
// Do stuff
}
catch
{
// Om nom nom
}

So why did I allow myself to do it here? I think subconsciously I was thinking “It’s only a script” but of course that was a mistake. In future I will try and make sure I treat scripts with the same respect as any other software I write. Even a simple batch file could do untold damage if badly written, let alone the more intricate things that are possible with PowerShell.

My first F# program

I love C# and have some experience in other languages. I have a hobby project and have contributed to another open source project as part of GiveCampUK. I love Pluralsight and although I’m still learning, am quite passionate about DDD, CQRS and Event Sourcing. However I still like to find alternative ways to exercise the “little grey cells” and so, despite having no use for it whatsoever, I’m going to make a concerted effort to learn F#. Here’s my first attempt of something marginally useful:

let pi = 3.141592654
let area r = pi * (r * r)
let x = area 2.0

I’ve been using tryfsharp.org, which seems to be quite a neat way to get into it. I’ll probably checkout Tekpub and Pluralsight, too. I just wish I knew what it was for

Apple Store Lockout

I’m in the market for a new laptop. I’ve spent a fair amount of time looking around and, despite being a 100% Windows user for my entire career, am seriously considering a 15" MacBook Pro Retina for my next upgrade. It’s a massive extravagance but I’m hoping it’ll last me even longer than my tired old Dell 6400.

Now since these things don’t come cheap, I want to have a good opportunity to play with them before I take the plunge. So I went to the Birmingham UK Bullring Apple store on Sunday to have another go with one.

As I arrived at the store, I saw the queue of die-hards outside the shop waiting patiently in line for the new iPad Mini, and decided there was no need for me to join that queue. I asked the chap at the door if I could come in to look at a MacBook.

"Oh we’re queuing just for entrance at the moment."

So I walked away. I still intend to get one of these machines at some point, but it’s safe to say it won’t be going on the monthly sales figures for that store.

I can understand making people queue to get one of the first handful of a new thing (putting aside the artificially-strangled stock availability), but I can’t understand why the store would make me queue behind them to look at something totally different?

DDD: Refactoring toward deeper insight

A good question came up on the DDD/CQRS group earlier today, and I thought I’d publish my response here.

The questioneer was asking how they should model deletions in their domain, where they might have a “Delete[Entity]Command”.

If you read Eric Evans’ DDD book, you’ll find it often talks about “refactoring toward deeper insight“. This basically means when you’re not sure which way to go when modelling the domain that you should go back and talk to your domain experts. Keep talking as the information soaks in and you’ll find yourself picking up on little seemingly throwaway phrases and bits of information here and there. They don’t think are particularly special because they’re so used to them, but to you these little facts are incredibly important. It’s like panning for gold.

In this case, “delete” might not be a use-case your domain experts need. In fact, unless your domain experts are in the domain of computers and file systems, I’d go as far as to say it’s highly unlikely. A Domain Model is just that – a model of the domain. Since most domains are in the real world, “delete” doesn’t really exist. You can’t “delete” a stock item, or a financial transaction. You can perhaps mark a stock item as “lost” or create a reciprocating financial transaction though.

Take an example of sales orders (modelled by a SalesOrder AR). If you ask your domain experts “what happens when you delete an order?” they’ll likely respond “Oh no – you can’t delete orders!”. You explain that’s not quite what you meant, and discover that orders can be “cancelled” or “completed”, in which case you can’t add any more line items.

In this example “completed” and “cancelled ” are the key words, and you’d implement the appropriate invariants in your SalesOrder aggregate root (AR). Of course that implementation may end up as a state machine, but then it’s often the case that an AR works like a state machine (i.e. favour a variable “state” rather than a heap of boolean flags).

In fact in general you should be wary of terms like “create”, “update” and “delete” when modelling your domain. If these are the only verbs in your ubiquitous language you should probably not be using DDD for that system.

Remember that DDD is allowing the Domain to Drive your Design. The Domain Experts know it best so they’re your best tool. Your domain model should reflect behaviours and rules required and defined by the domain experts and only those behaviours and rules.