Sunday, November 10, 2013

Programmer Life: A Method to our Maddness

In our last installment, we learned that everything we see, whether it's in programming or life, is either an object, a property, or a method. We also explored how we use objects to describe abstract concepts so that we can write reusable code.  But objects are only the beginning of our journey.  They are pretty useless unless we can make them do something.  A car wouldn't be very valuable to you unless you could make it go forward, turn left, go backward, stop, that sort of thing.

So, today, we're going to look at the concept of methods in Object Oriented Programming.

What is a Method?

In simple terms, a method is a little chuck of code that makes something happen within an object. Almost all programming languges, including those that are not OOP based, have the concept of methods. Some of them call them functions or subroutines but the fact is that, whatever they're called, they do the same thing: do something.

How are Methods Used?

Methods are usually fairly easy to use. Let's look at our car class from last lesson with a stop_moving() method added:

public Class Car{

public  int yearMade;
public  String make;
public  String model;
public  String color;

public  bool stopMoving(){
    return true;

Car myCar = new Car();

myCar.yearMade = "2014";
myCar.make = "Ford";
myCar.model = "Fusion";
myCar.Color = "Black";

bool isCarMoving;

isCarMoving = myCar.stopMoving();

if (isCarMoving == true){
   System.out.println("The car is not moving!");
   System.out.println("The car is still moving!");

As you can see above, we've added a method to Car that makes it do something. In our simple code, all we do is return a value but, if this were real code, we'd probably send a message to the car telling to stop then returning true or false depending on if it actually stopped or not. But we're trying to keep things simple in this example so we're just going to return a value.

As you might be seeing, the idea behind classes and methods are to abstract the code from the programmer as much as possible. For example, if someone tells me how to issue the call to Car() to stop the car from moving (car.stopMoving()) then I don't have to know how the code stops the car from moving. I just need to know that it does and what values it returns so I can check if the car has stopped. It makes programming a little easier and means the programmer doesn't have to worry about the dirty implementation details.

So that's how methods work! In our next installment, we're going to build out our method a bit more using more properties and interaction to make it more useful. We'll also explore how you can pass arguments into your methods so that they can work with outside data  Be sure to check back then!