Are function and method the same thing?

Asked

Viewed 2,108 times

14

When we talk about methods and functions, we are talking about the same thing?

For example:

function blablabla blabla

That is a method?

2 answers

19


It is not the same thing, but almost. The functionality of both is the same. It is a difference between procedural and object-oriented paradigm terminology.

The function is an algorithm, a set of instructions that does some processing at least. In general functions produce some result (mathematically it should be obliged, but in programming there is condescension). Functions can receive arguments.

The method is the same thing with the specialization that it is within a class and usually automatically works with the state of a given object. In the background this object is passed as an argument to the function so that its data can be manipulated. The method is considered a member that has a behavior over the state of the object.

The internal mechanism in the code is identical. It is practically a syntactic sugar to make available the this in the local context.

Static methods in the background are encapsulated functions within a class, ie it is only a scope organization from where the function is.

Some languages may use specific terminology, but the concept is the same for all of them.

Read more about function: Who is who in the use of functions?

Related: What is the difference between functions and procedures?

12

The answer can be yes and not that depends on the context.

Overall method and function are terms used to identify a named code block that can be reused in various parts of the program.

More specifically they are not the same thing. Function are used in languages that use the imperative paradigm and other important feature they (most of the time) do not keep states their execution is atomic or once finished all local variables have their values 'erased' or reset.

Methods this term is most commonly used with object orientation. An object/class is nothing more than a structure that combines data (properties) with behaviors (methods) and different from a function can save state.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.