All Topics  
Method (computer science)

 

   Email Print
   Bookmark   Link






 

Method (computer science)



 
 
In object-oriented programming
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
, a method is a subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
 that is exclusively associated either with a class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 (called class methods or static methods) or with an object
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
 (called instance methods). Like a procedure in procedural programming languages, a method usually consists of a sequence of statements
Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements....
 to perform an action, a set of input parameters to customize those actions, and possibly an output value (called the return value) of some kind.






Discussion
Ask a question about 'Method (computer science)'
Start a new discussion about 'Method (computer science)'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In object-oriented programming
Object-oriented programming

Object-oriented programming is a programming paradigm that uses "Object_" and their interactions to design applications and computer programs....
, a method is a subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
 that is exclusively associated either with a class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 (called class methods or static methods) or with an object
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
 (called instance methods). Like a procedure in procedural programming languages, a method usually consists of a sequence of statements
Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements....
 to perform an action, a set of input parameters to customize those actions, and possibly an output value (called the return value) of some kind. Methods can provide a mechanism for accessing (for both reading and writing) the encapsulated
Encapsulation

Encapsulation may refer to:...
 data stored in an object or a class.

Kinds of methods

As stated above, instance methods are associated with a particular object, while class or static methods are associated with a class. In all typical implementations, instance methods are passed a hidden reference
Reference (computer science)

In computer science, a reference is an object containing information about how to locate and access the particular data item, as opposed to containing the data itself....
 (e.g. this
This (computer science)

In many object-oriented programming programming languages, this is a keyword that is used in instance methods to refer to the object on which they are working....
, self or Me) to the object (whether a class or class instance) they belong to, so that they can access the data associated with it. For class/static methods this may or may not happen according to the language; A typical example of a class method would be one that keeps count of the number of created objects within a given class.

An abstract method is a dummy code
Dummy code

In computer programming, dummy code is inserted in a Skeleton to simulate processing and avoid compiler error messages. It may involve empty subroutine declarations, or functions that return a correct result only for a simple test case where the expected response of the code is known....
 method which has no implementation
Implementation

Implementation is the realization of an application, or execution of a plan, idea, model, design, specification, Standardization, algorithm, or policy....
. It is often used as a placeholder to be overridden
Method overriding (programming)

Method overriding, in object oriented programming, is a language feature that allows a Subclass to provide a specific implementation of a method that is already provided by one of its superclass es....
 later by a subclass of or an object prototyped from the one that implements the abstract method. In this way, abstract methods help to partially specify a framework
Framework

A framework is a basic conceptual structure used to solve or address complex issues. This very broad definition has allowed the term to be used as a buzzword, especially in a software context....
.

An accessor method is a method that is usually small, simple and provides the means for the state
State

A state is a political Social contract with effective sovereignty over a geographic area and representing a population. These may be nation states, State or multinational states....
 of an object to be accessed from other parts of a program. Although it introduces a new dependency, use of the methods are preferred to directly accessing state data because they provide an abstraction layer
Abstraction layer

An abstraction layer is a way of hiding the implementation details of a particular set of functionality. Software models that use layers of abstraction include the OSI model for computer network Protocol , the OpenGL graphics drawing library, and the byte stream input/output model originated by Unix and adopted by MSDOS, Linux, and most ot...
. For example, if a bank-account class provides a getBalance accessor method to retrieve the current balance
Balance

Balance may refer to:...
 (rather than directly accessing the balance data fields), then later revision
Revision

Selfref|For the use of the term revision on Wikipedia, see...
s of the same code can implement a more complex mechanism balance retrieval (say, a database
Database

A database is a structured collection of records or data that is stored in a computer system. The structure is achieved by organizing the data according to a database model....
 fetch) without the dependent code needing to be changed. A method that changes the state of an object is no longer called an accessor method, but rather an update method, a modifier method, or a mutator method
Mutator method

In computer science, a mutator method is a method used to control changes to a variable.The mutator method, sometimes called a "setter", is most often used in object-oriented programming, in keeping with the principle of encapsulation ....
. Objects that provide such methods are considered mutable objects.

Many languages support methods, called constructor
Constructor (computer science)

In object-oriented programming, a constructor in a class is a special block of statements called when an object lifetime#Creating objects, either when it is declared or dynamically constructed on the heap-based memory allocation through the keyword ?new?....
s, that are called automatically upon the creation of an instance of a class. Some languages have a special syntax for constructors. In Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
, C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
, C#, ActionScript
ActionScript

ActionScript is a scripting language based on ECMAScript. ActionScript is used primarily for the development of websites and software using the Adobe Flash Player platform , but is also used in some database applications , and in basic robotics, as with the Make Controller Kit....
, and PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
 they have the same name as the class of which they are a member (PHP 5 also allows __construct as a constructor); in Visual Basic .NET
Visual Basic .NET

Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework....
 the constructor is called New. Object Pascal
Object Pascal

Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
 constructors are signified by the keyword constructor and can have user-defined names (but are mostly called Create). Under Objective-C
Objective-C

Objective-C is a Reflection , Object-oriented programming programming language which adds Smalltalk-style message passing to C .Today it is used primarily on Mac OS X, iPhone OS, and GNUstep, three environments based on the OpenStep standard, and is the primary language used for the NEXTSTEP, OpenStep#OPENSTEP, and Cocoa application framew...
 the constructor method is split between two methods, alloc and init, with the alloc method setting aside memory for an instance of the class and the init method handling the bulk of initializing the instance; a call to the new method invokes both the alloc and the init method for the class instance.

Likewise, some languages have special destructor
Destructor (computer science)

In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the Resource which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process....
 methods, i.e. instance methods that are called automatically upon the destruction
Object lifetime

In computer science, the object lifetime of an object in object-oriented programming is the time between an object's creation till the object is no longer used, and is destructed or freed....
 of an instance of a class. In C++, they are distinguished by having the same name as the class of the object they're associated with, but with the addition of a tilde
Tilde

The tilde is a grapheme with several uses. The name of the character comes from Spanish language, from the Latin wikt:titulus meaning a title or superscription, though the term ?tilde? has evolved in that language and now has a different meaning in Linguistics....
 (~) in front (or __destruct in PHP 5). In Object Pascal
Object Pascal

Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
 destructors have the keyword destructor and can have user-defined names (but are mostly called Destroy). Under Objective-C
Objective-C

Objective-C is a Reflection , Object-oriented programming programming language which adds Smalltalk-style message passing to C .Today it is used primarily on Mac OS X, iPhone OS, and GNUstep, three environments based on the OpenStep standard, and is the primary language used for the NEXTSTEP, OpenStep#OPENSTEP, and Cocoa application framew...
 the destructor method is named dealloc.

Isolation levels

Whereas a C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
 programmer
Programmer

A programmer is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software....
 might push a value onto a stack
Stack (data structure)

In computer science, a stack is an abstract data type and data structure based on the principle of LIFO . Stacks are used extensively at every level of a modern computer system....
 data-structure by calling:
stackPush(&myStack, value);
a C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
 programmer would write:
myStack.push(value);


The difference is the required level of isolation
Isolation (computer science)

In database systems, isolation is a property that defines how/when the changes made by one operation become visible to other concurrent operations....
. In C, the stackPush procedure could be in the same source file as the rest of the program and if it was, any other pieces of the program in that source file could see and modify all of the low level details of how the stack was implemented, completely bypassing the intended interface
Interface (computer science)

Interface generally refers to an Abstraction_%28computer_science%29 that an entity provides of itself to the outside. This separates the methods of external communication from internal operation, and allows it to be internally modified without affecting the way outside entities interact with it, as well as provide Polymorphism in object-orien...
. In C++, regardless of where the class is placed, only the methods which are part of myStack will be able to get access to those low-level details without going through the formal interface methods. Languages such as C can provide comparable levels of protection by using different source files and not providing external linkage
Linker

In computer science, a linker or link editor is a computer program that takes one ormore object file generated by a compiler and combines them into a single executable program....
 to the private parts of the stack implementation.

Some recommended usages


A public method should preserve the class invariant
Class invariant

In computer programming, a class invariant is an invariant used to constrain object s of a class . Method s of the class should preserve the invariant....
s of the object it is associated with, and should always assume that they are valid when it commences execution (private methods do not necessarily need to follow this recommendation). To this effect, precondition
Precondition

In computer programming, a precondition is a condition or Predicate that must always be true just prior to the execution of some section of code or before an operation in a formal specification....
s are used to constrain the method's parameters, and postcondition
Postcondition

In computer programming, a postcondition is a condition or Predicate that must always be true just after the execution of some section of code or after an operation in a formal specification....
s to constrain method's output, if it has one. If any one of either the preconditions or postconditions is not met, a method may raise an exception
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
. If the object's state does not satisfy its class invariants on entry to or exit from any method, the program is considered to have a bug
Software bug

A software bug is an error, flaw, mistake, failure, or fault in a computer program that prevents it from behaving as intended . Most bugs arise from mistakes and errors made by people in either a program's source code or its software architecture, and a few are caused by compilers producing incorrect code....
.

The difference between a procedure
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
 and a method is that the latter, being associated with a particular object, may access or modify the data private to that object in a way consistent with the intended behavior of the object. Consequently, rather than thinking "a method is just a sequence of commands", a programmer using an object-oriented language will consider a method to be "an object's way of providing a service" (its "method of doing the job", hence the name); a method call is thus considered to be a request to an object to perform some task
Task

In common language, a task is part of a set of actions which accomplish a job, problem or assignment. Task is a synonym for activity although the latter carries a connotation of being possibly longer duration....
.

Consequently, method calls are often modeled as a means of passing a message
Message passing

Message passing in computer science, is a form of communication used in parallel computing, object-oriented programming, and interprocess communication....
 to an object. Rather than directly performing an operation on an object, a message (most of the time accompanied by parameters) is sent to the object telling it what it should do. The object either complies or raises an exception describing why it cannot do so. Applied to our stack example, rather than pushing a value onto the stack, a value is sent to the stack, along with the message "push".

Static methods

As mentioned above, a method may be declared as static, meaning that it acts at the class level rather than at the instance level. Therefore, a static method cannot refer to a specific instance of the class (i.e. it cannot refer to this, self, Me, etc.), unless such references are made through a parameter referencing an instance of the class, although in such cases they must be accessed through the parameter's identifier instead of this. An example of a static member and its consumption in C# code:

public class ExampleClass

/// Consumer of the above class:

// Static method is called -- no instance is involved ExampleClass.StaticExample;

// Instance method is called ExampleClass objMyExample = new ExampleClass; objMyExample.InstanceExample;

Confusingly, methods marked as class in Object Pascal
Object Pascal

Object Pascal refers to a branch of Object-oriented programming derivatives of Pascal , mostly known as the primary programming language of CodeGear Delphi....
 also cannot refer to a class object, as can class methods in Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
 or Smalltalk. For example, this Python method can create an instance of Dict or of any subclass of it, because it receives a reference to a class object as cls:

class Dict: @classmethod def fromkeys(cls, iterable, value=None): d = cls for key in iterable: d[key] = value return d

See also

  • Implementation inheritance
    Implementation inheritance

    In programming, Implementation inheritance is the inheritance of the full functionality of a Class , as opposed to the inheritance of an interface , which simply defines the methods that must be present....
  • Inheritance semantics
    Inheritance semantics

    Inheritance semantics is an important concept in object-oriented programming....
  • Subroutine
    Subroutine

    In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
  • Virtual inheritance
    Virtual inheritance

    In the C++ programming language, virtual inheritance is a kind of Inheritance that solves some of the problems caused by multiple inheritance by clarifying ambiguity over which ancestor class members to use....
  • Method name
    Method name

    A method name in object-oriented programming is an identifier not only uniquely identifying a subroutine or event handler, but more importantly providing a hint to the programmer about what the method can be expected to do....
  • Idempotence
    Idempotence

    Idempotence describes the property of operations in mathematics and computer science which means that multiple applications of the operation does not change the result....