CSC/ECE 517 Fall 2011/ch1 1h ps: Difference between revisions
No edit summary |
No edit summary |
||
(42 intermediate revisions by 2 users not shown) | |||
Line 4: | Line 4: | ||
== Introduction == | == Introduction == | ||
<p>The purpose of [http://en.wikipedia.org/wiki/Object-oriented_programming/ Object Oriented Programming] is to make programs model things the way people think or deal with the world i.e it's modeled around data rather than logic. | <p>The purpose of [http://en.wikipedia.org/wiki/Object-oriented_programming/ Object Oriented Programming] is to make programs model things the way people think or deal with the world i.e it's modeled around data rather than logic. An object-oriented program may be viewed as a collection of interacting [http://en.wikipedia.org/wiki/Object_(computer_science)/ objects], as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent "machine" with a distinct role or responsibility. The actions (or "methods") on these objects are closely associated with the object. </p> | ||
<p>Objects form the basis of OOP. Every Object wraps the data within a set of functions which helps to handle different appropriately. Let us now look at objects, their manipulation and the ways to do so.</p> | |||
== Objects - Attributes and Methods == | == Objects - Attributes and Methods == | ||
Line 11: | Line 12: | ||
<tr> | <tr> | ||
<td> | <td> | ||
<p>Similar to real world objects, software objects also consist of state and related behavior. An object stores it's state in <i>attributes</i> and exposes its behavior through <i>methods</i>. Let's look at the pseudo code for a bicycle object.</p> | <p>Similar to real world objects, software objects also consist of state and related behavior. An object stores it's state in <i>[http://en.wikipedia.org/wiki/Attribute_(computing)/ attributes]</i> and exposes its behavior through <i>[http://en.wikipedia.org/wiki/Method_(computer_programming)/ methods]</i>. Let's look at the pseudo code for a bicycle object.</p> | ||
<pre> | <pre> | ||
CLASS Bicycle | CLASS Bicycle | ||
Line 65: | Line 66: | ||
As seen above, a method is always called using parenthesis, within which arguments may be included if required. However, instance variable is accessed directly. | As seen above, a method is always called using parenthesis, within which arguments may be included if required. However, instance variable is accessed directly. | ||
== Getters and Setters and their Advantages == | |||
<p>One of the principles of Objected Oriented Design is that an object's implementation should not be exposed to other classes. This is to avoid difficulty in maintenance. [http://en.wikipedia.org/wiki/Mutator_method/ Getters and Setters] provide a way to read or write private data of a class for any kind of manipulation. They also provide for easy maintenance, in that, if any change needs to be made in the way the variable is set, only the setter method needs to be changed rather than looking for it and changing in every place. These methods also improve the code readability and bring about uniformity across the code.</p> | |||
== Comparison of syntax between various Programming Languages == | == Comparison of syntax between various Programming Languages == | ||
<p>The usage syntax of methods, instance variables, getters and setters is in the table below</p> | |||
<table border = 1> | |||
{|class="wikitable" | |||
|- | |||
!Programming Languages | |||
!Method call | |||
!Fields/Attributes | |||
!Getter / Setter | |||
!Comparison | |||
|- | |||
|ABAP (Advanced Business Application Programming) | |||
|<pre> | |||
CALL METHOD <meth> EXPORTING... <ii> =.<f i>... | |||
IMPORTING... <ei> =.<g i>... | |||
CHANGING ... <ci> =.<f i>... | |||
RECEIVING r = h | |||
EXCEPTIONS... <ei> = rc i... | |||
</pre> | |||
|<b>data</b> field <b>type</b> type | |||
|Same as other methods with the only difference that they start with SET or GET | |||
|Syntax is different for method calls and instance-variable reference | |||
|- | |||
|C++ | |||
|ObjectName.MethodName(parameters) | |||
|Same as methods. Example below: | |||
<pre> | |||
int getHealth() const { return health; } | |||
void setHealth(int h) { health = h; } | |||
</pre> | |||
|Different syntax is used to call methods and instance-variable references | |||
|- | |||
|C# | |||
|ObjectName.MethodName(parameters) | |||
|ObjectName.Attribute | |||
|They are just like methods. Example below: | |||
<pre> | |||
public string GetName() | |||
{ | |||
return m_name; | |||
} | |||
public void SetName(string name) | |||
{ | |||
m_name = name; | |||
} | |||
</pre> | |||
|Different syntax is used to call methods and instance-variable references | |||
|- | |||
|Java | |||
|ObjectName.MethodName(parameters) [Eg: x.method()] | |||
|ObjectName.Attribute [Eg: x.field] | |||
|They are nothing but method calls | |||
|Different syntax is used to call methods and instance-variable references | |||
|- | |||
|D | |||
|ObjectName.MethodName(parameters) | |||
|ObjectName.Attribute | |||
|No need for getters and setters. It can be directly accessed. | |||
<pre> | |||
import std.stdio; | |||
class Car | |||
{ | |||
float speed = 1.0; | |||
} | |||
void main(){ | |||
auto my_car = new Car(); | |||
my_car.speed = 2.5; | |||
writefln(my_car.speed); | |||
} | |||
</pre> | |||
|Syntax used for method calls and variable references is different | |||
|- | |||
|Objective C | |||
|output = [object methodWithOutput] | |||
|ObjectName->Attribute | |||
|An example of getter is below | |||
<pre> | |||
#import <Cocoa/Cocoa.h> | |||
@interface Photo : NSObject { | |||
NSString* caption; | |||
NSString* photographer; | |||
} | |||
- (NSString*) caption; | |||
- (NSString*) photographer; | |||
@end | |||
</pre> | |||
An example of setter is below | |||
<pre> | |||
#import <Cocoa/Cocoa.h> | |||
@interface Photo : NSObject { | |||
NSString* caption; | |||
NSString* photographer; | |||
} | |||
- (NSString*) caption; | |||
- (NSString*) photographer; | |||
- (void) setCaption: (NSString*)input; | |||
- (void) setPhotographer: (NSString*)input; | |||
@end | |||
</pre> | |||
|Syntax used for method calls and variable references is different | |||
|- | |||
|Python | |||
|ObjectName.MethodName(parameters) | |||
|ObjectName.Attribute | |||
|Pythonic way of implementing getters and setters is to using public members and turning them into properties when needed | |||
|Syntax used for method calls and variable references is sometimes the same and different at times (when there are arguments) | |||
|- | |||
|Javascript | |||
|ObjectName.MethodName(Parameters); | |||
|ObjectName.Attribute | |||
|<pre> | |||
var lost = { | |||
loc : "Island", | |||
get location () { | |||
return this.loc; | |||
}, | |||
set location(val) { | |||
this.loc = val; | |||
} | |||
}; | |||
lost.location = "Another island"; | |||
</pre> | |||
|Syntax is different for method calls and instance-variable reference | |||
|- | |||
|PHP | |||
|$ObjectName->MethodName(Parameters); | |||
|$ObjectName->Attribute | |||
|N/A. Attributes can be accessed directly. | |||
|Syntax is different for method calls and instance-variable reference | |||
|- | |||
|VB.NET | |||
|ObjectName.MethodName(Parameters); | |||
ObjectNmae.MethodName | |||
|ObjectName.Attribute | |||
|<pre> | |||
Public Property myProperty As String | |||
Get | |||
Return String.Empty | |||
End Get | |||
Private Set(ByVal value As String) | |||
somethingElse = value | |||
End Set | |||
End Property | |||
</pre> | |||
|Syntax may be same for method calls and instance-variable reference | |||
|- | |||
|Ruby | |||
|$ObjectName->MethodName(Parameters); | |||
|$ObjectName->Attribute | |||
|<pre> | |||
class Message | |||
attr_reader :message | |||
def message=(m) | |||
@message = m.dup | |||
end | |||
end | |||
class Message | |||
attr_writer :message | |||
def message | |||
@message.encode!("UTF-8") | |||
end | |||
end | |||
</pre> | |||
|Syntax is same for method calls and instance-variable reference | |||
|- | |||
|Lua | |||
|ObjectName.MethodName(Parameters); | |||
|ObjectName.Attribute | |||
|<pre> | |||
local index = getters and | |||
function(self, key) | |||
-- read from getter, else from fallback | |||
local func = getters[key] | |||
if func then return func(self) else return fallback[key] end | |||
end | |||
or fallback -- default to fast property reads through table | |||
local newindex = setters and | |||
function(self, key, value) | |||
-- write to setter, else to proxy | |||
local func = setters[key] | |||
if func then func(self, value) | |||
else rawset(self, key, value) end | |||
end | |||
</pre> | |||
|Syntax is different for method calls and instance-variable reference | |||
|- | |||
|Perl | |||
|$ObjectName->MethodName(Parameters); | |||
|$ObjectName->Attribute | |||
|<pre> | |||
BEGIN { | |||
my @attr = qw(author title number); | |||
no strict 'refs'; | |||
for my $a (@attr){ | |||
*{__PACKAGE__ . "::get_$a"} = sub { $_[0]->{$a} }; | |||
*{__PACKAGE__ . "::set_$a"} = sub { $_[0]->{$a} = $_[1] }; | |||
} | |||
} | |||
</pre> | |||
|Syntax is different for method calls and instance-variable reference | |||
|} | |||
</table> | |||
== Conclusion == | |||
<p> | |||
Having getters and setters in the implementation has its own advantages and disadvantages. The advantages are that | |||
<ol> | |||
<li>They provide [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)/ data encapsulation].</li> | |||
<li>They improve the code readability.</li> | |||
<li>Changes can be made only to the implementation without making changes to the code that uses the object.</li> | |||
</ol> | |||
Using getters and setters also has a disadvantage. They largely provide access to implementation details. But this could hinder <i>[http://en.wikipedia.org/wiki/Abstraction_(computer_science)/ data abstraction</i>, i.e. hiding the object's implementation of a message handler. Consider a getter function that returns a number. Wherever this method is called, the variable which holds the return value must match the return type of this function. Now if we change they way this method is implemented by changing the return type, then there could be trouble. | |||
</p> | |||
<p>Therefore it is important to design such that there is minimal data movement thereby minimizing possible errors.</p> | |||
<p>Using the same syntax for method calls and instance variable references have some advantages and disadvantages. One could argue that having the same syntax makes it simpler for the programmer. It makes the code lighter in terms of lines of code, thus avoiding bulky code. However, including distinct ways for using methods and variables enhances readability by enabling better understanding. This is possible because the manipulation is visible whereas if the syntax were the same(i.e. compact), the one reading has no idea about what is happening "under the hood".</p> | |||
== References == | |||
<ol> | |||
<li>[http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(object-oriented_programming)/ Comparison of Programming Languages]</li> | |||
<li>[http://forums.sdn.sap.com/thread.jspa?threadID=529448&tstart=6135/ Setters and Getters in ABAP]</li> | |||
<li>[http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?page=1/ Why getters and setters are evil?]</li> | |||
<li>[http://www.zeuscmd.com/tutorials/cplusplus/50-GettersAndSetters.php/ Getters and Setters]</li> | |||
<li>[http://cocoadevcentral.com/d/learn_objectivec/ Objective C]</li> | |||
<li>[http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html/ Ruby Classes- Objects]</li> | |||
<li>[http://www.vbtutor.in/getting-started-with-visual-basic-net/object-oriented-programming-in-vbnet/ VB.Net Object oriented programming]</li> | |||
<li>[https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript/ Javascript - Functions/Objects]</li> | |||
<li>[http://www.massassi.com/php/articles/classes/ PHP - Objects]</li> | |||
<li>[http://www.tutorialspoint.com/perl/perl_oo_perl.htm/ Perl - Objects]</li> | |||
</ol> |
Latest revision as of 02:52, 26 September 2011
Common Attribute/Member Syntax
Different object oriented programming languages include different ways of accessing the member variables and methods. This page discusses the various usages and their advantages and disadvantages.
Introduction
The purpose of Object Oriented Programming is to make programs model things the way people think or deal with the world i.e it's modeled around data rather than logic. An object-oriented program may be viewed as a collection of interacting objects, as opposed to the conventional model, in which a program is seen as a list of tasks (subroutines) to perform. In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects. Each object can be viewed as an independent "machine" with a distinct role or responsibility. The actions (or "methods") on these objects are closely associated with the object.
Objects form the basis of OOP. Every Object wraps the data within a set of functions which helps to handle different appropriately. Let us now look at objects, their manipulation and the ways to do so.
Objects - Attributes and Methods
Similar to real world objects, software objects also consist of state and related behavior. An object stores it's state in attributes and exposes its behavior through methods. Let's look at the pseudo code for a bicycle object. CLASS Bicycle ATTRIBUTES: speed: NUMBER gear: NUMBER pedal_cadence: NUMBER METHODS: ride(speed) changeGear(gear) changeCadence(pedal_cadence) |
In the above pseudo code, the attributes define the object and the methods provide a way of achieving the desired functionality from that object. The methods use the attributes to manipulate the object and achieve the functionality. From this we can observe that this manipulation is the very essence of programming using objects. Therefore the access of attributes and way of defining method calls very important in OOP.
Method call / Instance Variable reference Syntax
A running debate in O-O languages is whether method calls and instance-variable references should have the same syntax. Different programming languages implement this in different ways. Let's look at them by examples.
Same Syntax
Languages like Ruby use the same syntax for method calls and variable references. There is no distinction between these. We can see this in the example below:
class Song def duration=(newDuration) @duration = newDuration end end aSong = Song.new("Bicylops", "Fleck", 260) aSong.duration » 260 aSong.duration = 257 # set attribute with updated value aSong.duration » 257
This makes it simpler for the programmer to code. Also, it presents uniformity in the code.
Differing Syntax
Languages like Java employ different syntax for method calls and variable references as seen in this example below:
class Song{ int duration; Song(){} void setDuration(int dur){ duration = dur; } } Song sng = new Song(); sng.setDuration(260); System.out.println("Song duration = "+sng.duration);
As seen above, a method is always called using parenthesis, within which arguments may be included if required. However, instance variable is accessed directly.
Getters and Setters and their Advantages
One of the principles of Objected Oriented Design is that an object's implementation should not be exposed to other classes. This is to avoid difficulty in maintenance. Getters and Setters provide a way to read or write private data of a class for any kind of manipulation. They also provide for easy maintenance, in that, if any change needs to be made in the way the variable is set, only the setter method needs to be changed rather than looking for it and changing in every place. These methods also improve the code readability and bring about uniformity across the code.
Comparison of syntax between various Programming Languages
The usage syntax of methods, instance variables, getters and setters is in the table below
Programming Languages | Method call | Fields/Attributes | Getter / Setter | Comparison |
---|---|---|---|---|
ABAP (Advanced Business Application Programming) | CALL METHOD <meth> EXPORTING... <ii> =.<f i>... IMPORTING... <ei> =.<g i>... CHANGING ... <ci> =.<f i>... RECEIVING r = h EXCEPTIONS... <ei> = rc i... |
data field type type | Same as other methods with the only difference that they start with SET or GET | Syntax is different for method calls and instance-variable reference |
C++ | ObjectName.MethodName(parameters) | Same as methods. Example below:
int getHealth() const { return health; } void setHealth(int h) { health = h; } |
Different syntax is used to call methods and instance-variable references | |
C# | ObjectName.MethodName(parameters) | ObjectName.Attribute | They are just like methods. Example below:
public string GetName() { return m_name; } public void SetName(string name) { m_name = name; } |
Different syntax is used to call methods and instance-variable references |
Java | ObjectName.MethodName(parameters) [Eg: x.method()] | ObjectName.Attribute [Eg: x.field] | They are nothing but method calls | Different syntax is used to call methods and instance-variable references |
D | ObjectName.MethodName(parameters) | ObjectName.Attribute | No need for getters and setters. It can be directly accessed.
import std.stdio; class Car { float speed = 1.0; } void main(){ auto my_car = new Car(); my_car.speed = 2.5; writefln(my_car.speed); } |
Syntax used for method calls and variable references is different |
Objective C | output = [object methodWithOutput] | ObjectName->Attribute | An example of getter is below
#import <Cocoa/Cocoa.h> @interface Photo : NSObject { NSString* caption; NSString* photographer; } - (NSString*) caption; - (NSString*) photographer; @end An example of setter is below #import <Cocoa/Cocoa.h> @interface Photo : NSObject { NSString* caption; NSString* photographer; } - (NSString*) caption; - (NSString*) photographer; - (void) setCaption: (NSString*)input; - (void) setPhotographer: (NSString*)input; @end |
Syntax used for method calls and variable references is different |
Python | ObjectName.MethodName(parameters) | ObjectName.Attribute | Pythonic way of implementing getters and setters is to using public members and turning them into properties when needed | Syntax used for method calls and variable references is sometimes the same and different at times (when there are arguments) |
Javascript | ObjectName.MethodName(Parameters); | ObjectName.Attribute | var lost = { loc : "Island", get location () { return this.loc; }, set location(val) { this.loc = val; } }; lost.location = "Another island"; |
Syntax is different for method calls and instance-variable reference |
PHP | $ObjectName->MethodName(Parameters); | $ObjectName->Attribute | N/A. Attributes can be accessed directly. | Syntax is different for method calls and instance-variable reference |
VB.NET | ObjectName.MethodName(Parameters);
ObjectNmae.MethodName |
ObjectName.Attribute | Public Property myProperty As String Get Return String.Empty End Get Private Set(ByVal value As String) somethingElse = value End Set End Property |
Syntax may be same for method calls and instance-variable reference |
Ruby | $ObjectName->MethodName(Parameters); | $ObjectName->Attribute | class Message attr_reader :message def message=(m) @message = m.dup end end class Message attr_writer :message def message @message.encode!("UTF-8") end end |
Syntax is same for method calls and instance-variable reference |
Lua | ObjectName.MethodName(Parameters); | ObjectName.Attribute | local index = getters and function(self, key) -- read from getter, else from fallback local func = getters[key] if func then return func(self) else return fallback[key] end end or fallback -- default to fast property reads through table local newindex = setters and function(self, key, value) -- write to setter, else to proxy local func = setters[key] if func then func(self, value) else rawset(self, key, value) end end |
Syntax is different for method calls and instance-variable reference |
Perl | $ObjectName->MethodName(Parameters); | $ObjectName->Attribute | BEGIN { my @attr = qw(author title number); no strict 'refs'; for my $a (@attr){ *{__PACKAGE__ . "::get_$a"} = sub { $_[0]->{$a} }; *{__PACKAGE__ . "::set_$a"} = sub { $_[0]->{$a} = $_[1] }; } } |
Syntax is different for method calls and instance-variable reference |
Conclusion
Having getters and setters in the implementation has its own advantages and disadvantages. The advantages are that
- They provide data encapsulation.
- They improve the code readability.
- Changes can be made only to the implementation without making changes to the code that uses the object.
Using getters and setters also has a disadvantage. They largely provide access to implementation details. But this could hinder [http://en.wikipedia.org/wiki/Abstraction_(computer_science)/ data abstraction, i.e. hiding the object's implementation of a message handler. Consider a getter function that returns a number. Wherever this method is called, the variable which holds the return value must match the return type of this function. Now if we change they way this method is implemented by changing the return type, then there could be trouble.
Therefore it is important to design such that there is minimal data movement thereby minimizing possible errors.
Using the same syntax for method calls and instance variable references have some advantages and disadvantages. One could argue that having the same syntax makes it simpler for the programmer. It makes the code lighter in terms of lines of code, thus avoiding bulky code. However, including distinct ways for using methods and variables enhances readability by enabling better understanding. This is possible because the manipulation is visible whereas if the syntax were the same(i.e. compact), the one reading has no idea about what is happening "under the hood".