Someone thinks this is good

No.  How this is considered good, I don’t know.  Who wrote the code isn’t important – this is the way the code is supposed to be written.  At least, this is the way it’s being demonstrated.  With a straight face.

I cannot fathom how anyone can honestly think this is good and want to encourage its use.

<?php
return array(
// lots of config stuff here

            /**
             * Routes
             */

            'ZendMvcRouterRouteStack' => array(
                'parameters' => array(
                    'routes' => array(
                        'zfcuser' => array(
                            'type' => 'Literal',
                            'priority' => 1000,
                            'options' => array(
                                'route' => '/user',
                                'defaults' => array(
                                    'controller' => 'zfcuser',
                                    'action'     => 'index',
                                ),
                            ),
                            'may_terminate' => true,
                            'child_routes' => array(
                                'login' => array(
                                    'type' => 'Literal',
                                    'options' => array(
                                        'route' => '/login',
                                        'defaults' => array(
                                            'controller' => 'zfcuser',
                                            'action'     => 'login',
                                        ),
                                    ),
                                ),

// more config stuff here
);

Learning the vi language

I’m a long time user of vi (and I use vi interchangeably for both vi and vim), but it wasn’t until recently that I really started to understand the way vi works.  Oh, I could be productive in vi, but I wasn’t adept at learning vi.  I edit files in vi, I could open windows, I could move around, copy and paste, search and replace, and generally do the normal things you can do in other editors.  So when I had to open up vi, I didn’t freeze up and get lost.

Don’t Repeat Yourself

The problem here is two-fold.  First, I was looking for how to replicate actions I would perform in other editors. Saving a file, editing text, copy and paste, search and replace: all these things easily map to something you’d do in a traditional IDE.  You don’t replace a character in a traditional IDE.  You delete a character and enter a new one.  To copy and paste big blocks of text, you highlight that text with a mouse.  You navigate to different tabs with your mouse.  When you want to split your window, you probably have to do so with the menu.  You don’t append to a line.  You simply move your cursor and start typing.  You don’t jump to a character, and while you can, you rarely jump to a line.  You aren’t yanking lines, you don’t concern yourself with buffers, and you don’t repeat your actions.

Basically, an IDE more closely resembles a word processor for programming languages, whereas vi is a completely different beast (vi vi vi, editor of the beast, after all).

Therefore, the first thing I had to understand before really learning vi was I had to look past replacing what I did with an IDE, but rather, understand how to do things in vi.  And this is a fairly easy concept to understand once you learn one of the defining principles of using vi: if you have to keep pressing the same key to do something, you are probably doing it wrong.  Consider the basic movement keys: hjkl.  Using ‘j’ and ‘k’ to move more than one line should indicate to you there is a better way.  Moving to the top of the screen, the bottom, the middle, move up a page, half a page, or down.  These aren’t things you do in an IDE (you scroll), but in vi, that is an essential piece to the puzzle.

So, every time I wanted to do something, and I found myself repeating actions that seemed awkward, I’d search for a way to do it.

Find out more about noticing and unlearning vi anti-patterns with this excellent article from Tom Ryder.

Learn the Language

This leads us to the second thing I had to understand in order to really being learning vi.  You don’t learn vi by learning commands, you learn vi by learning a language.  Once you have a firm grasp of the language, you can start putting together your own commands.  Discovering new commands seems to become more intuitive.

Lets see this language in action.  Normally, if you want to delete a line, you’d type ‘dd’.  This deletes the line (and stores it away so you can paste it later if you want).  What if you want to delete more than one line?  You could repeat ‘dd’ on each line you wanted deleted.  But let’s say you want to delete the next 10 lines.    This is where the language comes in.  What you want is to delete 10 lines down.  So, you start with ‘d’, then enter 10, and finally, ‘j’ for:

d10j

This isn’t so much a command you need to remember.  Rather, it’s easier if you understand the language.  Deleting 5 lines up can be constructed the same way:

d5k

Once we learn how this language works, we can create our own commands

‘==’ will indent the current line.  We can follow the same pattern as delete to construct the following:

=5j

This properly indents the next 5 lines.  Of course, we can also do ‘gg=G’, which will move you to the first line, and then indent all lines until the last line.  We can do ‘ggdG’ as well, which will delete all the lines in the file.

The actual commands aren’t important.  Rather, it’s the language.  Once you understand how ‘d’ works, you can use the same language in other areas as well.

Want to copy the next five lines?  Just knowing that ‘yy’ will copy the current line, you could easily discern that ‘y5k’ will yank (copy) 5 lines up.

You can learn about speaking the vi language by reading an excellent article from Yan Pritzker.

Investment of time

Yes, learning vi will take time. It’s not something that will come naturally.  It’s a tool, and like any powerful tool, you have a lot to learn to truly start taking advantage of it.  It’s a professionals tool.  It’s a craftsman’s tool.  It’s something that, regardless of whatever else you might learn, will benefit you as long as you are programming.

Sure, you might enjoy your IDE, and I’m not here to suggest you drop your favorite tools.  Rather, it’s worth the investment to understand vi, it’s language, and how it works.  Even if you aren’t using it every single day, you’ll appreciate being able to open up the editor and using it without feeling constrained.

Other Resources

2012 – Reflection and Resolutions

The Story Thus Far

It’s safe to say 2011 was a big year for me.  In 2001, I moved to Montreal, Quebec to be wife my now-wife, Piera.  I got my first real job programming PHP for an online casino company.  After the company went bankrupt, I started my own company with 2 friends.  A credit card processing company called myVirtualCard.  This lasted for a good number of years, but we finally had to shut down.  Meanwhile, in 2007, I’d married Piera.  In 2009, I started work again at Gamma Entertainment handling their credit card processing department.  In 2008, we had our first son, Joseph Michael Robert Lotito.  In 2010, we had our second son, Julian Alfonso Lotito.  We also learned that summer that Joseph might be autistic.  We then spent the next year fighting with the Quebec medical establishment to get whatever helped we could for him (We got no support).  In the sprint of 2011, we’d had enough, and I made up my mind to move back to the US.  After all, we had that option.  In a few short months, I’d interviewed, got hired, found a place, made several flights all over the country, and in August of 2011, moved to Telford, PA to begin work at myYearbook.com.

Back in the U.S.A.

So, here I am, back home at the start of 2012.  If you’d asked me a year ago where I would be, here is not where I’d imagine.  But I’m glad we made the move.  As it turns out, Joseph does have Autism.  Had we waited a bit longer, he would be in much worse shape.  As it is, it will still require intense ABA therapy.  There is also some worry Julian might be autistic as well.  I believe the number was 90+ out of 150 autistic children are boys, and siblings of autistic children are 70% likely to be autistic as well.  Suffice it to say, we are keeping a close eye on him.  Luckily, he seems, if anything, to simply be mildly developmentally delayed.

The treatment we’ve received here in Bucks county in Pennsylvania has been outstanding.  Seeing the difference in care, I could never willingly return my children to Quebec.

2011

So for me, 2011 started with me in the US, on a trip to visit family, and it ended with me living here.  It’s rather humorous when you think about it, and the road it took to get here.  Most of 2011 can be summed up with this: “how did I manage to control this chaos.”  Between work, worrying about my son, finding a job, moving, getting acquainted with that new job, getting the wife and kids accustomed to a new country, and everything that entails: it was exhausting.  I had very little time for myself, it feels.  I put aside most of my hobbies since moving.  No painting, no gaming, no writing, very little exploratory programming (though it’s started getting better).

2011 was about the family.

2012

This year, with the family settled, I need to look at bettering myself.  Joseph is getting the help he needs to, I’m employed at a wonderful company and work with a lot of smart people, and I have immense opportunity to grow as a developer.

Resolutions are a traditional way to start the new year.  The problem is, this year started without me having thought of one.  I just simply forgot.  At my brother’s new years party, my sister-in-law handed me a card, and told me to fill it out with my resolutions.  She’d mail it to me at the end of the year.  This sounded like a great idea, except I had no idea what to write.  I simply hadn’t though of a resolution.

Since then, I’ve been pondering what I want to do.  There are the grand goals, the cliche goals: get in shape, make money, be happy, win the lottery.  I wanted something more concrete.  I want to change my life in small but meaningful ways.  Over the course of the year, I want to focus on one aspect, and carry over the habits I can.  My resolution isn’t to change any one thing.  Rather, my resolution is to better myself.

January – Freedom

I feel like I’ve already wasted half the month in coming up with what I want to do.  So, January is the month I’m giving to myself.  I’m not committing to anything in January.  No pressure.  I’m allowing myself to prepare for the coming months.

February – Hobby

In February, I want to start a hobby that isn’t related to programming or computers.  In fact, it shouldn’t involve computers at all.  This will most likely involve either wood working or miniature painting.  The former is possible with a garage, but I have no equipment.  The later I have everything for, including ample space.  However, the former involves me getting off my butt, which is something I should address at some point.

March – Getting Healthy

I really shouldn’t wait so long, but by March, I want to be on the road to health.  More importantly, this is the month when I want to start really learning more about getting healthy.  Eating right, exercising and enjoying it, and taking care of myself.  I’ve done this before, and by March, I was doing really well.  I can do this.

April – Ludum Dare

I want to write a game.  In my spare time, I’ve been playing with an event driven gaming framework in JavaScript.  It’s been a lot of fun, and come April, I want to take part in Ludum Dare 23.  I’ll probably take a couple days off before and after, and make sure the wife knows what I’m doing.  It will require training and practice before hand, but by April I should be ready to go.  This means, of course, having completed a game or two before hand.

May – Open Source All the Things!

I haven’t contributed to an open source project in a long time.  The goal here would be to contribute some libraries and code I’ve written (will write).  It’s not much, but I need to spend time putting them together and releasing them, or at least finishing them up.  I’d always want to release the JavaScript Game Event Engine I’m working on (for use with Ludum Dare).  May would be set aside for getting that up and released.

June – iOS App

By this time, I will have wanted to release an iOS App.  I have one in the works.  It’s a simple app, but great for learning the system, and something I would use (always a plus).  It’s also an app that isn’t covered well in the app store.  So, by June, I’ll want to have released it.

July – Learn a new language

I’m not really sure which language, but by this time, I’d want to try to learn something new.  I was introduced to Erlang back in August of 2011, and enjoyed it.  Maybe putting some more time into it would be fun.  Regardless, July should involve learning a new language.  The goal will be to write a simple HTTP server, I think.  That’s always fun, and a great way to learn the system, it’s libraries, and has a fairly practical value.

August – Node

If myYearbook holds Node the same time this year as the previous year, we’ll have it in August.  Node is the company developer retreat.  3-days away at some remote location having our own mini-conference.  2011 was fun, despite the storm and lack of power.  Besides of Node, however, I’ll also have time to continue learning that new language.

September – Talk More

I want to push myself to start giving more talks.  I’m already giving a talk this coming friday at a PHP meet up group, but it’s a small affair.  By September, I want to be in a position to give more talks, and really start pushing it.  I have no issue standing in front of people and talking (I actually enjoy it).  My issue has always been self-confidence.  I mean, do people really want to hear me give a talk?  By September, I want to make that a yes.  This will involve blogging more, writing more, contributing more of course.

October – Master Smaller Tools

There are a lot of tools out there in the Unix world, and I simply don’t know them all.  While over the course of the year, I’m sure I’ll learn many new things, I want to allow myself time in October to simply learning these smaller tools.  Maybe coming to better understand writing vim plugins, or getting a better handle on make or bash.  The goal here isn’t to learn anything in particular, but rather focused attention on learning these tools.

November – NANOWRIMO

NANOWRIMO.  Nuff said.

December – Reflection

With the holidays approaching, now is the time for reflection, relaxation, and discovering if I’ve achieved this rather grand list of things I want to accomplish.

Is it doable? Yes.  Can I do it? Sure.  Will I? Who knows?   So much can happen, but having a plan helps out.  I’d like to think that every every month now I have something to look forward to, something to keep me on track.  Many small goals that will, I imagine, improve myself.

I hope I am as resolved as I will need to be.

Blocks

  1. Do one thing.
  2. Do it well.
  3. Keep it concise.
  4. Use only what is given.
Today we continue from Comments and explore how to refactor out code from blocks.  In Comments, we learned to extract code out into it’s own method whenever we use a comment to describe a block of code.  Today, we are going to look at how to do the same thing with blocks.
A block of code is any code that exists within a if, a loop, or a switch statement.  A good rule of thumb is every time you indent your code.  Our goal is to keep indents inside your code from going beyond 2 levels.  Let’s look at a typical method where we break this rule.
public function createAction()
{
    $adminForm = new Form_User();
    $adminForm->removeElement('dealership_id');

    if ($this->getRequest()->isPost()) {
        if ($adminForm->isValid($_POST)) {
            $mAdmin = new Application_Model_DbTable_Users();
            $result = $mAdmin->createAdmin(
                $adminForm->getValue('name'),
                $adminForm->getValue('email'),
                $adminForm->getValue('password'),
                $adminForm->getValue('role')
            );

            if ($adminForm->getValue('notify') === 'yes') {
                if ($adminForm->getValue('notifyPhone') === 'yes') {
                    $notification = new Application_Model_DbTable_PhoneNotification($mAdmin);
                } else {
                    $notification = new Application_Model_DbTable_Notification($mAdmin);
                }
                $notification->sendNotification();
            }

            if ($result)
                $this->_forward ('confirm');
        }
    }

    $adminForm->setAction('/admin/create');
    $adminForm->setMethod('post');
    $this->view->form = $adminForm;
}

Before we start refactoring this, I want to cover a couple things.  First, the above is a small example, but it can still be used to explain our need.  Secondly, what we learn here can be applied to code, regardless of the size or complexity.

Complexity

Before we set out on this road, we need to define complexity.  Specifically, I’m referring to Cyclomatic Complexity.  The best definition of Cyclomatic Complexity that I’ve found is from the PHPMD page on Cyclomatic Complexity.

Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are ‘if’, ‘while’, ‘for’, and ‘case labels’. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.

Our goal is to keep what we write in the low complexity category.  At this point, we should go through the sample code from above, and figure out how much complexity there is.

public function createAction()  // Complexity 1
{
    $adminForm = new Form_User();
    $adminForm->removeElement('dealership_id');

    if ($this->getRequest()->isPost()) {  // Complexity 2
        if ($adminForm->isValid($_POST)) {  // Complexity 3
            $mAdmin = new Application_Model_DbTable_Users();
            $result = $mAdmin->createAdmin(
                $adminForm->getValue('name'),
                $adminForm->getValue('email'),
                $adminForm->getValue('password'),
                $adminForm->getValue('role')
            );

            if ($adminForm->getValue('notify') === 'yes') {  // Complexity 4
                if ($adminForm->getValue('notifyPhone') === 'yes') {  // Complexity 5
                    $notification = new Application_Model_DbTable_PhoneNotification($mAdmin);
                } else {  // Complexity 6
                    $notification = new Application_Model_DbTable_Notification($mAdmin);
                }
                $notification->sendNotification();
            }

            if ($result)  // Complexity 7
                $this->_forward ('confirm');
        }
    }

    $adminForm->setAction('/admin/create');
    $adminForm->setMethod('post');
    $this->view->form = $adminForm;
}

A total of 7 complexity, on the high end of moderate complexity.  You might be looking at this code and wondering what makes it so complex.  It is simple enough.  It’s built to handle a form.  It checks input, creates a new user if the form was submitted in a valid format, and sets up notifications that were obviously a choice in the form.  It finally forwards off to the confirmation.

But, that is actually a lot of complexity.  To test this function, we’d need at least 7 test cases.  Even more so, this method violates some of our rules.  Do one thing.  It does many.  It’s not concise.  And it’s also not just using what is given.

We are going to focus on the complexity portion today.  We are going to bring down the size of this method step by step.

Indents are intents to modularize

Every time you indent your code, you should be thinking about modularizing.  In other words, if you indent your code into a block, you should consider moving that code into it’s own method.

Let’s start with the extremely large if in the middle there.  The one that checks to see if the request is a post.  When we indent that block of code inside, we should ask ourselves if that code inside can be better moved to it’s own method.  The answer is a resounding yes.  Within that block of code, we have 5 levels of complexity.  By moving all that complexity out of the createAction method, we will help decrease the complexity of that single method.  More so, we make that method easier to read, and we are able to compartmentalize the code even more.  We make our code even more reusable.

Where with comments we used the comment as an indicator of a new method, here we use the ideated block of code as an indicator.

public function createAction() // Complexity 1
{
    $adminForm = new Form_User();
    $adminForm->removeElement('dealership_id');

    if ($this->getRequest()->isPost()) { // Complexity 2
        $this->letFormHandleInput($adminForm);
    }

    $adminForm->setAction('/admin/create');
    $adminForm->setMethod('post');
    $this->view->form = $adminForm;
}

protected function letFormHandleInput ($adminForm) // Complexity 1
{
    if ($adminForm->isValid($_POST)) { // Complexity 2

        $mAdmin = new Application_Model_DbTable_Users();
        $result = $mAdmin->createAdmin(
            $adminForm->getValue('name'),
            $adminForm->getValue('email'),
            $adminForm->getValue('password'),
            $adminForm->getValue('role')
        );

        if ($adminForm->getValue('notify') === 'yes') { // Complexity 3
            if ($adminForm->getValue('notifyPhone') === 'yes') { // Complexity 4
                $notification = new Application_Model_DbTable_PhoneNotification($mAdmin);
            } else { // Complexity 5
                $notification = new Application_Model_DbTable_Notification($mAdmin);
            }

            $notification->sendNotification();
        }

        if ($result) // Complexity 6
            $this->_forward('confirm');
    }
}

Referring back to createAction, we see that the complexity has dropped to a mere 2 points.  Granted, letFormHandleInput is 6 points, but we aren’t done yet.  Each method should be easy to understand, and easy to test.  createAction is now incredibly easy to understand.  It creates a new form for display, and if it receives a post request, it let’s the form handle the input.

I’ll admit, I’m not too enamoured with the name of the new method, but it’s simple, and defines exactly what the method does.  More importantly, we’re also passing the form in.  This means that we can pass this method any form.  If something fails, we come out of the method, and continue with the display of the form.  Normally, I’d want to also define letFormhandleInput as

protected function letFormHandleInput(Zend_Validate_Interface $adminForm, array $data)

Here, $adminForm would be explicit in what it is, and I’d pass in the $_POST data, rather than calling it.  In the method itself, I’d swap out the calls to $adminForm->getValue, and instead call directly from $data.  However, this goes beyond our discussion here.  However, I make mention of this because those simple changes are not only easy to make, but value in terms of maintainability, testing, and longevity.

Because letFormHandleInput is still complex, we need to extract some methods out from it as well.  letFormHandleInput is actually wrapped directly around a giant if.  A simple check to see if the $_POST data is valid.  After that point, everything is indented. It also happens that the form doesn’t do much after that.  We grab data from it, but as I noted above, that’s easily removed. Regardless, the sign is fairly clear: indented blocks are what we are looking for.

public function createAction() // Complexity 1
{
    $adminForm = new Form_User();

    $adminForm->removeElement('dealership_id');

    if ($this->getRequest()->isPost()) { // Complexity 2
      $this->validateNewUserDataInput($adminForm, $_POST);
    }

    $adminForm->setAction('/admin/create');
    $adminForm->setMethod('post');
    $this->view->form = $adminForm;
}

protected function validateNewUserDataInput (Zend_Validate_Interface $adminForm, $data)  // Complexity 1
{
    if ($adminForm->isValid($data)) { // Complexity 2
        $this->addNewUser($data);
    }
}

protected function addNewUser ($data)  // Complexity 1
{
    $mAdmin = new Application_Model_DbTable_Users();
    $result = $mAdmin->createAdmin(
        $data['name'],
        $data['email'],
        $data['password'],
        $data['role']
    );

    if ($data['notify'] === 'yes') {  // Complexity 2
        if ($data['notifyPhone'] === 'yes') {  // Complexity 3
            $notification = new Application_Model_DbTable_PhoneNotification($mAdmin);
        } else { // Complexity 4
            $notification = new Application_Model_DbTable_Notification($mAdmin);
        }

        $notification->sendNotification();
    }

    if ($result) // Complexity 5
        $this->_forward('confirm');
}

Once again, we’ve reduced complexity, and in our resulting method, our complexity has gone down.  As well, we’ve also remove the task of creating a new user to another method.  addNewUser does exactly that, it adds a new user and all it’s associate baggage.  I also took this time to better define what we needed, and what we didn’t.  You’ll see I’m pulling directly from $data now.  No need to pass $adminForm around.  Also, letFormHandleInput only requires a Zend_Validate_Interface object now, further decoupling ourselves.  I also took the liberty of renaming letFormHandleInput to validateNewUserDataInput.  This name better describes exactly what it does.  Granted, it also goes directly to creating a new user, but that’s something for another day.

Back on topic, lets take the next step, and refactor addNewUser in the same manner we’ve been.  Let’s see, we have another block of code.  This block sets up notifications.

protected function addNewUser ($data) // Complexity 1
{
    $mAdmin = new Application_Model_DbTable_Users();
    $result = $mAdmin->createAdmin(
        $data['name'],
        $data['email'],
        $data['password'],
        $data['role']
    );

    $this->setupNotificationsForUser($data, $mAdmin);

    if ($result) // Complexity 2
        $this->_forward('confirm');
}

protected function setupNotificationsForUser (array $data, Application_Model_DbTable_Users $mAdmin)  // Complexity 1
{
    if ($data['notify'] === 'yes') { // Complexity 2
        if ($data['notifyPhone'] === 'yes') { // Complexity 3
            $notification = new Application_Model_DbTable_PhoneNotification($mAdmin);
        } else { // Complexity 4
            $notification = new Application_Model_DbTable_Notification($mAdmin);
        }

        $notification->sendNotification();
    }
}

In this case, I just decided to encapsulate the entire notification code into it’s own method.  Here now, setupNotificaitonsForUser can be passed proper data, and from that, we can setup notifications for a users outside the creation of a new user.  This means when you write your code for editing a users notification preferences, you already have your notification setup.  Complexity is at 4, but that brings us to the low category of complexity.  There is one more thing we can do to simplify this code.  However, by this point, you should already see what we can do, and how it will simplify the code even further.

By extracting out the second if/else clause in setupNotificationsForUser, we abstract away the creation process.

All these methods can be applied to other forms of blocks of code.  Every case in a switch should probably have its own method.  Any loop should call out to a method.  At every level of complexity, you want to keep things as simple as possible.  When you read a block of code, it should be simple.  It should do something specific.  It should do is quickly, and it should do it well.

Comments

I once posted  “comments indicate future refactoring.” I want to reaffirm my belief in that, and clearly explain. In order to fully appreciate this, let’s lay down some fundamental beliefs. These are beliefs I have built on experience, and later, I’ll apply them to more general fundamental beliefs like SOLID, but for now, these are simple rules I feel are good to follow.

  1. Do one thing.
  2. Do it well.
  3. Keep it concise.
  4. Use only what is given.

These aren’t overly complex rules. In fact, they are pretty simple. We are going to aim to meet these rules in a rather simple manner: using comments.

Now, let’s define what type of comments I’m referring to. I’m not talking about DocBlock comments. These are comments that allow for parsing by specific tools and allow us to generate documents about the code.

I’m also not referring to comments that repeat the code.

// increment a by 1
$a++;

That is a poor comment, and should be removed. It does nothing except add to confusion.

The comments I’m referring to, however, are a bit more involved. But let’s start with an exercise.

Code should explain what it does. It doesn’t always do this. For example, what’s the purpose of the following code?

if ( preg_match(EMAIL_REGEX, $input) || 
     is_numeric($input) || 
     preg_match(USERNAME_REGEX, $input) ) { /* ... */ }

It’s easy to see what the code is doing, but not the purpose. If we add a comment, it will help matters.

// Check to see if the user input matches one of the searchable data sets
if ( preg_match(EMAIL_REGEX, $input) ||
     is_numeric($input) || 
     preg_match(USERNAME_REGEX, $input) ) { /* ... */ }

Hey! That helps. The code checks to see if the user input matches a pattern for searching a data set. Okay, that helps. But it’s still problematic. The comment isn’t clear. Is it referring to just the if-clause, or is it referring to the block inside the if-statement. Can you trust the comment? After all, as time progresses and code enters maintenance phase, things can and will change. Is it easy to read? It’s not difficult, but when you are read the comment, you then have to mentally associate that with the code. It takes extra effort. And for what? Saying something explicit.

Maybe it’s better that we ask a simple question: What is the comment trying to tell us?

If the input matches a searchable data set, run the blocked code.

Luckily, we can say that succinctly.

if ( $this->inputMatchesSearchableData( $input ) ) { /* ... */ }

// ...
function inputMatchesSearchableData ( $input )
{
    return preg_match(EMAIL_REGEX, $input) ||
           is_numeric($input) ||
           preg_match(USERNAME_REGEX, $input);
}

Using the extra method refactoring recipe, we’ve made our code much, much easier to read. inputMatchesSearchableData says exactly what the method does, and in our original block of code, it reads much easier than the comment did. We’ve also refactored the code that checks to see if the input is searchable. We’ve split responsibility, and suddenly, our original method does one less thing.

Every time I use a comment to explain what code is doing, I always ask myself if it’s code that should be removed. If what the code is doing isn’t directly related to the parent method, the answer is most likely yes.

Often times, the comment itself is a good indicator of the name of the function. Extract the method out, and keep each method small, precise, and simple.

I picked the destination

In August, I moved from Montreal after almost 10 years to the small town of Telford, Pennsylvania, a little less than an hour north of Philadelphia.  It’s a beautiful little town.  Our home is nestled in a small development filled with couples with kids that are around the same age as Joseph and Julian.  Lots of prospective baby sitters in the next few years as well.  Within 10 minutes, we have pretty much everything we could be looking for in terms of local shopping, as well as several wonderful local pizza joints.

It’s a wonderful place.

I work at myYearbook.com, a wonderful social discovery site, in New Hope, Pennsylvania.  It’s a good hour commute in the morning, and a bit longer on the way back home.  The people that work there are incredibly smart, highly motivated, and know their field extremely well.  It’s wonderful working with them.  Every day is a learning experience.  It’s a wonderful place to grow and expand professionally.  Between the number of published authors and open source contributors, as well different technologies we are using, it’s hard for anyone not be learning something new every day.

But why did I move?

Joseph.  Born in November of 2008, he was pre-diagnosed with autism in the summer of 2010 at one-and-a-half years old.  For a year, my wife and I fought he Quebec government to get help for him.  Between both private and public care, he was constantly denied treatment.  Coming to Pennsylvania, the public care he receives as a child with autism is light years beyond what Quebec had to offer.  Before getting here, we’d gotten appointments.  Within the first month, he’d received more help for autism then he’d ever gotten in Quebec.  It was at the same time wonderful and sickening.  To know he was getting help, and to realize how many people are still suffering in Quebec.

My greatest hack was moving to Pennsylvania and getting my son help.  It was making that decision to move.  When you’ve lived in a place for 10 years, it’s hard to disrupt your life.  But one afternoon, after another major setback, I told my wife that I was going to move us to the US and get Joseph care.  It wasn’t a discussion.  It was a decision.  A few months later, we left Quebec hoping for the best.

There are times in your life you are given an opportunity, but those are far and few between.  Waiting on them is a mistake.  Instead, you need to make your own opportunities.  You need to make a decision.  There was a lot of work between deciding to move, and finally moving in to our new place.  I won’t say it was easy.  But it was easier than I thought it would be.  But still, it was a lot of work.  But the hardest part was finally admitting that the only person that could make this happen was my wife and me.  Making a decision.

We all make choices in our lives. They can be simple choices.  What to have for dinner?  What to name a variable?  What tree to use for this data set?  These are easy choices.  They are easy because we have control over them.

The decision to move, as big as it was, was easy to make when I understood I had to take control.  I couldn’t wait on a careless government.  Who could I trust, more than my wife and I, for my son’s well-being?  No one.

Since moving, Joseph has received a tremendous amount of real help tailored for his condition.  In November, when he turns 3, he goes in for more intensive treatment.  Everywhere doors are open.  The effort is on his treatment, not on finding treatment.

From the moment I made that decision until today, I never reflected on the difference of that decision as opposed to others I’ve made in my life. What, after all, truly made this decision different?

I made a choice about what I wanted.  After that was made, I simply had to make it happen.  Plot the course.  I didn’t make a choice to make a plan to reach an outcome.  I picked the destination.

People will tell you it’s not where we go but how we get there that matters.  And while I don’t disagree with the latter part, the destination had better matter, or else you’re just wandering aimlessly.  So what does all this mean?

Pick a destination.  Get there well.

How not to automatically detect location

We’re moving.  We are leaving Montreal, and moving to Telford, PA.  And it’s happening soon.  Very soon.  Luckily, we have most everything in order.  A place to move to, a job, utilities, TV, Internet, phone and movers.  We have most everything packed.  A lot of work moving, especially to a different country, but it’s exciting.

One thing I am finding difficult to overcome, however, is the internet.  More precisely, “smart” developers who decide to use my IP address as an indicator of what country I’m in and deny me the ability to even *look* at something.

My IP Address is not my nationality

Despite living in Canada for almost 10 years, I’m still American.  Do not assume that just because I have a Canadian IP address that I am Canadian.  Most web sites get this correct.  They display error messages talking about the location.  Some, however, make the extra leap and assume I am Canadian.  I am not.  While I don’t have anything against Canadians (my wife and kids are, after all), it just strikes me as odd.  And it’s wrong.

It’s even more wrong when the error message says the offer is only available to American’s or someone with an American address.  I am one, and I have one.

I want to read up on your service

Let’s be clear: I realize you don’t offer your service to people living in Canada.  You can even tell me that.  But redirecting links and preventing me from even reading the material is dumb.  I’m moving, and I’d like to read up on what you have to offer.  I know better than you where I am, why I’m at your site, and what I need from it.  It’s one thing from preventing me from actually making a purchase, it’s another thing entirely to block all the information on a service from me.

Even more annoying are the sites that redirect you, but then allow you to browse the sites anyway.  I have to try and search the site for the information I was originally directed to.  And that’s annoying.

Don’t shun me

Living in Canada, I’m fully aware of how the laws make certain things difficult.  Living in Quebec means I’m completely aware of how downright difficult it is to provide services here.  Quebec is in every exception for anything ever offered.  I mean, if I come across some special that is available in Canada, I need only read the small print to find the Quebec exception.

But that doesn’t mean you should go the extra step of blocking me from seeing an offer or getting updates on future offers.

Listen, I’m moving to a new area, a new country, a new way of doing things.  I want to do as much as I can before getting down there.  Stop trying to be “smart” and get all creative.  Do the bare minimum, warn me, prevent me from spending money: find.  I can accept that.  But stop preventing me from learning about your service.

iTunes Match and the Music Labels

Apple announced on Monday iCloud, Lion, and iOS5.  Oh , and one more thing: iTunes Match.  A 24.99$ a year service that lets you take your existing pira…. er, ripped music and get Apple to legitimize it.  The revolutionary part of this announcement has to do with the labels.  It’s clear the music labels were involved in approving this plan, and it’s also clear that a part of that yearly fee is going to the labels.  It’s low enough people will pay it.  A lot of people.

But the big story is simply that the labels have found a way to profit from the pirates.  With a system like Apple in place, they can now track which songs are being stored and get a cut.  It’s an amazing system, and whoever came up with the idea is pretty slick.  Of course, the flip side is they are also going to make money from people who already purchased the CD.  They don’t mind, I’m sure.

How to get an invite to Forrst

If you don’t know, Forrst is a invite-online developer and designer community started by Kyle Bragger (@kylebragger).  It’s a fairly friendly community, with lots of great feedback from a wide variety of people with all levels of skill.  However, one thing Forrst strives for is a community for all levels of people.  From beginners to experts, designers and developers, Windows/Mac/Linux users, all are invited.  At least, as long as you are willing to put forth the effort.

To get an invite, an existing member must invite you (and invites only come to those who contribute back to the community), or you have to be voted in after having applied.  To join, you go to the “I want to join” page.  On that page, it asks for a few pieces of information, including a  link to something you’ve done.  A github page, open source project, some fancy design.  Something to show that you are a developer or designer oriented person.

The second part, however, is the most important part.  The Forrst join page asks you to provide sample feedback for a random post.

Provide Good Feedback

Listen.  Forrst is all about communication.  Communication between all types of people.  This means feedback is important.  Poor feedback is bad.  We don’t like it.  However, good feedback is cherished, loved, and rewarded.  So, when Forrst asks you to provide feedback for a post on the Join page, realise that real Forrst members are going to review this feedback.  It takes 3 votes to get you in, and chances of finding 3 people to agree that “That looks awesome” is good feedback is slim.

Let me try to make this clear: the feedback you provide on the join page indicates to us the type of feedback you’ll provide once a member.  If the feedback provided is essentially worthless, then making you a member won’t help the community.  A community built up around feedback.  What this means is that you should put some effort into your feedback.

So, here are some tips on how to write good feedback.

1. Pick a post you can answer

Forrst provides a nice little button that you can click on.  It will reload the post to provide feedback for.  Don’t just settle for the first post you see.  Instead, find something you are actually interested in commenting on.  You aren’t expected to comment on everything that gets posted to Forrst.  Not everyone that gets posted to Forrst is going to get good comments.  So, click a way and find something that will allow you to provide good feedback.

2. Why, not what

“That looks awesome!”

The person you are providing feedback too is probably not going to see your post, so you aren’t going to win brownie points for complimenting work.  Though, if the work is good, providing compliments is fine.

However, in this case, “That looks awesome” is fairly useless.  It just explains what you feel.  It doesn’t explain “why” it looks awesome.  Take a few minutes to go into detail about what you like and why.  Even if you can’t express it clearly, try.  Remember, effort is key here.  Explaining why you like something takes a bit more than just saying you like it, but it provides a lot more value.  Others can learn from it, the original poster can focus on those areas.  Who knows, in explaining why you like something, you might learn a little about yourself.

3. We need Effortmore, not Effortless

Okay, that was bad.  But, the point is, your feedback should take a bit of effort.  It is, after all, an application to join.  And regular members like me are going to read this feedback.  I’ll by frank, if I see a 10 word comment, I don’t bother looking at anything else and move on to the next person.  Maybe it’s unfair, but I figure it’s the same amount of effort put into the comment.

It doesn’t take long.  A couple minutes at most.  Ask yourself after you’ve finished the comment if it’s something you’d like to receive.  Does it actually share a unique idea.  Does it express an opinion? Is that opinion explained?

The Elite

Forrst isn’t about being among the elite.  It’s about being among people who are just like you.  Frankly, if you feel applying to the site and actually putting effort into the feedback is too much work, then Forrst probably won’t benefit you.  That’s fine.  However, if you truly want to join, then maybe this little piece of advice will help you avoid a pitfall you might not think about.  From the Forrst join page:

Since Forrst is a very critique- and discussion-oriented community, we ask prospective users to leave sample feedback on a post from one of our members.

We review this.  The members.  And I imagine those of us that review these potential members are very interested in keeping Forrst’s quality high.  We will be picky.  After all, we want to log into Forrst and enjoy what we read there.  We want to be part of a community of people that we’d go out drinking with.  A little bit of effort will go a long way.

Join us!  We aren’t elitist.  We just want you to know that this is the place for you, and we want to know that you’ll get a lot out of this community.  But only as long as you are willing to give.

Of course, as mentioned, the other way to join is to be invited by an existing member with invites.  Like myself.  In that case, beer is ALWAYS a welcomed bribe.