Property (programming)
Encyclopedia
A property, in some object-oriented
Object-oriented programming
Object-oriented programming is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction,...

 programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....

s, is a special sort of class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...

 member, intermediate between a field
Field (computer science)
In computer science, data that has several parts can be divided into fields. Relational databases arrange data as sets of database records, also called rows. Each record consists of several fields; the fields of all records form the columns....

 (or data member) and a method
Method (computer science)
In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

. Properties are read and written like fields, but property reads and writes are (usually) translated to get and set method calls. The field-like syntax is said to be easier to read and write than lots of method calls, yet the interposition of method calls allows for data validation, active updating (as of GUI visuals), or read-only 'fields'. That is, properties are intermediate between member code (methods) and member data (instance variable
Instance variable
In object-oriented programming with classes, an instance variable is a variable defined in a class , for which each object of the class has a separate copy. They live in memory for the life of the object....

s) of the class, and properties provide a higher level of encapsulation
Information hiding
In computer science, information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed...

 than public field
Field (computer science)
In computer science, data that has several parts can be divided into fields. Relational databases arrange data as sets of database records, also called rows. Each record consists of several fields; the fields of all records form the columns....

s.

Support in languages

Programming languages that support properties include ActionScript 3, C#, D
D (programming language)
The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++...

, Delphi
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...

/Free Pascal
Free Pascal
Free Pascal Compiler is a free Pascal and Object Pascal compiler.In addition to its own Object Pascal dialect, Free Pascal supports, to varying degrees, the dialects of several other compilers, including those of Turbo Pascal, Delphi, and some historical Macintosh compilers...

, eC, F#, JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....

, Objective-C 2.0, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...

, Scala, Vala
Vala (programming language)
Vala is a programming language created with the goal of bringing modern language features to C, with no added runtime needs and with little overhead, by targeting the GObject object system. It is being developed by Jürg Billeter and Raffaele Sandrini. The syntax borrows heavily from C#...

, and Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...

. Some object-oriented languages, such as 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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...

, don't support properties, and require the programmer to define a pair of accessor and mutator
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...

methods instead. Oberon-2
Oberon-2
Oberon-2 is an extension of the original Oberon programming language that adds limited reflection and object-oriented programming facilities, open arrays as pointer base types, read-only field export and reintroduces the FOR loop from Modula-2....

 provides an alternative mechanism using object variable visibility flags. Other languages designed for the Java Virtual Machine
Java Virtual Machine
A Java virtual machine is a virtual machine capable of executing Java bytecode. It is the code execution component of the Java software platform. Sun Microsystems stated that there are over 4.5 billion JVM-enabled devices.-Overview:...

, such as Groovy, do natively support properties. While C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 doesn't have first class properties, they can be emulated due to operator overloading. Also note that some C++ compilers support first class properties (the Microsoft C++ compiler as an example)

In most languages, properties are implemented as a pair of accessor/mutator methods, but accessed using the same syntax as for public fields. Omitting a method from the pair yields a read-only or an uncommon write-only property.

In some languages with no built-in support for properties, a similar construct can be implemented as a single method that either returns or changes the underlying data, depending on the context of its invocation. Such techniques are used e.g. in Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...

.

Some languages (Ruby, Smalltalk) achieve property-like syntax using normal methods, sometimes with a limited amount of syntactic sugar
Syntactic sugar
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express....

.

C#


class Pen {
private int m_Color; // private field

public int Color { // public property
get
{
return m_Color;
}
set
{
m_Color = value;
}
}
}



// accessing:
Pen pen = new Pen;
// ...
pen.Color = ~pen.Color; // bitwise complement ...

// another silly example:
pen.Color += 1; // a lot clearer than "pen.set_Color(pen.get_Color + 1)"!


Recent C# versions also allow "auto-implemented properties" where the backing field for the property is generated by the compiler during compilation. This means that the property must have a setter, however it can be private.



class Shape {

public Int32 Height { get; set; }
public Int32 Width { get; private set; }

}


C++

C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...

 does not have first class properties, but there exist several ways to emulate properties to a limited degree. Two of which follow:

  1. include


template class property {
T value;
public:
T & operator = (const T &i) {
::std::cout << i << ::std::endl;
return value = i;
}
// This template class member function template serves the purpose to make
// typing more strict. Assignment to this is only possible with exact identical
// types.
template T2 & operator = (const T2 &i) {
::std::cout << "T2: " << i << ::std::endl;
T2 &guard = value;
throw guard; // Never reached.
}
operator T const & const {
return value;
}
};

struct Foo {
// Properties using unnamed classes.
class {
int value;
public:
int & operator = (const int &i) { return value = i; }
operator int const { return value; }
} alpha;

class {
float value;
public:
float & operator = (const float &f) { return value = f; }
operator float const { return value; }
} bravo;
};

struct Bar {
// Using the property<>-template.
property alpha;
property bravo;
};

int main {
Foo foo;
foo.alpha = 5;
foo.bravo = 5.132f;

Bar bar;
bar.alpha = true;
bar.bravo = true; // This line will yield a compile time error
// due to the guard template member function.
::std::cout << foo.alpha << ", "
<< foo.bravo << ", "
<< bar.alpha << ", "
<< bar.bravo
<< ::std::endl;
return 0;
}

C++, Microsoft & C++Builder-specific

An example taken from the MSDN documentation page.


// declspec_property.cpp
struct S
{
int i;
void putprop(int j)
{
i = j;
}

int getprop
{
return i;
}

__declspec(property(get = getprop, put = putprop)) int the_prop;
};

int main
{
S s;
s.the_prop = 5;
return s.the_prop;
}


D


class Pen
{
private int m_color; // private field

// public get property
public int color {
return m_color;
}

// public set property
public int color (int value) {
return m_color = value;
}
}



auto pen = new Pen;
pen.color = ~pen.color; // bitwise complement

// the set property can also be used in expressions, just like regular assignment
int theColor = (pen.color = 0xFF0000);


In D version 2, each property accessor or mutator must be marked with @property:


class Pen
{
private int m_color; // private field

// public get property
@property public int color {
return m_color;
}

// public set property
@property public int color (int value) {
return m_color = value;
}
}

Delphi/Free Pascal


type TPen = class
private
m_Color: Integer;
function Get_Color: Integer;
procedure Set_Color(RHS: Integer);
public
property Color: Integer read Get_Color write Set_Color;
end;

function TPen.Get_Color: Integer;
begin
Result := m_Color
end;

procedure TPen.Set_Color(RHS: Integer);
begin
m_Color := RHS
end;



// accessing:
var pen: TPen;
// ...
pen.Color := not pen.Color;

(*
Delphi also supports a 'direct field' syntax -

property Color: Integer read m_Color write Set_Color;

or

property Color: Integer read Get_Color write m_Color;

where the compiler generates the exact same code as for reading and writing
a field. This offers the efficiency of a field, with the safety of a property.
(You can't get a pointer to the property, and you can always replace the member
access with a method call.)

F#


type Pen = class
let mutable _color = 0

member this.Color
with get = _color
and set value = _color <- value
end


let pen = new Pen
pen.Color <- ~~~pen.Color

JavaScript


function Pen {
this._color = 0;
}
// Add the property to the Pen type itself, can also
// be set on the instance individually
Object.defineProperties(Pen.prototype, {
color: {
get: function {
return this._color;
},
set: function (value) {
this._color = value;
}
}
});


var pen = new Pen;
pen.color = ~pen.color; // bitwise complement
pen.color += 1; // Add one

Objective-C 2.0


@interface Pen : NSObject {
NSColor *color;
}
@property(copy) NSColor *color; // color values always copied.
@end

@implementation Pen
@synthesize color; // synthesize accessor methods.
@end

// Example Usage
Pen *pen = en alloc] init];
pen.color = [NSColor blackColor];
float red = pen.color.redComponent;
[pen.color drawSwatchInRect:NSMakeRect(0, 0, 100, 100)];


Note that the modern Objective-C runtime can synthesize instance variables for properties; hence, explicit declaration of instance variables is not necessary, but still possible.

PHP


class Pen {
private $_color;

function __set($property, $value) {
if ($property

'Color') {
return $this->_color = $value;
}
}

function __get($property) {
if ($property

'Color') {
return $this->_color;
}
}
}



$p = new Pen;
$p->Color = ~$p->Color; // bitwise complement
echo $p->Color;

Python

Properties only work correctly for new-style classes (classes that have object as a superclass), and are only available in Python 2.2 and newer (see the relevant section of the tutorial Unifying types and classes in Python 2.2). Python 2.6 added a new syntax involving decorators for defining properties; this only works on properties that are readable.


class Pen(object):
def __init__(self):
self._color = 0 # "private" variable

@property
def color(self):
return self._color

@color.setter
def color(self, color):
self._color = color



pen = Pen
  1. accessing:

pen.color = ~pen.color # bitwise complement ...

Ruby


class Pen
def initialize
@color = 0
end
# there is actually a shortcut for these: attr_accessor :color will
# synthetise both methods automatically, it was expanded for
# compatibility with properties actually worth writing out
def color
@color
end
def color=(value)
@color = value
end
end

pen = Pen.new
pen.color = ~pen.color

Visual Basic (.NET to 2010)


Public Class Pen

Private m_Color As Integer ' Private field

Public Property Color As Integer ' Public property
Get
Return m_Color
End Get
Set(ByVal Value As Integer)
m_Color = Value
End Set
End Property

End Class



' accessing:
Dim pen As New Pen
' ...
pen.Color = Not pen.Color

Visual Basic 6


' in a class named clsPen
Private m_Color As Long

Public Property Get Color As Long
Color = m_Color
End Property

Public Property Let Color(ByVal RHS As Long)
m_Color = RHS
End Property



' accessing:
Dim pen As New clsPen
' ...
pen.Color = Not pen.Color

See also

  • Bound property
    Bound property
    A bound property of an object is a property which transmits notification of any changes to an adapter or event handler.A simple example is the text property of a textbox control...

  • Field (computer science)
    Field (computer science)
    In computer science, data that has several parts can be divided into fields. Relational databases arrange data as sets of database records, also called rows. Each record consists of several fields; the fields of all records form the columns....

  • Indexer (programming)
    Indexer (programming)
    In programming, an indexer is in object-oriented programming a kind of smart array that enables the user to get an index of objects held within an object. It is a member of a class that enables the use it like an array...

  • Method (computer science)
    Method (computer science)
    In object-oriented programming, a method is a subroutine associated with a class. Methods define the behavior to be exhibited by instances of the associated class at program run time...

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

  • Uniform access principle
    Uniform access principle
    The Uniform Access Principle was put forth by Bertrand Meyer. It states "All services offered by a module should be available through a uniform notation, which does not betray whether they are implemented through storage or through computation." This principle applies generally to object-oriented...

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK