Method (computer science)


Method (computer science)

In object-oriented programming, the term method refers to a subroutine that is exclusively associated either with a class (called class methods, static methods, or factory methods) or with an object (called instance methods). Like a procedure in procedural programming languages, a method usually consists of a sequence of statements to perform an action, a set of input parameters to customize those actions, and possibly an output value (called return value) of some kind. Methods can provide a mechanism for accessing (for both reading and writing) the encapsulated 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 instead associated with a class. In all typical implementations, instance methods are passed a hidden reference (e.g. this, 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 method which has no implementation. It is often used as a placeholder to be overridden 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.

An accessor method is a method that is usually small, simple and provides the means for the state 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. For example, if a bank-account class provides a getBalance() accessor method to retrieve the current balance (rather than directly accessing the balance data fields), then later revisions of the same code can implement a more complex mechanism balance retrieval (say, a database 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. Objects that provide such methods are considered mutable objects.

Many languages support methods that are called automatically upon the creation of an instance of a class, known as a Constructors. Some languages have a special syntax for constructors. In Java, C++, C#, ActionScript, and PHP 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 the constructor is called New. Object Pascal constructors are signified by the keyword constructor and can have user-defined names (but are mostly called Create). Under Objective-C 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 methods, i.e. instance methods that are called automatically upon the destruction 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 (~) in front (or __destruct in PHP 5). In Object Pascal destructors have the keyword destructor and can have user-defined names (but are mostly called Destroy). Under Objective-C the destructor method is named dealloc.

Isolation levels

Whereas a C programmer might push a value onto a stack data-structure by calling::stackPush(&myStack, value);a C++ programmer would write::myStack.push(value);

The difference is the required level of isolation. 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. 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 to the private parts of the stack implementation but this is less neat and systematic than the more cohesive and enforced isolation of the java approach.

Some recommended usages

A public method should preserve the class invariants 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, preconditions are used to constrain the method's parameters, and postconditions 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. 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.

The difference between a procedure 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.

Consequently, method calls are often modeled as a means of passing a message 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".

tatic methods

As mentioned above, a method may be declared as static (or Shared in Visual Basic .NET), 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{ public static void StaticExample() { // static method code } public void InstanceExample() { // instance method code here // can use THIS } }

/// Consumer of the above class:

// Static method is called -- no instance is involvedExampleClass.StaticExample();

// Instance method is calledExampleClass objMyExample = new ExampleClass();objMyExample.InstanceExample();

Confusingly, methods marked as class in Object Pascal also cannot refer to a class object, as can class methods in Python 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
*Inheritance semantics
*Subroutine
*Virtual inheritance
*Method name
*Idempotence


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Method (computer programming) — In object oriented programming, a method is a subroutine (or procedure or function) associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time. Methods have the special property… …   Wikipedia

  • computer science — computer scientist. the science that deals with the theory and methods of processing information in digital computers, the design of computer hardware and software, and the applications of computers. [1970 75] * * * Study of computers, their… …   Universalium

  • COMPUTER SCIENCE — The term Computer Science encompasses three different types of research areas: computability, efficiency, and methodology. General Introduction Computability deals with the question of what is mechanically computable. The most natural way to… …   Encyclopedia of Judaism

  • Object (computer science) — In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure. (With the later introduction of object oriented programming the same word,… …   Wikipedia

  • Kernel (computer science) — In computer science, the kernel is the central component of most computer operating systems (OS). Its responsibilities include managing the system s resources (the communication between hardware and software components). As a basic component of… …   Wikipedia

  • Reflection (computer science) — In computer science, reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming .In most modern computer… …   Wikipedia

  • Recursion (computer science) — Recursion in computer science is a way of thinking about and solving problems. It is, in fact, one of the central ideas of computer science. [cite book last = Epp first = Susanna title = Discrete Mathematics with Applications year=1995… …   Wikipedia

  • Abstraction (computer science) — In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization… …   Wikipedia

  • AP Computer Science — Advanced Placement Computer Science (also called APCS) is the name of two distinct Advanced Placement courses and examinations offered by the College Board to high school students as an opportunity to earn college credit for a college level… …   Wikipedia

  • Polymorphism (computer science) — This article is about the programming language theory concepts with direct application to functional programming languages. For a gentler introduction of these notions as commonly implemented in object oriented programming, see Polymorphism in… …   Wikipedia


Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”

We are using cookies for the best presentation of our site. Continuing to use this site, you agree with this.