3 Signs Your Object-Oriented PHP Is Slowing Down Your Team

In the last few versions of PHP, their OOP got real.  And this is good.  While it’s not the perfect paradigm, I am a big fan of object-oriented programming.

One of the key concepts in object-oriented programming is interface.  It’s about you and another programmer having an agreed-upon way for your code to talk to theirs.  Having small, componentized software with clearly-defined interfaces is great for teams.  It’s what’s made OO the dominant paradigm in business since the 1990s.

Unfortunately, too much PHP code these days follows the letter of the OO law, but not the spirit.  If you’re making any of the following common mistakes, you’re costing the rest of your team valuable development time.

  • Does your method return an array where the calling code is expected to just know the keys it will contain? Yes? Make it a class.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    
        // BAD - Calling code has NO IDEA what's in the returned array
        public function getPerson($id) {
            $person = array(
              'name' => 'Sean',
              'age' => 33,
              'favoriteColor' => 'blue'
            );
            return $person;
        }
     
        // GOOD: Calling code knows about the Person class
        public function getPerson($id) {
            $person = new Person;
            $person->name = 'Sean';
            $person->age = 33;
            $person->favoriteColor = 'blue';
            return $person;
        }
  • Does your method take, as a parameter, an array where the calling code is expected to just know what keys it populate? Yes?  Break it up into separate parameters.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
                // BAD - Calling code does not know what $student must contain
                public function findStudent($student) {
                    $person = new Person;
                    $person->name = $student['name'];
                    // ...
                }
     
                // GOOD - Calling code knows exactly what to pass
                public function findStudent($name, $age) {
                    $person = new Person;
                    $person->name = $name;
                    // ...
                }
  • Does your class have one single private member which is an array?  Why do you hate the guy who will have to inherit this code?  Break it up into individual private members.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    
                    // BAD - Anyone maintaining this in the future has to study 
                    // the WHOLE CLASS to see what array indexes are in use before
                    // making changes
                    class Person
                    {
                        private $_data = array();
     
                        public function __construct($name, $age) {
                            $this->_data['name'] = $name;
                            $this->_data['age'] = $age;
                        }
                    }
     
                    // GOOD - It's clear at a glance what class members are in play
                    class Person
                    {
                        private $_name;
                        private $_age;
     
                        public function __construct($name, $age) {
                            $this->name = $name;
                            $this->age = $age;
                        }
                    }

For some reason — reasons I do not understand — some PHP developers (just spend a little time on /r/php) are vehemently opposed to writing interfaces.  ”Write a class just to use as a return type?? This isn’t Java, with their labyrinthine class library!”

Well, no, it’s not Java.  But just writing classes to provide interface to facilitate teamwork won’t turn it into Java’s ridiculousness, either.  That’s a false dichotomy.

The takeaway: Other coders should never have to dig through your implementation to figure out how to work with your code.  They should have access to an interface (either in the form of a class, or literally just an interface) to tell them everything they need to know.  It’ll cut down on bugs, and save significant development time over the lifespan of a project.

Posted in Uncategorized | Leave a comment

Property Accessors using Traits in PHP 5.4

When you first wrote your PHP application, your Customer class just had a fullName property, and all was good.  ”Hi there, <?= $customer->fullName ?>!” your code gleefully outputs at the top of every page.

Then one day your boss decides that that’s too formal for a hip young company such as the one you work at, and what you should be going is greeting the user by his first name.  After a bit of a refactor, your Customer class now has two separate properties: firstName and lastName.

You change the header of your site to just use $customer->firstName now, but what about the rest of the codebase? There are a lot of places where you were using the customer’s full name, which should continue to use the full name. Should you change them all to a concatenation of the two new properties? You could, but you probably don’t want to.

More important, the guys who work on the corporate intranet use the Customer class, too.  They’re going to be annoyed, to say the least, if you tell them you’ve removed a property from that class on which they rely heavily. And rightly so, because it’d be breaking the interface you gave them.

Wouldn’t it be nice if there was some way in PHP to keep the old fullName property as a kind of alias, which just concatenates the two new properties?[1]

In other languages, you can.  In C#, it’d look like this:

public string FullName
{
    get
    {
        return firstName + " " + lastName;
    }
}

(Something similar was proposed for PHP 5.5, but unfortunately it was voted down.)[2]

Luckily, adding this functionally is really pretty easy using PHP’s overloading (which, in true PHP fashion, is not overloading in the sense that every other language on the planet uses the word “overloading”).

So let’s take a look at how.  (If you want to cut right to the chase, I’ve got an implementation available on bitbucket.)  Let’s implement it as a PHP trait, so it doesn’t interfere with your own class hierarchy:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
trait AccessorsTrait
{
    public function __set($name, $value) {
        $accessorMethodName = 'set' . ucfirst($name);
        if (method_exists($this, $accessorMethodName)) {
            call_user_func([$this, $accessorMethodName], $value);
        }
        else {
            $this->{$name} = $value; // Fall back to default behavior.
        }
    }
 
    public function __get($name) {
        $accessorMethodName = 'get' . ucfirst($name);
        if (method_exists($this, $accessorMethodName)) {
            return call_user_func([$this, $accessorMethodName]);
        }
        else {
            return $this->{$name}; // Will trigger a PHP "Undefined property" notice
        }
    }
}

(The __get and __set methods are only called if the property being accessed doesn’t exist.)

The above code checks to see if an appropriate accessor method exists for the property you’re trying to get or set.  If so, it invokes it. If not, it just falls back to the standard PHP behavior of triggering an E_NOTICE when trying to read a non-existent property, or creating it when trying to write to one.

Now back to the example of your Customer class. Apply the above trait like so:

class Customer 
{
    use AccessorsTrait;
 
    public $firstName;
 
    public $lastName;
 
    public function getFullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

This allows you to continue using $customer->fullName in your calling code.  And interface is maintained.

Posted in Programming | 1 Comment

New Open Source Projct – MVC Basics

After getting sick of copying the same basic functionality into each new ASP.NET MVC 3 project, I ripped it out and put it into a separate easy-to-use package called Sean’s MVC Basics.

Right now it’s got three modules (separated using MVC “Areas”):

1. Analytics, to include all the meta tags needed for Google Analytics, Bing Webmaster Tools, and Yahoo Site Explorer.

2. CDN, to easily toggle between using locally-hosted JavaScript, or JavaScript hosted on Microsoft’s CDN.

3. The biggie: A drop-in replacement login page which only uses OpenID & OAuth providers — NO local usernames or passwords!

Packaging up the little things I use like this and making them open source is still pretty new to me, so if you do use it, I’d be thrilled to hear about it, and if you have any feedback or want to contribute, by all means let me know!

Posted in Internet, Programming, Web | Leave a comment

Too Many Sean McClearys On The Dance Floor

Just look at this guy at the 35-second mark…

Not only is he also a websman; not only is he also from Oregon; but he also has my haircut!

Posted in Personal | Leave a comment

More On the Crapping Up of Twitter: I Am Not Alone

Scott Vandehey seems to agree with my (according to feedback I got) charming, popular opinion on the futility of trying to attach any kind of meaningful meaning to the number of your Twitter followers.  In his post he calls it “The False Economics of Twitter.”

It’s nice to see I’m not the only one who believes Twitter was designed with the intention that you follow people whose tweets you actually want to read[1] and is confused by the oft-espoused assertions to the contrary.

Posted in Internet, Opinion, Web | Leave a comment

Forget “Reach” For Measuring Social Media ROI (At Least Until It’s Actually Measurable)

A hand reaching toward the sky

Photo by Twitter user Charl22

HubSpot recently wrote that “reach” (your number of Twitter followers and Facebook “likes”) is the number 1 way to measure social media ROI, saying:

The number of Twitter followers, Facebook fans, LinkedIn group members, etc. you have is directly related to your social media success.

Perhaps the folks at HubSpot haven’t had much time to look at Twitter lately. (They do seem to be busy writing whitepaper after fact-heavy whitepaper[1]; they have so much to share with us.)

I wish they would have expanded on this.[2] Because I find it hard to believe.

Twitter: Follow Me (Blindly)

The thing is, Twitter is full of accounts who follow other people with no intention of ever reading their tweets, ever.[3] Many are powered by programs which automatically follow anyone deemed to be part of their target audience (usually determined by whom they’re already following), or just indiscriminately follow everyone, blasting the follow-shotgun drunkenly around in all directions. The thing is: They don’t care about you or your tweets; they’re only hoping you’ll follow them back so they can do one or all of the following:

  1. Advertise to you.
  2. Appear to be some kind of Twitter big shot with oh-so-many followers.
  3. Sell the account, with its 10,000 followers, to someone else. (Yes, these services exist. I’m not linking to them.)

There’s also no shortage of people who do this manually, over time — people who follow thousands of other users. There are not even enough hours in the day for them to read what their followers tweet.

I’m not saying there’s anything wrong with following a gazillion people on Twitter, or that it’s misusing the service. What I’m saying is: obviously, many many Tweets go unread, and that fact does not jive with a belief in an ROI-predictive “reach” which is based on a number of followers. [4]

Facebook: You Really Like Me?

Like us on Facebook, and get this coupon! When we reach 3000 likes, we’ll donate to this charity!

How many Facebook campaigns attempt to motivate people to like them for reasons other than actually liking their product or service? (Many, from what I’ve seen.)

Is there a good chance this person is going to want to chat with you and other passionate users about, let’s say, mountain bikes (yeah, your company sells mountain bikes) once they’ve clicked whatever they had to click to get their Starbucks coupon?

Because, if not … well, how is this more valuable than just buying a big list of email addresses from some shady company, and firing up the spam cannon?

Give me a big stack of coupons, or freemiums[5], or funny kitty videos, and I’ll give you a big stack of Facebook “likes.” Even if you’re giving away something relevant to your business, all the “likes” in the world won’t mean anything if the people don’t actually, you know, like you.  It does not mean all your future updates and messages will “reach” them It only means you’ve paid, in time or money, to get their attention for a few seconds: a convoluted, expensive advertisement.

Can We Get Around Reach, Please?

Followers and “likes” are not true measurements of reach. A company with 500 followers, 50% of whom are engaged and interested in their product, has more reach than one with 10,000 followers where only 1% are interested.  And how many of each company’s followers are computer programs? Self-promoters just looking for a follow-back? Imaginary hot chicks “lookin’ for cool people lolz”?

“Reach” in the sense the word is being tossed around is actually how many people theoretically could have seen your message. (And by all appearances, quite a few people didn’t.)  It’s not a useful metric; it will not help you determine whether you’re wasting your time not.[6]

Anyone who dedicates time and resources to “focusing more of your social media efforts on generating new fans and followers,” as HubSpot recommends, should first ask them (or anyone else, for that matter) to connect the dots and show the causation (not correlation) between more social network pals and success.  My fear is that it actually works in reverse, and that fans and followers are not the cause of successful social media use, but can be a result of it.

But then, I’m not a marketer, so by all means: set me straight.

PS[7] – Sorry about all the footnotes!  I just re-read A Supposedly Fun Thing I’ll Never Do Again and it must have had an effect!

Posted in Internet, Opinion | 5 Comments

Where’s Sean Been?

All quiet on the blog front lately.  So where’ve I been?  Well, I moved to Austin for a project I’m working on called Common Tastes.  It’s a recommendation engine for anything and everything, which we can apply to niche-targeted websites on any subject, like beer, tea, fast food, video games, etc.

Check it out, and by all means, if you have any feedback, please let us know!

P.S. – See that little doodad over there on the right, saying “People who like this blog will love this blog?”  That’s the Common Tastes Predictor Widget, in case you’re curious.

Posted in Personal | Leave a comment

3 Tips for Effective Web Writing

Web writing is a genre of its own, and one day universities will offer degrees in it just like they do for journalism. (In fact, some probably do already.) Half way between newspaper and brochure writing, copy for the web must both inform the user and present a professional appearance.

Unfortunately, most people writing for the web today tend toward one spectrum or the other. Jakob Nielsen, from whom most of the information in this article originates, is the master of usability and his website is just as easy to use and navigate as you’d expect; but find me one company out there with a website design as bland as his and I’ll show you a soon-to-be-out-of-business company.

Similarly, websites with giant mastheads, lengthy introductory text and useless start pages are sadly a dime a dozen.

What’s proven is this: You only have a split second to snag a web user, and users don’t read; they scan.

Simple to grasp, yet so often forgotten.

#1. Know Your Users

Your users are doing one of two things on your site: Seeking or browsing.

The Seeker

If your website is a resource, then your website is for seekers.  And for the seeker, you need to step back and get out of their way.

Do not put three paragraphs of bland marketing copy between the seekers and what they’re looking for. Seekers have no patience, and, unless you’re the only game in town, will keep on surfing to the first one of your competitors that doesn’t make them think* in order to get what they want.

Don’t worry about your page looking too skeletal. Think back to the early days of search engines, when there were more contenders out there. Who emerged as the leader? The ones who surrounded their search forms with a bunch of extra content they wanted you to look at? Or the one with one simple input field and a button?

The Browser

Browsers are users you’ve drawn to your site and now that they’re here you need to tell them something. Maybe it’s your latest promotion. Maybe it’s this list of funny links.

Unlike with the seeker, instead of stepping back and getting out of the way, you need to get the the browser’s attention; the text is the focus. Put the important words in the F-pattern zone where they’ll see it. Start sentences with key words that will jump out at them.

In either case, dense blocks of text copied from your brochure about how you’re the #1 provider of such-and-such neither helps them find what they’re looking for nor tells them anything they care about.  It will only lose them in a hurry.

#2. Use Bullets For Scannable Text

Ever notice that so many web pages and blog entries are titled “7 Ways To Do This” or “5 Tips For Doing That”? It’s because readers will expect a bulleted list. And the readers? They like their bulleted lists.

Why? First of all, the user knows it’s likely to be a short article, and is therefore more likely to check it out.

And bulleted lists make it easier to get the gist of the text without having to invest the time in actually reading it all.

#3. Make Your Paragraphs Shorter

Ever notice how newspaper paragraphs consist of only a single sentence? They’re not dumbing it down. Newspapers have dealt with readers scanning their text to find the interesting stuff for years.

I’m not saying a single sentence is the maximum, but do make your paragraphs more specifically-themed than you would for your term paper.  Readers guess from the first couple of words what to expect if they continue reading, and decide in an instant whether or not they’re interested. Having each idea stand out visually makes it easier to jump to the next one, and the text faster to scan.

* Don’t Make Me Think by Steve Krug, by the way, has made such an impact on me that I now inadvertently work its title into discussions about web usability.

Posted in Internet, Web | Leave a comment

The Problem with OpenID and OAuth? Attributes.

OK, some of you out there would say there are a lot of problems with OpenID and OAuth. But what’s on my mind today is the usability problem they both share: attributes.

I’m not talking about the old complaint that “no user will know what his OpenID identifier is or what to do with it.”  As I mentioned in my previous post 5 Mistakes No Modern Website Should Make, some sites do manage to make OpenID logins painless for even the most grandmotherly of users.  What I’m talking about are the attributes.

So as any schoolchild knows, when doing an OpenID or OAuth transaction, the client website — the one the user is logging in to (in to which the user is logging?) — may request some extra information (“attributes” in the biz) from the provider (the site that verifies the user’s identity).  I’m talkin’ email address.  I’m talkin’ birthdate.  Information your users may have, back in the olden days, been prompted to enter on your sign-up form, available at your fingertips.

“Whoa there, Big Brother,” you say, voice a-tremble. “What if I don’t want your website to have all that information? I just want to log in and play your damn flash game!”  Well well, just settle yourself down, settle yourself right down, kiddo.  Did you honestly think the smart people who created OpenID aren’t working for you? Did you honestly think the bunch of talented Mr. Ripleys* who invented OAuth would leave you dangling?

Well “aww hellz no” is the answer to those two questions.  Should the client site request any extra information, the provider site will ask the user (hey! that’s you!) to confirm that he wants to share this information.  And you can say “yes” or “no”.  If my website requires your email address — a very common practice — to create an account, this is a faster and easier way for the user to give it to me.  If my website would also like but doesn’t need your birthday (so we can send you an e-card, really, it’s going to have an adorable kitty on it, you’ll love it) I can ask for both.

But what if the user only wants to share the email address?

And that’s the problem: It’s all or nothing.  When the user says no, that he doesn’t want to share all of this information, the login is canceled.  You’d think it wouldn’t be rocket science to have a list of requested attributes with a checkbox by each one, so the user can pick and choose which information he’d like to share.  But not one major OpenID or OAuth provider offers this.

Many sites will choose not to make use of attributes at all, knowing that most users will choose “No” when they see the mile-long list of personal information every website would like to have.  And it’s a shame, too, because this seldom-used feature could have made online sign-up forms a thing of the past.

* I’ve never actually seen The Talented Mr. Ripley and don’t know referring to the creators of OAuth as a “bunch of talented Mr. Ripleys” makes any sense, at all.

Posted in Internet, Opinion, Web | Leave a comment

Your Clients Don’t Know What They Want

Maybe the biggest dysfunction of the programming world is that clients (customers if you’re a freelancer; that guy from Marketing if you’re a 9-to-5) will approach developers not with their problem that needs solving, but with a plan for the application they think will solve it. And the developer will, unquestioningly and tragically, implement it.

Your client’s plan will be given to you, bafflingly, as a PowerPoint document. This is your first indication that this person should not be designing a software application on his own.  It will be full of vague phrases like “streamlined” and “hard-wired.” At many points in this document, you will not even know what the client is talking about.  But you will implement it anyway, shaking your head and saying “If that’s what he wants…

The problem is that that’s not what your client wants, even if he believes otherwise. And if you implement what he asked for, word-for-word, he will not go away be satisfied.

So what does he really want?

Find the Problem

Don’t misinterpret my mocking our hypothetical client; this situation is not his fault. It’s yours.

Don’t get depressed because you’re taking instructions from someone who writes the word “WEB” in all capital letters as it were an acronym. He’s allowed; you are the IT specialist around here.

Buried somewhere in the plans for his application lies the real problem he is trying to solve, and you need to find it. If you can’t find it, ask. If he can’t explain it, have him show it to you. If you have to, spend the day in customer service, or in the lab, or at the shipping dock with him. You cannot give the client a solution without understanding the problem.

Don’t worry about offending the client by second-guessing him. Make it clear that this is to help you do you job, and trust me, they will appreciate the careful attention you’re giving them. They will be happy.

Create Functional Specs

In an ideal environment, functional specifications would be handed to you by an analyst who’s already hammered everything out with the client, technical specs would come from the architect, and you could dive right in to programming. But you do not work in an ideal environment. Otherwise you would not currently have a guy with pretty-boy hair pressuring you to drop your other projects to start on his, and a boss who wants you to just frickin’ handle it, please, will you?

You need functional specs. If you don’t write them now, start. Don’t try and doctor the client’s original document up and pass it off as the specs. Don’t even copy and paste from it. You can’t be confident that you’re about to develop a working solution for the client until you can write down the problem and a description of how your application will solve it. Functional specs are not only for client buy-in and covering your own ass later, but more importantly they are to verify that you understand the problem and will solve it.

When you’re done, show it to the client. This is his opportunity to tell you that you’ve misunderstood something, or why the application you want to develop isn’t going to work.

Just like with any other kind of writing, creating the functional specs will expose the angles from which you (and the client) haven’t viewed the issue yet, and bring up new questions. It’ll take a few drafts before you’ve got it, but changing a Word document is faster than re-designing database tables.

Use Mock-Ups

Your client doesn’t know what a combo box is. He believes he knows what tabs are, but he’s actually thinking about tree controls.

Mock-ups are invaluable for showing the client how your proposed interface will work, and they take almost no time at all. Drag and drop one up in Visio, or just draw it with a pencil. It doesn’t have to be a work of art, it just has to visually explain what you’ve already described verbally in the specs.

Every screen, popup, and dialog of your interface should be mocked up.  A few seconds spent mocking up that one seldom-used input dialog will save you a couple hours fixing it one month from now.

Now Start Coding

And don’t feel like you’ve lost time in getting here.  In the end, all the documenting and dialogging with the client will save you time.  When you finally start coding, you will move very quickly, without back-tracking and making fewer mistakes.

The first couple times I saw this in action, I was amazed.  Projects where only 40% of the time was spent on actual coding finished faster than projects where 90% of the time was spent coding.  This really brings into light the difference between software development, which you’ve been doing since the moment your client approached you, and coding.  They are not synonymous.

Accept That There Will Be Revisions

You’ve gone through three drafts of the functional specs before the client signed his name to them. You’ve faithfully documented the technical specifications for the application (which is outside the scope of this article, but you did do that, right?) so your co-worker can pick up where you left off after you’re, oh I don’t know, devoured by grizzlies or something. You’ve got a basic, tentatively-bug-free build of your application ready for the client to take a look at, and… he forgot to tell you that he needs to enter last week’s widget price when shipping on Thursdays, otherwise the delivery truck will explode!

Why why WHY didn’t he mention this before? You discussed the application with him at length. You practically wrote that damn functional specs document with him at your side and you even drew him pictures of how it would look! For the love of God could you be working with bigger imbeciles???

The client isn’t an imbecile. Don’t forget that the two of you are breaking new ground here. After all, if applications to solve this exact problem were a dime a dozen, the client could buy it for $99.99 and you’d be shuffling down the cold, cold street with your shopping cart.

As long as your application’s been developed with a solid understanding of the problem its solving, almost any revision can be accommodated without having to go back to square one.

Posted in Opinion, Programming | Leave a comment