concept behavior in category cloud

appears as: behavior, behaviors, behavior
Object Storage Across the Cloud

This is an excerpt from Manning's book Object Storage Across the Cloud.

You should be seeing how adding behavior to an extensible system is a low-friction activity. It’s a joy to be able to focus almost entirely on accomplishing the desired behavior, composing pieces of the existing infrastructure to hook up the rest of the plumbing. There’s a rare moment as a developer when you might feel like the conductor of an orchestra, slowly layering the strings, woodwinds, and percussion together into a wonderful harmony. If your orchestra produces more of a cacophony from time to time, don’t get disheartened. Find the points of rigidity causing dissonance, and see how you can free yourself up, using what you’ve learned.

9.1. Introduce constructor arguments to make behavior configurable

We’ve discussed earlier how services should be created in one go, with all their dependencies and configuration values provided as constructor arguments. When it comes to changing the behavior of a service object, the constructor is again the place to be. Always prefer using a replaceable constructor argument when you want to influence the behavior of a service.

  • What is wrong with the following code?
    class Preferences
    {
        private string preferencesFilePath;
    
        public function __construct(string preferencesFilePath)
        {
            this.preferencesFilePath = preferencesFilePath;
        }
    
        public function getPreference(
            string preference,
            bool defaultValue
        ): bool {
            preferences = this.loadPreferences();
    
            if (isset(preferences[preference])) {
                return preferences[preference];
            }
    
            return defaultValue;
       }
       protected function loadPreferences(): array
       {
            return json_decode(
                file_get_contents(preferencesFilePath)
            );
        }
    }
    
    final class DatabaseTablePreferences extends Preferences
    {
        private Connection connection;
        public function __construct(Connection connection)
        {
            this.connection = connection;
        }
    
        protected function loadPreferences(): array
        {
            return this.connection.executeQuery(
                'SELECT * FROM preferences'
            ).fetchAll();
        }
    }
    1. DatabaseTablePreferences uses inheritance to change the behavior of a service.
    2. Preferences should extend DatabaseTablePreferences instead.
    3. Preferences should dispatch events to allow loading preferences from a different location.
    4. Loading the preferences should be delegated to a dedicated service with its own interface.