java coding adventure

Inside the hut: methods

What are Methods?

As I wrote in previous chapter methods do things.

The method is a piece of code that has a name and can be used in various places of your program.

After method finishes its task it can return a result.

Let’s take a look at the well-known method add:

methodDescription.png

The method above does the addition.

To do its task, the method needs two summands: we call them method arguments. A method can have many arguments. Or it can have none. Depends on what do you need to do.

A method takes the arguments, processes them and then returns a value or an object.

The code above can also look like this:

public in add(int summand1, int summand2){
    int sum = summand1 + summand2;
return sum;
}

The best is to Keep It Short & Simple (one of the programming good practices: KISS, known also as Keep It Simple, Stupid), so I chose the first approach instead.

How to use a method?

In CalculatorTest.java there is a code to @Test add method:

public class CalculatorTest {public class CalculatorTest {
@Test
public void sum() {
Calculator calculator = new Calculator();
Assert.assertEquals(3, calculator.add(1, 2));
}

First you create a calculator:

Calculator calculator = new Calculator();

Then in a test you use this calculator to do the addition:

calculator.add(1, 2)

The rest around it is to keep a test running so let’s skip the details for now.

Advertisements

2 thoughts on “Inside the hut: methods”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s