Chapter 5. Using objects

 

This chapter covers

  • Using a template to write methods
  • Validating method arguments and return values
  • Dealing with failure inside a method

Having instantiated an object, you’re ready to use it. Objects can offer useful behaviors: they can give you information and they can perform tasks for you. Either way, these behaviors will be implemented as object methods.

Before we discuss the design rules that are specific for either retrieving information or performing tasks, we’ll first discuss something these methods should have in common: a template for their implementation.

5.1. A template for implementing methods

Whenever you design a method, you should remember the following template.

Listing 5.1. A template for methods
[scope] function methodName(type name, ...): void|[return-type]
{
    [preconditions checks]

    [failure scenarios]

    [happy path]

    [postcondition checks]

    [return void|specific-return-type]
}

5.1.1. Precondition checks

The first step is to verify that the arguments provided by the client are correct and can be used to fulfill the task at hand. Make any number of checks, and throw exceptions when anything looks off.

Precondition checks have the following shape:

if (/* some precondition wasn't met */) {
    throw new InvalidArgumentException(/* ... */);
}

As discussed earlier, you can often use standard assertion functions for these kinds of checks.

Assertion.inArray(value, ['allowed', 'values']);

5.2. Some rules for exceptions

Summary

Answers to the exercises