Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant practices on "random utility functions" [closed]

How do you all organize your random functions to improve a language's functionality outside of OOP classes (global functions)?

I've seen libraries, but I'm still not sold on this being a good solution, especially if you don't have enough functions. I'm specifically interested in how people organize random PHP and JavaScript functions.

like image 264
Matt Avatar asked Feb 07 '10 01:02

Matt


1 Answers

I try to avoid declaring functions in the global namespace altogether. The very rare occasions where I do this, is when adding userland implementations of functions that are not in my version of PHP, for instance

if(false === function_exists('lcfirst'))
{
    function lcfirst( $str ) { /* ... */}
}

Functions like this could go in a compatibility.php which would be included in a bootstrap file, so they are available throughout the application and the check to function_exists makes sure I don't run into issues once the PHP version has native support for the function.

For all other functions, I'd try to see whether they cannot go onto a dedicated object first. Usually, "random" functions are just misplaced. Have a look at which objects use your utility functions and then see whether you can move the methods there. Maybe there is a superclass waiting to come out. Also see Information Expert pattern.

If there is no objects these methods can go on, you can still group them in a static module with the name Utils in a unique namespace, so they don't clutter up the global namespace. This way, you can be sure you are not clashing with other third party functions in the global scope.

Prior to 5.3, I'd group them following the PEAR naming convention and prefixing class names following your folder structure, for example if the module was in com/mattmueller/utils.php, you'd use

class Com_MattMueller_Utils
{
     public static function something($a, $b) { /* ... */ }
}

As of PHP5.3, we've got real namespaces and you can do

namespace com\mattmueller\Utils;

class Utils
{
    public static function something($a, $b) { /* ... */ }
}

In Javascript you don't have namespaces but can easily simulate them by adding the functions to an object, e.g.

// JavaScript
var com = (com) ? com : {};
com.mattmueller = {
    'Utils': {
        'something' : function(a,b) { /* ... */ }
     }
};

The common frameworks usually implement functions for creating namespaces as well.

like image 129
Gordon Avatar answered Oct 21 '22 16:10

Gordon