How variable naming can significantly impact your teams productivity

What does kunnr mean? Anybody? If you’ve worked with SAP than you might know but to everyone else good luck. What about rqnb? Does it mean anything to you? Isn’t it obvious to you that rqnb represents a request number? Seriously though, why do people name their variables so cryptically?

Think about it a little, how much easier would the code be if the variable was named requestNumber instead of rqnb? And for those of you who think it will save a few keystrokes, hence make your typing faster, remember that each time you use the variable you have to remember how to abbreviate it. With one variable it’s not so bad, but when you have dozens, you’re always looking up the different variable names.

Continue reading: How variable naming can significantly impact…

Every method must have 10 lines of code or less

The key idea is not short methods nor few methods per class. The key idea is Conceptual Singularity. The class has one and only one purpose. All methods support a single, singular purpose and nothing else.

When a class is singular, it tends to be “small” simply because every line you add potentially disrupts the Conceptual Singularity of the class. A “small” class tends to have fewer methods, again, simply because every method you add increases the probability of contaminating the singular purpose. Methods tend to be short for the same reason.

Advantages

  1. Easier to test.
  2. Easier to reuse.
  3. Easier to modify.
  4. Less bugs are discovered on short methods and on short classes.
  5. Development team codes faster, because there is less need for refactoring.

Experiment

Take a relatively small class and go merciless on it. Refactor it as much as you possibly can. When you’re done, look at any class that has multiple member variables in it. Can any one of the member variables exist separately from the others? Split off that member variable into it’s own class (even it seems absurd to you). Can the methods be partitioned into methods that work on variable A and methods that work on variable B? Split the sets of methods into two classes. Can any part of the class be made more abstract? Extract out the abstract part into a new class. Continue doing this until you can’t refactor any more. Split the class up based on the functionality. When you’re done, you will have singular purposes classes. Repeat this experiment over and over again. After two years go back and take another look at your first attempt. Split the classes up even further on what you now see.

Source: c2.com

Using PHP_CodeSniffer

PHP_CodeSniffer is a library that tokenises and “sniffs” PHP code to detect violations of a defined set of coding standards. It is an essential development tool that ensures that your code remains clean and consistent. It can even help prevent some common semantic errors made by developers. Raphael Stolt did a great job porting the TooManyMethods and ExcessiveMethodLength rules to PHP_CodeSniffer. Visit his blog for more information.

Collaboration on steroids

Confluence, the world’s most widely used enterprise wiki, announced expanded integration with Microsoft Office and SharePoint that introduces Confluence to the masses. The latest release includes a host of goodies for business users looking to flex their productivity muscles and improve collaboration.

Confluence 2.9 includes a new alternative that makes editing a wiki page much simpler for everyone. Confluence users can now edit wiki pages directly from Microsoft Excel, Word or PowerPoint, via an exclusive new plugin called Office Connector.

More info: Confluence 2.9 Released

Is PHP an agile programming language?

In raising the question about whether a specific programming language is agile I want to avoid exploring what makes a language agile, or comparing PHP with other languages. The intention here is not to associate PHP to agile as a natural relationship, as much as to try and understand if we can find the ingredients in the PHP world, for creating an agile environment.

Continue reading: Is PHP an Agile Programming Language?

Loading models within modules in the Zend Framework

Modularity is an important design principle, one of its goal is to design systems that are easier to extend, understand and manage. In 2006, Zend Framework introduced a “conventional modular directory structure” that allows users to group applications into self-contained units. The problem with this is that the framework doesn’t offer any method for loading models within a module, reason why I came up with this solution.

Let’s go back in time a bit…

19 June 2007

Matthew Weier O’Phinney wrote:

We haven’t spent much time on a generic model interface. We suggest placing module specific models in a models subdirectory of your module simply for grouping purposes. Consider, for instance, if you decided to distribute a module, or wanted to restrict access in your repository for certain developers to work only on certain modules, all the code is then in one place. We don’t have any methods yet for automatically including models within a module. It’s fairly easy to do it manually:

require_once dirname(__FILE__) . '/models/MyModel.php';

03 Dec 2007

Ralph Schindler wrote:

The future of ModelLoader will be revisited once PluginLoader is fully documented.

16 Apr 2008

Bradley Holt wrote:

Zend Framework provides two primary ways in which it can be extended: either through components or modules. Components are library items either in your own namespace or in the Zend namespace. Since components are library items, there’s a fair bit of “glue” needed to get them working. Modules are ready-to-run code that can be dropped into your application that you can have up-and-running with minimal setup. If you find yourself introducing a lot of cross-module dependencies then perhaps you would be better of creating components instead and then using these components from within your modules.

I would like to have some more guidance from Zend here on best practices for writing MVC modules. If lots of people started following the same practices, we could end up with a situation where there a lot of well-written, modular applications out there that can be wired up to quickly build your application. For example, grab a wiki module and a blog module and throw them into a custom Zend Framework application and quickly have a website with all of these features integrated.

19 Jul 2008

Neil Garb wrote:

If you’re like me, you like to use different classes to represent the same model in different modules. The rationale is quite simple: by using different classes you’re encapsulating module-specific business logic within that module. For instance, a user model in an admin module may require functions related to access control, whereas the model’s counterpart in a website module might need functionality to send messages to other users.

But if you’re like me you’ve also encountered the difficulty of using classes with the same name with Zend_Loader’s registerAutoload(). The problem is that registerAutoload() uses PHP’s include path, in which path ordering is significant. This means that you can’t, in your bootstrap, just set the include path to include the model directories for each module.

Present Day

I think Bradley hit the nail on the head when he said:

If lots of people started following the same practices, we could end up with a situation where there a lot of well-written, modular applications out there that can be wired up to quickly build your application.

Exactly. I really think it’s time to create a Zend_Controller_Directory class and move all the module-specific functionality away from Zend_Controller_Front.

For example:

Zend_Controller_Directory

public function addModuleDirectory() {}
public function setDefaultModule() {}
public function getDefaultModule() {}
public function setControllersDirectoryName() {}
public function setModelsDirectoryName() {}
public function setRoutesDirectoryName() {}
...

Zend_Controller_Action

public function getModel() {}
public function getModule() {}
public function getContainer() {}
public function addDependency() {}
...

Bootstrapper

require_once 'Zend/Controller/Directory/Standard.php';
$directory = new Zend_Controller_Directory_Standard();
$directory->setControllersDirectoryName('controllers');
$directory->setModelsDirectoryName('models');
$directory->setRoutesDirectoryName('routes');
$directory->setDefaultModule('default');
$directory->addModuleDirectory('../application/modules');

require_once 'Zend/Controller/Front.php';
$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(true);
$frontController->setDirectory($directory);

Invoking models

class Blog_IndexController extends Zend_Controller_Action
{
  public function indexAction()
  {
    $model = $this->getModel('PostModel');
    $userModel = $this->getModel('UserModel', 'user');
  }
}

However, if you are only interested in loading models within modules, here’s an example of how I’m doing it.

Scalable and Flexible Directory Structure for Web Applications

Designing a modular and component-based directory structure for your Web applications can seem like an easy task. If your system is small, it may seem logical to go with the simplest design possible, but if there’s anything more time consuming and complex than developing a new directory structure design, it’s trying to redesign an existing system that wasn’t developed with growth in mind.

Consistency

To ensure that your development and build processes work effectively in a team environment, it’s essential to start with a correct directory structure that is consistent across all of your development servers. Frameworks, for example, provide a standard directory structure to organize the content in a logical way, consistent with the architecture choices: MVC pattern and project, application and module grouping.

The directory structure of the Zend Framework:

project/
  app/
    modules/
      module/
        controllers/
        models/
        views/
  cache/
  config/
  lib/
    Zend/
  public/
    index.php
  tests/

The directory structure of Symfony:

project/
  apps/
    application/
      modules/
        module/
            actions/
            config/
            lib/
            templates/
  cache/
  config/
  data/
  lib/
  log/
  plugins/
  test/
  web/
    css/
    images/
    js/
    uploads/

The directory structure of Ruby on Rails:

project/
  app/
    controller/
    helpers/
    models/
    views/
    layouts/
  components/
  config/
    environments/
  db/
  lib/
  log/
  public/
    css/
    images/
    js/
    uploads/
  script/
  test/
  vendor/

Scalability and Flexibility

A small system may very well start with a single project, but as the business requirements grow, you may find it useful to divide the system into multiple projects. If you’re creating your directory structure from scratch, you have the opportunity to maximize scalability and flexibility.

Using a directory as a container for all of the shared libraries enables greater reuse of components. If a project needs to reference a specific library create a symbolik link, for example:

libraries/
  ezComponents/
  Zend/
    1.5/
    1.5.1/
    1.5.2/
    1.6/

projectA/
  lib/
    Zend/ -> /home/libraries/Zend/1.6
  public/

projectB/
  lib/
    Zend/ -> /home/libraries/Zend/1.6
  public/

File references should be used only to reference outer-project libraries (such as the Zend Framework) that are not specific to a project. On of the advantages of doing it this way is that project references are sensitive to changes, this means that you can automatically switch from one version to another one without having to distribute files across multiple projects.

There are two main models to consider for creating projects:

1. Single application
2. Multi-application

Single Application

The single application model allows you to break up your projects to provide a greater level of isolation and control. Think about which applications you want to work on in isolation, and create separate projects accordingly.

project/
  app/
    controllers/
    models/
    views/
  lib/
    Zend/ -> /home/libraries/Zend/1.6
  public/

Or in larger systems, a modular single application model:

project/
  app/
    modules/
      module/
        controllers/
        models/
        views/
  lib/
    Zend/ -> /home/libraries/Zend/1.6
  public/

These are simpler to work with and offer a number of significant advantages over the multi-application model. For example, it allows you to work on smaller subsystems, and therefore reduces the complexity of the project and the number of dependencies.

Multi-application

In some cases, you may want to divide your project into multiple applications. For example, if you want to reduce the number of files required on each application. This allows you to work on separate applications within the inner-project boundary. A single project approach is simpler, so split a project up into multiple applications only if absolutely necessary.

project/
  apps/
    applicationA/
      modules/
    applicationB/
      modules/
  config/
  lib/
  public/

One of the disadvantages of using this model is that you are limited in the way you can break up your projects. This is because of the application dependency relationships. As a result, if you want to move a particular application to a different server, you are forced to copy all the dependent files, such as configuration files, layouts, schemas and/or specific components and libraries. Unless you have very good reasons to use a multi-application model, you should avoid this and adopt a single application model.

Naming Conventions

Ruby on Rails did a great job establishing a standard directory structure, and since then everyone has tried to conform to this structure as much as possible. For that reasons, when naming your folders you should aim for a consistent set of names, this can greatly simplify project organization. While it is possible to rename folders later on in the development cycle, you should avoid this if possible. For example:

Bad:

project/
  controllers/
  etc/
  ezComponents/
  models/
  templates/
  var/
    log/
    tmp/
  www/
  Zend/

Good:

project/
  app/
    controllers/
    models/
    views/
  config/
  lib/
    ezComponents/
    Zend/
  log/
  public/
  tmp/

Versioning

It is always good to assign unique version numbers to unique states of a project. These numbers are generally assigned in increasing order and correspond to new developments in the project.

project/ -> /home/project_version/0.3

project_version/
  0.1/
  0.2/
  0.3/
    app/
      modules/
        module/
          controllers/
          models/
          views/
    lib/
    public/

One of the advantages of doing it this way is that when a new version of the project is released, you only need to change the reference to the version number, as opposed to modifying the Web server configuration file. This speeds up the deployment process and allows you to rollback to a previous state of the project very easily.

Proposed Structure

The directory structure I use for my projects has been influenced by many frameworks, specially Rails, which defines a standard project structure. I’ve then added to this some things I’ve seen in real-world projects.

libraries/
  Zend/
    1.5.2/
    1.6/

mysite/
  build/
  migrate/
  www/ -> /home/mysite_version/0.2

mysite_version/
  0.1/
  0.2/
    app/
      cache/
      config/
      layouts/
      modules/
        module/
          controllers/
          i18n/
          models/
          properties/
          views/
      tmp/
    lib/
      Core/
      Zend/ -> /home/libraries/Zend/1.6
    public/
      index.php
    test/

Web server configuration file (never changes):

<VirtualHost *:80>
DocumentRoot /home/mysite/www/public
ServerName mysite.com
ServerAlias www.mysite.com
</VirtualHost>

More information


Frameworks vs Libraries

David Otton wrote:

Since the publication of Pragmatic’s Ruby on Rails book, the industry has fallen in love with frameworks. Because Rails wrapped up several perfectly sound techniques in one easy-to-use package, people who learnt it were, almost incidentally, learning a solid web development pattern. Add a dash of silver bullet marketing, and its no surprise many of them rushed to re-implement it in their native languages. PHP in particular has spawned a ridiculous number of variations on the theme.

Continue reading: Frameworks vs Libraries in PHP

PHP implemented in 100% Java

Quercus allows developers to incorporate Java code into PHP web applications and gives both Java and PHP developers a fast, safe, and powerful alternative to the standard PHP interpreter.

Quercus natively supports Unicode and the new Unicode syntax of the up-and-coming PHP 6, and implements a growing list of PHP extensions (i.e. APC, iconv, GD, gettext, JSON, MySQL, Oracle, PDF, Postgres, etc.). Many popular PHP applications will run as well as, if not better, than the standard PHP interpreter straight out of the box.

Quercus PHP libraries are written entirely in Java, thereby taking the advantages of Java applications and infusing them into PHP.

Benefits

Although PHP users and Java users can take advantage of Quercus immediately without modifying their application, the real benefits come from developing mixed Java/PHP applications:

  • PHP libraries written in Java are fast, safe, and relatively easy to develop, compared with C libraries. Since Java is the library language, developers won’t need to be paranoid about third-party libraries having C-memory problems or segvs.
  • PHP applications can take advantage of Java libraries and capabilities like JMS, SOA frameworks, Hibernate, or Spring. (Or EJB if you really wanted.)
  • Java application can move presentation code to PHP, leaving behind templating systems, or languages with small libraries, and taking advantage of PHP flexibility and capability.

Links

5 great articles on SPL Iterators

Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve standard problems and implements some efficient data access interfaces and classes. When PHP 5 was initially released, it included a strong sense of standardization introduced in the core package. This can be a real time saver when common programming issues must be solved through proven, standard solutions. That’s precisely the case with iterators, since the SPL package includes many predefined iterating classes that can be used for traversing different data structures, without having to reinvent the wheel over and over again.

Articles

Where is the include coming from?

The includes of the system map out the dependencies of the system, which files depend on which, which subsystem depends on which. When working with a system, it’s always useful to map out the dependencies before hand.

Here are some examples:

WordPress 2.2.1
http://wordpress.org

MediaWiki 1.12
http://www.mediawiki.org/

phpBB 3.0
http://www.phpbb.com/

phpMyAdmin 2.9.1.1
http://www.phpmyadmin.net/

Symfony 1.1
http://www.symfony-project.org/

Zend Framework 1.5.2
http://framework.zend.com/

CakePHP
http://www.cakephp.org/

CodeIgniter
http://codeigniter.com/

Seagull Framework
http://seagullproject.org/
(Demian Turner)