Thought Process Behind Writing a New Method
Break the task of writing a new method into smaller steps.
We'll cover the following
As programmers, we like to split our tasks up and do one thing after another. This allows us to focus on a tiny task, and once we’ve solved it, we move on to the next one.
When we need to add some new functionality to our program, we’ll constantly need to add methods because they are what add behavior.
Method name
The first thing we should ask is what the method should do. The answer to this gives us a hint for a good method name.
Let’s say we’re working on an application that deals with emails, and we’re specifically trying to format an email. Our method name can be format_email
.
With this first task solved, knowing the method name, we can already go ahead and write down the method definition:
def format_emailend
While this is a useless method because it does nothing at all, it’s already a valid method. That’s good progress already; we’ve made the first step.
Parameters lists
The next thing we ask ourselves is if the method needs to be given any information to perform its function. The answer to this question specifies the method’s parameters list.
In our example, the answer is probably that it needs the email in order to format it.
So, we can add the parameters list to the method:
def format_email(email)end
With these two things solved, we can now start thinking about implementing the method body. How can we transform the email into some formatted text?
We’d add a new line between def
and end
and ensure it’s indented by two spaces. We’ll then focus on the code that makes up the method body:
def format_email(email)
#...
end