Defining Pass-Through Functions on Angular Decorators

I recently got a question about some code in one of my Pluralsight courses related to Angular decorators. The question was whether or not each function on a decorated service needed to be defined even if the behavior of the function was not being modified.

For the sake of clarity and demonstration purposes, I decorated the $log service and implemented each function even though the only one whose behavior I was actually modifying was the log function.

My implementation looked like the following:

    function logDecorator($delegate, books) {

    function log(message) {
        message += ' - ' + new Date() + ' (' + books.appName + ')';
        $delegate.log(message);
    }

    function info(message) {
        $delegate.info(message);
    }

    function warn(message) {
        $delegate.warn(message);
    }

    function error(message) {
        $delegate.error(message);
    }

    function debug(message) {
        $delegate.debug(message);
    }

    return {
        log: log,
        info: info,
        warn: warn,
        error: error,
        debug: debug
    };
}

The $delegate object represents the existing $log service. Simply implementing a function just to call the corresponding function on the $delegate object is technically unnecessary. You can save yourself some typing by just assigning the function from the $delegate object to the corresponding function on the returned object. Making that change to the code above would look like the following:

    function logDecorator($delegate, books) {

    function log(message) {
        message += ' - ' + new Date() + ' (' + books.appName + ')';
        $delegate.log(message);
    }

    return {
        log: log,
        info: $delegate.info,
        warn: $delegate.warn,
        error: $delegate.error,
        debug: $delegate.debug
    };
}

It's a little more concise and the functionality is exactly the same. It's really a matter of style. I like the more concise approach for production code, but there's nothing wrong with clarity and explicitness if you prefer the more verbose form.

Author image
About Brice Wilson