Attention to the Role Played by a Method

Is the method a command or a question?

Generally speaking, methods play one of two roles:

  • They answer a question.
  • They perform a command.

Examples of methods that are questions

If we have a user object, and users have a name, we’d ask the user object for its name by calling the name method. The user.name method returns the user’s name. Arrays know their size (the number of elements they have), so we can ask an array: [1, 2, 3].size returns 3.

Another example is the sort method on arrays. This method doesn’t actually sort the array that it’s called on. Instead, it returns a new array with the same values, but in sorted order. So, we’re essentially asking what the array would look like if it was sorted:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy