What's the difference between a method and a function?
Asked Answered
I

42

2163

Can someone provide a simple explanation of methods vs. functions in OOP context?

Intertwine answered 30/9, 2008 at 23:45 Comment(3)
See also subroutine vs. function, function vs. procedure, coroutines.Lucrecialucretia
It would be interesting to see another explanation outlining difference between methods and functions in r. It's interesting as method would usually contain a function. If method is an object-dependent function then function checking for object class if(class(object)) { ... } else {stop()} would be conceptually equivalent to method?Ammonium
Proper terminology can really depend on the language, so it can mean slightly different things in different contexts. Even so, since programmers who work with one language over another are more used to certain terminologies. Programmers are also influenced by their coworkers' use of the terms (whether correct or incorrect). These terms are often used interchangeably. See some of the comments below, for example.Coze
A
2230

A function is a piece of code that is called by name. It can be passed data to operate on (i.e. 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 a name that is associated with an object. In most respects it is identical to a function except for two key differences:

  1. A method is implicitly passed the object on which it was called.
  2. A method 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.)

Antlia answered 1/10, 2008 at 0:0 Comment(14)
For 1), you should also add that methods in C++ are called member functions. Thus, the difference between functions and methods in this context is analogous to the difference between functions and member functions in C++. Furthermore, languages like Java only have methods. In this case, functions would be analogous to static methods and methods would have the same meaning. For 2), you should add that a method is able to operate on the private instance (member) data declared as part of the class. Any code can access public instance data.Hypoxanthine
a function is a mathematical construct. I would say all methods are functions but not all functions are methodsBoeke
Coming from a functional programming background, I feel there is a profound distinction between function and method. Mainly methods have side effects, and that functions should be pure thus giving a rather nice property of referential transparencyGoodin
@TylerGillies and HHC, I agree it might be nice if "function" and "method" meant what you wanted them to, but your definitions do not reflect some very common uses of those terms.Roofdeck
By this definition wouldn't a static method not actually be considered a method because it doesn't have anything to do with a particular instance?Knopp
a static method is a class method, while a "normal" method (i.e a method associated with a particular object) is an instance methodSyllabi
Where did you get the criteria that 'All data that is passed to a function is explicitly passed.'? That is first clearly impossible because even constants and literals are data. But, assuming you don't mean it in that literal sense I cant find definitions of functions that assert that. Also it supports the implication that methods are not a subset of functions, which I have to agree with @TylerGillies on.Cilice
@RaffiKhatchadourian As of 2014-04, Java has functions that are not methods: docs.oracle.com/javase/tutorial/java/javaOO/…Marmoset
@AndrewEdgecombe, you wrote that functions are "called by name", by which I think you meant that they are called like this: foo(). But anonymous functions are not called in this way (they are anonymous).Marmoset
Can you cite any sources for this? Or at least give some context. I don't think this definition is universal.Anthropogenesis
Its WRONG. Any function MUST return a value, otherwise it is a procedure.Cung
A really easy test is that a function always returns the same result if called with the same parameters. A method may also involve state. This means that--for instance in Java a static call might not be a "Function" since it can deal with static variables. It also means that a non-static call might be a function: f(int x){return x*x) is a function in any context. This is the most common usage I have seen lately.Kv
From my perspective, a function is a peace of software, some subprogram/subroutine. It has a name by which it can be called, a list of parameters, and eventually a value to return. So what you name as methods are functions, but - as in C++ - member functions. Member of the class, or member of the instance of the class. There's no real reason to invent a new name for these elements of the programs. It's not intuitive, not clear, not useful, it creates some conceptual mess. I really see no reasons for inventing these terms.Knoxville
A method is a block of code which only runs when it is called. You can pass data, known as parameters, into a method. Methods are used to perform certain actions, and they are also known as functions.Deb
S
1108

A method is on an object or is static in class.
A function is independent of any object (and outside of any class).

For Java and C#, there are only methods.
For C, there are only functions.

For C++ and Python it would depend on whether or not you're in a class.
But in basic English:

  • Function: Standalone feature or functionality.
  • Method: One way of doing something, which has different approaches or methods, but related to the same aspect (aka class).
Scissor answered 30/9, 2008 at 23:51 Comment(14)
How about static methods in a class? Those would be independent of an object (in java). Wouldn't that be a function then?Garold
In Scala: function A function can be invoked with a list of arguments to produce a result. A function has a parameter list, a body, and a result type. Functions that are members of a class, trait, or singleton object are called methods. Functions defined inside other functions are called local functions. Functions with the result type of Unit are called procedures. Anonymous functions in source code are called function literals. At run time, function literals are instantiated into objects called function values. Programming in Scala Second Edition. Martin Odersky - Lex Spoon - Bill VennersHord
@Garold There is a question about that recently stackoverflow.com/questions/30402169/… The Java Language Specification just differs them as "class method"(static) and "instance method". So they're still all methods.Extrabold
@Garold static methods in Java are associated with a class, which itself is an object. As a related aside, all methods are functions. But not all functions are methods. Which is to say that this answer is technically incorrect. Because methods are a subset of functions, some functions are not independent of objects.Cilice
In JavaScript, "when a function is stored as a property of an object, we call it a method" (which means a method is not independent of an object), "When a function is not the property of an object, then it is invoked as a function"(a function is independent). These sentences quoted by double quotation marks are from the book "JavaScript: The Good Parts".Ablate
A Java method may not be on an object: it could be static.Mauramauralia
Java has lambda expressions, which are functions that are not methodsMarmoset
In Python there are methods and functions.Clyde
The distinction is often a bit academic insofar as methods can be created to do all the things that functions do. But in OO programming a method requires that only a class (or an instance of it) which includes that method may invoke that method. Functions only require a set of values (used as its parameters) and they return another set of values.Edacity
@Mauramauralia but if the function/method is static is it a function or a method? It cannot just be a function because it can directly work with private static variables of its class! But it cannot just be a method because it cannot operate on non-static data unless they are passed explicitly.Granth
@Vl4dimyr: a static method is still a method. It is called via the class. The only important difference is that it doesn’t have the instance passed to it implicitly.Rambort
In C++ there are no methods, there are member functions.Tamar
I just added an answer with Python's official documentation which defines a method and a function.Mafaldamafeking
this statement have pinned my thoughts and assumptions. it is good to see the community rates it. my knowledge confidence increased. experience dependent information is precious...Greenland
A
327

'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.

Adamok answered 30/9, 2008 at 23:48 Comment(10)
Well, ActionScript can have both methods and functions, depending on if the function is bound to an instance of a class or not (all depends on how it is defined). So, there is a difference.Transfinite
A method is a special type of function with an implicit argument passed (an instance of the class that the method is defined on). This is important as a function, in strict terms, should not use or modify anything not in its argument list.Diffusive
@Diffusive it's not always the case that methods are passed implicit arguments. In Python, the self argument is explicit. And many languages have static methods, which are not passed an instance.Marmoset
@mheiber those are some valid points. With regards to self, you are correct, it is explicitly defined. The key is that the call is implicit, based on the original object reference. There are languages that support overriding a this or self, but those constructs are then usually referred to as functions, rather than methods.Diffusive
@mheiber As far as static methods are concerned - java implemented them as a workaround so functions could be implemented without requiring a context. I would go so far as to propose that 'static method' is a misleading term and should be replaced... in an ideal theoretical world :)Diffusive
@Diffusive C++, Scala, Python, Ruby, JavaScript, and Scala all have static methods, so I don't think it's just a Java thing. I don't like them either: they amount to using objects (bundles of state) as if they were namespaces.Marmoset
@Diffusive - The "implicit argument" being passed for methods is not true in all object models. For example, in the Common Lisp Object System (CLOS), a method call looks just like a function call. Example: (method obj param1 param2) and (function obj param1 param). And a method is called a method (defined with defmethod) while a function is called a funtion (defined with defun).Toombs
The most significant difference is that a method can be overridden in a subclass, but a function cannot be overridden (though in some languages it can be shadowed). Method calls therefore are (in the general case) dynamically dispatched because a method call cannot be statically bound to a particular class's implementation of that method. A function call can generally be statically bound to the function's implementation (in languages with static binding).Serrell
Maybe that smart group of people didn't have the vocabulary at the time. Someone thought of referring to it as "method". Just like someone would have come along and thought of calling that "cart that moves on 4 wheels" a "car" and a "bigger cart that moves on 4 wheels" a "truck"Cloistered
@Diffusive Meh, maybe this is being passed implicitly in C# under the hood, but the reality is that no one thinks about it that way. this just refers to the current instance on which the method was called; it doesn't matter how it got there. That's just implementation detail and I don't think it's at all relevant to whether a function is a method or not.Vesuvianite
N
131

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 by itself.

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 fed and you could call that a function since it does not belong to any class in particular.

Naughty answered 1/10, 2008 at 0:33 Comment(0)
S
114

Simple way to remember:

  • Function → Free (Free means it can be anywhere, no need to be in an object or class)
  • Method → Member (A member of an object or class)
Shropshire answered 8/10, 2017 at 0:7 Comment(2)
since there's usually interchangeable, why do you need a mnemonic?Mantinea
@Mantinea I assume for the situations where they are not interchangeable.Marybelle
L
55

A very general definition of the main difference between a Function and a Method:

Functions are defined outside of classes, while Methods are defined inside of and part of classes.

Linnette answered 28/10, 2014 at 23:8 Comment(0)
M
38

The idea behind Object Oriented paradigm is to "treat" 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.

Mori answered 30/9, 2008 at 23:45 Comment(0)
A
23

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).

Amye answered 30/9, 2008 at 23:56 Comment(0)
M
20

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.

Meghanmeghann answered 30/9, 2008 at 23:55 Comment(1)
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).Meghanmeghann
S
18

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)

Solidus answered 30/9, 2008 at 23:52 Comment(0)
T
16

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.

Teillo answered 1/10, 2008 at 0:54 Comment(0)
S
16

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.

In "C", the word "function" means a program routine.

In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.

In C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts. If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.

Stonecrop answered 12/1, 2016 at 2:13 Comment(1)
Actually, in your example both are method... or I would call It procedure and function.Cung
B
14

Function or a method is a named callable piece of code which performs some operations and optionally returns a value.

In C language the term function is used. Java & C# people would say it a method (and a function in this case is defined within a class/object).

A C++ programmer might call it a function or sometimes method (depending on if they are writing procedural style c++ code or are doing object oriented way of C++, also a C/C++ only programmer would likely call it a function because term 'method' is less often used in C/C++ literature).

You use a function by just calling it's name like,

result = mySum(num1, num2);


You would call a method by referencing its object first like,

result = MyCalc.mySum(num1,num2);
Benjaminbenji answered 6/2, 2014 at 5:3 Comment(0)
M
13

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.

Migrant answered 3/12, 2008 at 9:47 Comment(0)
S
11

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.

Say answered 30/9, 2008 at 23:59 Comment(0)
S
10

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"
   }
}
Solidus answered 30/9, 2008 at 23:57 Comment(0)
W
10

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.)

Wold answered 1/10, 2008 at 1:20 Comment(0)
H
9

for me: the function of a method and a function is the same if I agree that:

  • a function may return a value
  • may expect parameters

Just like any piece of code you may have objects you put in and you may have an object that comes as a result. During doing that they might change the state of an object but that would not change their basic functioning for me.

There might be a definition differencing in calling functions of objects or other codes. But isn't that something for a verbal differenciations and that's why people interchange them? The mentions example of computation I would be careful with. because I hire employes to do my calculations:

new Employer().calculateSum( 8, 8 );

By doing it that way I can rely on an employer being responsible for calculations. If he wants more money I free him and let the carbage collector's function of disposing unused employees do the rest and get a new employee.

Even arguing that a method is an objects function and a function is unconnected computation will not help me. The function descriptor itself and ideally the function's documentation will tell me what it needs and what it may return. The rest, like manipulating some object's state is not really transparent to me. I do expect both functions and methods to deliver and manipulate what they claim to without needing to know in detail how they do it. Even a pure computational function might change the console's state or append to a logfile.

Huddle answered 13/4, 2012 at 9:50 Comment(0)
S
7

Let's not over complicate what should be a very simple answer. Methods and functions are the same thing. You call a function a function when it is outside of a class, and you call a function a method when it is written inside a class.

Skippet answered 14/12, 2017 at 14:3 Comment(0)
T
6

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.

Threatt answered 30/9, 2008 at 23:53 Comment(0)
A
6

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.

Alvaalvan answered 1/10, 2008 at 0:0 Comment(0)
C
6

IMHO people just wanted to invent new word for easier communication between programmers when they wanted to refer to functions inside objects.

If you are saying methods you mean functions inside the class. If you are saying functions you mean simply functions outside the class.

The truth is that both words are used to describe functions. Even if you used it wrongly nothing wrong happens. Both words describe well what you want to achieve in your code.

Function is a code that has to play a role (a function) of doing something. Method is a method to resolve the problem.

It does the same thing. It is the same thing. If you want to be super precise and go along with the convention you can call methods as the functions inside objects.

Calcicole answered 31/3, 2015 at 22:34 Comment(0)
G
5

Function is the concept mainly belonging to Procedure oriented programming where a function is an an entity which can process data and returns you value

Method is the concept of Object Oriented programming where a method is a member of a class which mostly does processing on the class members.

Glyn answered 10/11, 2015 at 14:23 Comment(0)
H
4

I am not an expert, but this is what I know:

  1. Function is C language term, it refers to a piece of code and the function name will be the identifier to use this function.

  2. Method is the OO term, typically it has a this pointer in the function parameter. You can not invoke this piece of code like C, you need to use object to invoke it.

  3. The invoke methods are also different. Here invoke meaning to find the address of this piece of code. C/C++, the linking time will use the function symbol to locate.

  4. Objecive-C is different. Invoke meaning a C function to use data structure to find the address. It means everything is known at run time.

Heckelphone answered 30/7, 2013 at 4:2 Comment(0)
K
4

TL;DR

A Function is a piece of code to run.
A Method is a Function inside an Object.

Example of a function:


function sum(){
  console.log("sum")l
}

Example of a Method:

const obj = {
a:1,
b:2,
sum(){
  }
}

So thats why we say that a "this" keyword inside a Function is not very useful unless we use it with call, apply or bind .. because call, apply, bind will call that function as a method inside object ==> basically it converts function to method

Kaffraria answered 20/12, 2019 at 7:11 Comment(0)
W
3

I know many others have already answered, but I found following is a simple, yet effective single line answer. Though it doesn't look a lot better than others answers here, but if you read it carefully, it has everything you need to know about the method vs function.

A method is a function that has a defined receiver, in OOP terms, a method is a function on an instance of an object.

Wyly answered 23/4, 2017 at 23:11 Comment(0)
S
3

A class is the collection of some data and function optionally with a constructor.

While you creating an instance (copy,replication) of that particular class the constructor initialize the class and return an object.

Now the class become object (without constructor) & Functions are known as method in the object context.

So basically

Class <==new==>Object

Function <==new==>Method

In java the it is generally told as that the constructor name same as class name but in real that constructor is like instance block and static block but with having a user define return type(i.e. Class type)

While the class can have an static block,instance block,constructor, function The object generally have only data & method.

Saccule answered 25/12, 2017 at 3:55 Comment(0)
D
3

Function - A function in an independent piece of code which includes some logic and must be called independently and are defined outside of class.

Method - A method is an independent piece of code which is called in reference to some object and are be defined inside the class.

Disable answered 17/1, 2019 at 8:35 Comment(1)
What do you call a piece of code in a static class, that is also static, is this a method or a function? A static function/method of a class does not need an object of the class it is declared in.Bouquet
K
3

In just 2 words: non-static ("instance") methods take a hidden pointer to "this" (as their 1st param) which is the object you call the method on.

That's the only difference with a regular standalone function, dynamic dispatching notwithstanding.

If you are interested, read the details below.

I'll try to be short and will use C++ as an example although what I say can be applied to virtually every language.

  • For your CPU, both functions and methods are just pieces of code. Period.
  • As such, when functions/methods are called, they can take parameters

Ok, I said there's no actual difference. Let's dig a bit deeper:

  • There are 2 flavors of methods: static and non-static
  • Static methods are like regular functions but declared inside the class that acts merely like a namespace
  • Non-static ("instance") methods take a hidden pointer to "this". That's the only difference with a regular standalone function.

Dynamic dispatching aside, it means it's as simple as that:

class User {
    public string name; // I made it public intentionally

    // Each instance method takes a hidden reference to "this"
    public void printName(/*User & this*/) {
        cout << this.name << endl;
    }
};

is equivalent to

public getName(User & user) {
    // No syntactic sugar, passing a reference explicitly
    cout << user.name << endl;
}

So, essentially, user->printName() is just syntactic sugar for getName(user).

If you don't use dynamic dispatch, that's all. If it is used, then it's a bit more involved, but the compiler will still emit what looks like a function taking this as a first parameter.

Kingcraft answered 5/3, 2020 at 11:52 Comment(1)
Great explanation. Can you add printName() being a method while getName() being a function somewhere next to the example code?Cleanlimbed
Z
3

General answer is:

method has object context (this, or class instance reference),

function has none context (null, or global, or static).

But answer to question is dependent on terminology of language you use.

  1. In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.

  2. In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.

  3. In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this and methods whith this (with object context).

  4. In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.

  5. Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.

  6. C# is very similar to Java, but has many C++ advantages.

Zen answered 30/12, 2020 at 20:21 Comment(0)
M
2

In C++, sometimes, method is used to reflect the notion of member function of a class. However, recently I found a statement in the book «The C++ Programming Language 4th Edition», on page 586 "Derived Classes"

A virtual function is sometimes called a method.

This is a little bit confusing, but he said sometimes, so it roughly makes sense, C++ creator tends to see methods as functions can be invoked on objects and can behave polymorphic.

Marismarisa answered 6/9, 2017 at 4:2 Comment(0)
P
2

Here is some explanation for method vs. function using JavaScript examples:

test(20, 50); is function define and use to run some steps or return something back that can be stored/used somewhere.

You can reuse code: Define the code once and use it many times.

You can use the same code many times with different arguments, to produce different results.

var x = myFunction(4, 3);   // Function is called, return value will end up in x

function myFunction(a, b) {
    return a * b;          // Function returns the product of a and b
}

var test = something.test(); here test() can be a method of some object or custom defined a prototype for inbuilt objects, here is more explanation:

JavaScript methods are the actions that can be performed on objects.

A JavaScript method is a property containing a function definition.

Built-in property/method for strings in javascript:

var message = "Hello world!";
var x = message.toUpperCase();
//Output: HELLO WORLD!

Custom example:

function person(firstName, lastName, age, eyeColor) {
    this.firstName = firstName;  
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.changeName = function (name) {
        this.lastName = name;
    };
}

something.changeName("SomeName"); //This will change 'something' objject's name to 'SomeName'

You can define properties for String, Array, etc as well for example

String.prototype.distance = function (char) {
    var index = this.indexOf(char);

    if (index === -1) {
        console.log(char + " does not appear in " + this);
    } else {
        console.log(char + " is " + (this.length - index) + " characters from the end of the string!");
    }
};

var something = "ThisIsSomeString"

// now use distance like this, run and check console log

something.distance("m");

Some references: Javascript Object Method, Functions, More info on prototype

Plexiglas answered 28/9, 2017 at 14:12 Comment(2)
Please don't post identical answers to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, tailor your answers to the question.Koblenz
Thank you for the feedback, I didn't tailor other answer, I deleted that anwer. :-)Plexiglas
I
2

Difference Between Methods and Functions

From reading this doc on Microsoft

Members that contain executable code are collectively known as the function members of a class. The preceding section describes methods, which are the primary kind of function members. This section describes the other kinds of function members supported by C#: constructors, properties, indexers, events, operators, and finalizers.

So methods are the subset of the functions. Every method is a function but not every function is a method, for example, a constructor can't be said as a method but it is a function.

Inconveniency answered 15/12, 2017 at 18:42 Comment(1)
Properties, indexers and events are not functions. The getters, setters (for properties and indexers), adders and removers (for events) are functions. Function members are members that are associated with one or more functions, but not necessarily by being a function.Orsino
L
2

There's a clear difference between method and funtion as:

Function is an independant piece of code which you can invoke anywhere by just mentioning it's name with given arguments, like in most of the procedural languages e.g C++ and python. While

Method is specifically associated with an object, means you can only invoke a method by mentioning it's object before it with dot(.) notation, like in specifically pure Object Oriented languages like C# and java.

Liberalism answered 15/12, 2020 at 7:13 Comment(1)
Only point I disagree: C# and Java are not pure object oriented languages. You can code quite functional in these languages. :)Cleanlimbed
M
2

What's the difference between a method and a function?

Python's official documentation defines it like this (thank you to @Kelly Bundy here!):

function

A series of statements which returns some value to a caller. It can also be passed zero or more arguments which may be used in the execution of the body. See also parameter, method, and the Function definitions section

method

A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.


A square is a rectangle, but not all rectangles are squares. The way I interpret the world, a method is a function, but not all functions are methods. What makes a method unique is that it is a special type of function which also is associated with a class and has access to class member variables.

See also:

  1. [my ans] hasattr is called a method, but it looks like a function
Mafaldamafeking answered 20/12, 2021 at 4:4 Comment(0)
G
2

A function is a set of instructions or procedures to perform a specific task. it can be used to split code into easily understandable parts, which can be invoked or reused as well.

Methods are actions that can be performed on objects. it is also known as functions stored as object properties.

Major Difference: A function doesn’t need any object and is independent, while the method is a function, which is linked with any object.

//firstName() is the function

function firstName(){
 cosole.log('John');
}

firstName() //Invoked without any object

const person = {
  firstName: "John",
  lastName: "Doe",
  id: 5566,
};

//person.name is the method
person.name = function() {
  return this.firstName + " " + this.lastName;
};

document.getElementById("demo").innerHTML =
"My father is " + person.name() //performs action on object; 

Graecoroman answered 5/11, 2022 at 10:33 Comment(0)
M
1

They're often interchangeable, but a method usually refers to a subroutine inside a class, and a function usually refers to a subroutine outside the class. for instance, in Ruby:

# function
def putSqr(a)
   puts a ** 2
end


class Math2
   # method
   def putSqr(a)
      puts a ** 2
   end
end

In Java, where everything (except package and import statements) must be inside the class, people almost always refer to them as "methods".

Mantinea answered 22/9, 2019 at 11:53 Comment(0)
S
1

A function and a method look very similar. They also have inputs and return outputs. The difference is that a method is inside of a class whereas a function is outside of a class.

Seabee answered 6/5, 2020 at 12:19 Comment(0)
P
1

A method is a member of any object or class. A function is independent.

But in the case of Javascript, function and method are interchangeable.

Problematic answered 10/8, 2021 at 17:52 Comment(0)
P
1
  • Functions are independent blocks of code that can be called independently, methods are functions associated with an object or class and used within that object or class.

  • Methods can access and modify object data with other methods in the class, while functions usually operate on their inputs and return results.

  • Methods are often used to determine the behavior of an object, while functions are used to modularize code and facilitate reusability

  • Methods are named using dot notation (object.method ()), and functions are appended with their names (functionName ()).

Primordial answered 15/6, 2023 at 5:42 Comment(0)
P
0

With the C# terminology, there’s a distinction between functions and methods. The term function member includes not only methods, but also other nondata members such as indexers, operators, constructors, destructors, and properties — all members that contain executable code.

reference => Professional C# and .NET 2021 Edition - written by Christina Nagel

Papen answered 14/9, 2021 at 5:51 Comment(0)
W
0
  • OOP is a design philosophy. In this context a "Method" is an "action", a "behaviour" of the object, an "operation", something an object does. A right click on a mouse object is an action. This action or behavior in several languages that implement OOP design is called "method".

  • "Function" is related only to procedural languages as C and Pascal and is not related with OOP philosophy, even technically the implementation is similar to method. A "function" is a block of code in a procedural language like C, that has a defined purpose, a isolated and defined functionality, that can also return a result. "Procedure" is also a function that does not return a result, but its just a technical difference.

Ways answered 17/8, 2022 at 9:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.