Strange PHP scoping

Posted on Tuesday, May 11th, 2010 under , ,

I came to the conclusion that PHP is the programing language with the weirdest features. After the variable variables mess, that allows to you to name your variables stuff like !@#$%^&*()_+= and not be able to use them directly, I thought I saw everything. But no, yesterday I’ve bumped in another strange PHP feature. An even stranger feature.

Take a look at the code below:

class Example
{
    public function dynamicMethod($string)
    {
        // calls method baz() of the same class
        // class Example *does not have* a baz() method 
        $this->baz($string);
    }    
}
 
class Foo
{
    public function bar()
    {
        // a dynamic method called statically
        // no Example object is being instantiated
        Example::dynamicMethod('whatever');
    }
 
    public function baz($string)
    {
        echo 'Method baz() called with param "' . $string . '"' . PHP_EOL;
    }
}
 
$foo = new Foo();
$foo->bar();

What do you think the code will do? Yield an exception? A syntax error? Work? Well, strangely enough, it works:

Tudor-Barbus-MacBook% php blog-example.php
Method baz() called with param "whatever"

…and it seems that this feature is here to stay and be supported in the future, since I’m using the new PHP 5.3 version:

Tudor-Barbus-MacBook% php -v
PHP 5.3.1 (cli) (built: Feb 11 2010 02:32:22) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies

I wonder how this can be useful to somebody.

Unit testing & TDD

Posted on Wednesday, December 2nd, 2009 under , ,

Last week, I had a discussion with Ionut – my colleague at Ninespices – about a piece of code I had wrote in one of our applications. The piece was meant to log the current user’s actions to the database for future reference. It looked something like this (more or less, the actual code isn’t that important):

protected function _log($info) {
    $identity = Zend_Auth::getInstance()->getIdentity();
    $this->save(
        array(
            'user_id' => $identity->id,
            'info' => $info,
        )
    );
}

Ionut said to me: “I don’t like it! It’s hardcoded!”. I said that it’s not, as I don’t hardcode anything, since we all know that each time one hardcodes something in a software application, God kills a kitten.

But Ionut asked me a simple question: “How do you test it? How do you mock Zend_Auth?”. For the record, Ionut is the Test Driven Development guy of the team. He always writes tests for his applications, whereas I don’t, since my code “just works”…well, kind of…sometimes :) . The point he made is interesting: how do you mock Zend_Auth? The answer is obvious: D’oh, you don’t!

In order to be able to properly use unit testing to test a piece of code, that code must be written in a manner that allows unit testing. To make a method “testable”, you must not instantiate other objects, call other classes’ static methods and so on. For instance, let’s consider a piece of code that looks like this:

public function methodThatRequiresTesting($input) {
    // get data on the current logged user
    $identity = Zend_Auth::getInstance()->getIdentity();
    $userId = $identity->id;
 
    // instantiate a helper class
    $helper = new MyLibrary_Helpers_Foo();
 
    // do whatever
}

It’s quite obvious that this code isn’t “unit testing friendly” as you cannot mock the helper or Zend_Auth. The proper way to write it in order to be “unit-testable” is either:

public function methodThatRequiresTesting($input, $userId, MyLibrary_Helpers_Foo $helper) {
    // do whatever
}

…or…

public function methodThatRequiresTesting($input) {
    // get the user id
    $userId = Zend_Registry::get('userId');
 
    // get the helper
    $helper = Zend_Registry::get('Helpers/Foo');
 
    // do whatever
}

This way, one can easily add mocks instead of the actual objects, isolate the functionality of this particular method and test it. Of course, the first “testable” code is wrong, as it breaks separation of concerns. A method should have input and output, and any additional entities (functions, classes) used inside the method’s body in order to compute the output from the input should be encapsulated within the method. Receiving these entities as input is a very bad practice, for obvious reasons.

The second code example is better from an architectural point of view, but it can be quite memory intensive, as one might instantiate a lot of helpers and place them in the registry without ever using them, thus wasting valuable system resources.

That very night, Ionut & I went to the 26th edition of Wurbe, where one the the topics was – beside the crappy beer – Test Driven Development. There was a somewhat heated debate on whether to use TDD or not, unit testing, functional (system) testing and so on. I particularly liked one of the opinions expressed there – by a guy who’s name I forgot :) – on functional testing. There’s no need to write unit tests for all your components. Only write tests for those components which contain complicated algorithms, so each time you refactor the code and optimise the algorithm, you know if what you did is good or not. And write a system test, in the end, to test the whole application.

It makes more sense to me this way.

Google tech talks on API

Posted on Wednesday, August 19th, 2009 under ,

Google Tech Talks are Google’s answer to TED Talks but, as expected, with much more focus on technology. And they show some very interesting stuff, like the following talk on how to design an API. If you have a free hour, watch it.

Via Alex Novac.

Valuable software

Posted on Friday, January 30th, 2009 under ,

I’ve been a programmer for about 5 years now. I’ve worked on a large variety of projects. Small projects, medium projects, large projects. I’ve worked in teams, I’ve worked alone. I was an employee. I was a freelancer. But from these 5 years, I’ve spent about 1 year – an astonishing 20% – or maybe even more working on projects that were never used. They were paid for. I was paid for my work, but the project was simply cast aside. Nobody used it.

And I’m puzzled, some of those projects were quite expensive, not the average “500 euro for a 5 pages with contact form and Google maps widget website” deals you find when working with freelancers. After months of work and thousands of euros paid…nothing. The project was quietly buried. And I’m not a singular case. I’ve talked to my friends that also work as developers and most of them worked more than once on a project that was never used. Is software so worthless than you can easily cast aside projects that costed so much? It seems it is.

I believe it’s because the clients usually think about huge projects, with thousands of features that will make them the next month’s billionaires, while forgetting that developing projects of that magnitude usually take months or sometimes years to be implemented and by the time it’s ready, might not worth a dime and it would be cheaper to simply throw it away than continue pumping money into it.

Imagine a project that was started 18 months ago and and was initially scheduled to be released in 24 months. Let’s say that this project was meant to be “the next big thing” in real-estate with all the possible features, with anything a real-estate agent’s heart could ever desire. Would be in production today? I seriously doubt that. Nowadays, the only way you can become a real-estate millionaire is to start as a real-estate billionaire. And why would anyone pump money in that? The market moves so quickly, that this year’s niche could be full of competitors next year.

The solution: start small. Build a large project in small incremental steps. Use agile development methodology. Be ready to change the specs at any time. Build the project as modularised as possible. Make sure that you can easily add new stuff and remove worthless stuff. Have a look over MVC, it allows a more agile approach on web projects.

And of course, always ask yourself: what would Captain Picard do?

Scrum & agile development

Posted on Monday, January 26th, 2009 under ,

When I started my programming career, I was convinced that waterfall is the way to go. I felt the need to have clear specifications for the project I was working on since the very beginning. The let me see what you’ve done so far e-mails from the customers were a real pain in the ass, because since no partial releases were scheduled, I usually had to pick and choose parts of the project that seemed to work and build an adhoc release. The result was what one might call a Frankenstein of software development that had major bugs, didn’t quite work and the only thing it could do right was to annoy everybody. The client was annoyed because he was feeling that his money are not well spent and I was annoyed because I was stuck with a meddling client who doesn’t stick to the agreed plan. If the release isn’t scheduled for another three months, the he should go and bother somebody else. Maybe a government employee from the IRS. But instead of doing just that, the client was sending bug reports -- fix this, change that -- on the “Franky version”. So the project was slowly branching into two. We had to continue the development of the main branch, as initially agreed, but we also had to do some bug fixing and changes to the adhoc version. Fixing those bugs was taking away valuable development time and the estimated time of delivery was being pushed further and further in the distant future.

Now that he could see parts of the software, the client was changing his mind about some of the specifications and was asking for new features that weren’t originally planed. Features that were incompatible with what we’ve done so far. And…long story short: epic fail!

After spending about 2 years in the waterfall hell, I have found out about Agile development and scrum. It’s a whole different approach that divides a large scale project into smaller parts that are easier to implement, easier to test and easier to change if the customer changes his mind. In the current economical climate, even without meddling customers, a waterfall approach to software development is bound to fail. Imagine how things looked 12 months ago and how they look now. A software project must be able to adapt quickly and meet the market’s requests.

I have found this video on Adobe’s (Romania) blog that explains agile development and scrum in about 10 minutes. Enjoy!

Page titles and MVC

Posted on Saturday, January 10th, 2009 under ,

After taking the Zend PHP 5 exam, I’m focusing on the Zend Framework (I think that the sidebar on the right hand side could use a little green :P ). A more theoretical subject today. It’s about the page’s <title> tag and the MVC pattern. According to CakePHP’s implementation of the MVC, the decision about a page’s title should be taken at the “controller level”.

class StudentsController extends AppController {
    public function index() {
        $this->pageTitle = 'View all students'; // setting the page title
    }
}

In Zend’s documentation, I couldn’t find anything on this issue, as ZF is much more permissive than CakePHP and anyone can choose his own way to do things. And it isn’t always a good thing. Sometimes less options are better. In Zend Framework, you can set the page title in the controller, like such:

class StudentsController extends Zend_Controller_Action {
	public function indexAction() {
		$this->_helper->layout()->getView()->headTitle('View all students'); //  setting the page title
	}
}

or in the view

/**
 * views/scripts/students/index.phtml
 */
$this->headTitle('View all students');

The main question here is if the title is tag is business logic or presentation. Due to the title tag high impact on SEO and my CakePHP background, I personally lean towards the first option. The title isn’t just presentation, it’s more than that and setting the title should be done at the controller level.