views:

5956

answers:

18

I am a long-time Applescript user and new shell scripter who wants to learn a more general scripting language like Javascript or Python for performance reasons.

I am having trouble getting my head around concepts like object orientation, classes and instantiation.

If someone could point me to a pithy explanation of methods vs. functions it might help me get over the "hump". The explanations I found using google are just barely over my head.

Thanks.

A: 

A object method can be either a function (which returns a value) or a procedure (which doesn't return anything).

For example:

Public Class Object 'Declare object

    Public Function GetSomeValue() 'this is a method
     return "value"
    End Function

    Public Sub DoSomething() 'this is also a method, but it's not a function
     Response.Write("doing something")
    End Sub 

End Class
Matias Nino
+1  A: 

'method' is the object-oriented word for 'function'. That's pretty much all there is to it (ie., no real difference).

Unfortunately, I think a lot of the answers here are perpetuating or advancing the idea that there's some complex, meaningful difference.

Really - there isn't all that much to it, just different words for the same thing.

[late addition]


In fact, as Brian Neal pointed out in a comment to this question, the C++ standard never uses the term 'method' when refering to member functions. Some people may take that as an indication that C++ isn't really an object-oriented language; however, I prefer to take it as an indication that a pretty smart group of people didn't think there was a particularly strong reason to use a different term.

Michael Burr
A: 

If you are looking for a primer on OO programming, you could give this one a try (a bonus Appendix from a C# programming book). Methods and Functions are the same in C#.

dmo
+12  A: 

A method is on an object. A function is independent of an object.

For Java, there is only methods. For C, there is only functions.

For C++ it would depend on whether or not you're in a class or not.

Aaron
+1  A: 

Methods are functions of classes. In normal jargon, people interchange method and function all over. Basically you can think of them as the same thing (not sure if global functions are called methods).

http://en.wikipedia.org/wiki/Method_(computer_science)

Statement
+1  A: 

From my understanding a method is any operation which can be performed on a class. It is a general term used in programming.

In many languages methods are represented by functions and subroutines. The main distinction that most languages use for these is that functions may return a value back to the caller and a subroutine may not. However many modern languages only have functions, but these can optionally not return any value.

For example, lets say you want to describe a cat and you would like that to be able to yawn. You would create a Cat class, with a Yawn method, which would most likely be a function without any return value.

marcj
+8  A: 

Let's say a function is a block of code (usually with its own scope, and sometimes with its own closure) that may receive some arguments and may also return a result.

A method is a function that is owned by an object (in some object oriented systems, it is more correct to say it is owned by a class). Being "owned" by a object/class means that you refer to the method through the object/class; for example, in Java if you want to invoke a method "open()" owned by an object "door" you need to write "door.open()".

Usually methods also gain some extra attributes describing their behaviour within the object/class, for example: visibility (related to the object oriented concept of encapsulation) which defines from which objects (or classes) the method can be invoked.

In many object oriented languages, all "functions" belong to some object (or class) and so in these languages there are no functions that are not methods.

fd
I belabored that methods could be owned by an object or class since Javascript (which you mentioned in your question) is one of the languages that bucks the general trend of object oriented languages by having methods owned by objects and not classes (although similar structures to classes exist).
fd
+4  A: 

In OO world, the two are commonly used to mean the same thing.

From a pure Math and CS perspective, a function will always return the same result when called with the same arguments ( f(x,y) = (x + y) ). A method on the other hand, is typically associated with an instance of a class. Again though, most modern OO languages no longer use the term "function" for the most part. Many static methods can be quite like functions, as they typically have no state (not always true).

TheSoftwareJedi
+1  A: 

Methods on a class act on the instance of the class, called the object.

class Example
{
   public int data = 0; // Each instance of Example holds its internal data. This is a "field", or "member variable".

   public void UpdateData() // .. and manipulates it (This is a method by the way)
   {
      data = data + 1;
   }

   public void PrintData() // This is also a method
   {
      Console.WriteLine(data);
   }
}

class Program
{
   public static void Main()
   {
       Example exampleObject1 = new Example();
       Example exampleObject2 = new Example();

       exampleObject1.UpdateData();
       exampleObject1.UpdateData();

       exampleObject2.UpdateData();

       exampleObject1.PrintData(); // Prints "2"
       exampleObject2.PrintData(); // Prints "1"
   }
}
Statement
+1  A: 

In OO languages such as Object Pascal or C++, a "method" is a function associated with an object. So, for example, a "Dog" object might have a "bark" function and this would be considered a "Method". In contrast, the "StrLen" function stands alone (it provides the length of a string provided as an argument). It is thus just a "function." Javascript is technically Object Oriented as well but faces many limitations compared to a full-blown language like C++, C# or Pascal. Nonetheless, the distinction should still hold.

A couple of additional facts: C# is fully object oriented so you cannot create standalone "functions." In C# every function is bound to an object and is thus, technically, a "method." The kicker is that few people in C# refer to them as "methods" - they just use the term "functions" because there isn't any real distinction to be made.

Finally - just so any Pascal gurus don't jump on me here - Pascal also differentiates between "functions" (which return a value) and "procedures" which do not. C# does not make this distinction explicitly although you can, of course, choose to return a value or not.

Mark Brittingham
A: 

To a first order approximation, a method (in C++ style OO) is another word for a member function, that is a function that is part of a class.

In languages like C/C++ you can have functions which are not members of a class; you don't call a function not associated with a class a method.

Captain Segfault
+28  A: 

A function is a piece of code that is called by name. It can be passed data to operate on (ie. the parameters) and can optionally return data (the return value).

All data that is passed to a function is explicitly passed.

A method is a piece of code that is called by name that is associated with an object. In most respects it is identical to a function except for two key differences.

  1. It is implicitly passed the object for which it was called
  2. It is able to operate on data that is contained within the class (remembering that an object is an instance of a class - the class is the definition, the object is an instance of that data)

(this is a simplified explanation, ignoring issues of scope etc.)

Andrew Edgecombe
+1  A: 

If you feel like reading here is "My introduction to OO methods"

The idea behind Object Oriented paradigm is to "threat" the software is composed of .. well "objects". Objects in real world have properties, for instance if you have an Employee, the employee has a name, an employee id, a position, he belongs to a department etc. etc.

The object also know how to deal with its attributes and perform some operations on them. Let say if we want to know what an employee is doing right now we would ask him.

employe whatAreYouDoing.

That "whatAreYouDoing" is a "message" sent to the object. The object knows how to answer to that questions, it is said it has a "method" to resolve the question.

So, the way objects have to expose its behavior are called methods. Methods thus are the artifact object have to "do" something.

Other possible methods are

employee whatIsYourName
employee whatIsYourDepartmentsName

etc.

Functions in the other hand are ways a programming language has to compute some data, for instance you might have the function addValues( 8 , 8 ) that returns 16

// pseudo-code
function addValues( int x, int y )  return x + y 
// call it 
result = addValues( 8,8 )
print result // output is 16...

Since first popular programming languages ( such as fortran, c, pascal ) didn't cover the OO paradigm, they only call to these artifacts "functions".

for instance the previous function in C would be:

int addValues( int x, int y ) 
{
   return x + y;
}

It is not "natural" to say an object has a "function" to perform some action, because functions are more related to mathematical stuff while an Employee has little mathematic on it, but you can have methods that do exactly the same as functions, for instance in Java this would be the equivalent addValues function.

public static int addValues( int x, int y ) {
    return x + y;
}

Looks familiar? That´s because Java have its roots on C++ and C++ on C.

At the end is just a concept, in implementation they might look the same, but in the OO documentation these are called method.

Here´s an example of the previously Employee object in Java.

public class Employee {

    Department department;
    String name;

    public String whatsYourName(){
        return this.name;
    }
    public String whatsYourDeparmentsName(){
         return this.department.name();
    }
    public String whatAreYouDoing(){
        return "nothing";
    } 
    // Ignore the following, only set here for completness
    public Employee( String name ) {
        this.name = name;
    }

}

// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John

// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();

// Print the info to the console.

 System.out.printf("Employee %s is doing: %s", name, doingWhat );

Output:
Employee John is doing nothing.

The difference then, is on the "domain" where it is applied.

AppleScript have the idea of "natural language" matphor , that at some point OO had. For instance Smalltalk. I hope it may be reasonable easier for you to understand methods in objects after reading this.

NOTE: The code is not to be compiled, just to serve as an example. Feel free to modify the post and add Python example.

OscarRyz
Bravo! Brilliant exposition on how methods are commands to objects. This is key to understanding OO and the lack of the rhetoric you display in this answer is why OO is so abused in the industry today. Excellent post.
moffdub
+1  A: 

In general: methods are functions that belong to a class, functions can be on any other scope of the code so you could state that all methods are functions, but not all functions are methods:

Take the following python example:

class Door:
  def open(self):
    print 'hello stranger'

def knock_door:
  a_door = Door()
  Door.open(a_door)

knock_door()

The example given shows you a class called "Door" which has a method or action called "open", it is called a method because it was declared inside a class. There is another portion of code with "def" just below which defines a function, it is a function because it is not declared inside a class, this function calls the method we defined inside our class as you can see and finally the function is being called "alone".

As you can see you can call a function anywhere but if you want to call a method either you have to pass a new object of the same type as the class the method is declared (Class.method(object)) or you have to invoke the method inside the object (object.Method()), at least in python.

Think of methods as things only one entity can do, so if you have a Dog class it would make sense to have a bark function only inside that class and that would be a method, if you have also a Person class it could make sense to write a function "feed" for that doesn't belong to any class since both humans and dogs can be feed and you could call that a function since it does not belong to any class in particular.

Gustavo Rubio
+1  A: 

A function is a mathematical concept. For example:

f(x,y) = sin(x) + cos(y)

says that function f() will return the sin of the first parameter added to the cosine of the second parameter. It's just math. As it happens sin() and cos() are also functions. A function has another property: all calls to a function with the same parameters, should return the same result.

A method, on the other hand, is a function that is related to an object in an object-oriented language. It has one implicit parameter: the object being acted upon (and it's state).

So, if you have an object Z with a method g(x), you might see the following:

Z.g(x) = sin(x) + cos(Z.y)

In this case, the parameter x is passed in, the same as in the function example earlier. However, the parameter to cos() is a value that lives inside the object Z. Z and the data that lives inside it (Z.y) are implicit parameters to Z's g() method.

Bradley Mazurek
A: 

Since you mentioned Python, the following might be a useful illustration of the relationship between methods and objects in most modern object-oriented languages. In a nutshell what they call a "method" is just a function that gets passed an extra argument (as other answers have pointed out), but Python makes that more explicit than most languages.

# perfectly normal function
def hello(greetee):
  print "Hello", greetee

# generalise a bit (still a function though)
def greet(greeting, greetee):
  print greeting, greetee

# hide the greeting behind a layer of abstraction (still a function!)
def greet_with_greeter(greeter, greetee):
  print greeter.greeting, greetee

# very simple class we can pass to greet_with_greeter
class Greeter(object):
  def __init__(self, greeting):
    self.greeting = greeting

  # while we're at it, here's a method that uses self.greeting...
  def greet(self, greetee):
    print self.greeting, greetee

# save an object of class Greeter for later
hello_greeter = Greeter("Hello")

# now all of the following print the same message
hello("World")
greet("Hello", "World")
greet_with_greeter(hello_greeter, "World")
hello_greeter.greet("World")

Now compare the function greet_with_greeter and the method greet: the only difference is the name of the first parameter (in the function I called it "greeter", in the method I called it "self"). So I can use the greet method in exactly the same way as I use the greet_with_greeter function (using the "dot" syntax to get at it, since I defined it inside a class):

Greeter.greet(hello_greeter, "World")

So I've effectively turned a method into a function. Can I turn a function into a method? Well, as Python lets you mess with classes after they're defined, let's try:

Greeter.greet2 = greet_with_greeter
hello_greeter.greet2("World")

Yes, the function greet_with_greeter is now also known as the method greet2. This shows the only real difference between a method and a function: when you call a method "on" an object by calling object.method(args), the language magically turns it into method(object, args).

(OO purists might argue a method is something different from a function, and if you get into advanced Python or Ruby - or Smalltalk! - you will start to see their point. Also some languages give methods special access to bits of an object. But the main conceptual difference is still the hidden extra parameter.)

Sam Stokes
+1  A: 

Function is a set of logic that can be used to manipulate data.

While, Method is function that is used to manipulate the data of the object where it belongs. So technically, if you have a function that is not completely related to your class but was declared in the class, its not a method; It's called a bad design.

A: 

diff b/w method and function is that the method always returns a value but function may or may not return.

sachin