Today I Learned - Rocky Kev

TIL thinking in States

POSTED ON:

TAGS:

This is a great reminder of how to approach a problem.

"Sorry, we're super-duper, mega-out of milk."

To a programmer, that's an odd statement. You're either out of milk or you're not.

There's no "super duper" state. There's no 'So out of milk there's chaos'.

Using a example from a e-commerce platform:

If the user paid, then ship it. If it's shipped, then the whole order is complete.

This function smells funny:

function isComplete() {
return isPaid() && hasShipped();
}

Why? That whole function is encompassing two states.

When we think in state machines:

State machine rules:

img source

You can ONLY move to each state after completion of the prior one.

An order can only be in one of three distinct states:

The order if finalized when hasShipped() has occured.

So that function should be:

function isComplete() {
return hasShipped();
}

Via:
https://97-things-every-x-should-know.gitbooks.io/97-things-every-programmer-should-know/content/en/thing_84/


Related TILs

Tagged:

TIL thinking in States

This is a great reminder of how to approach a problem.

TIL thinking in States

This is a great reminder of how to approach a problem.

TIL thinking in States

This is a great reminder of how to approach a problem.