Core S2 Software Solutions

Setters and getters in the world of OOP

Older article from Voxel Entertainment; originally written by Jeremy Bridon.

Object Oriented Programming, or OOP, usually requires a system of “getters” and “setters” to access an object’s properties. Most languages don’t enforce this concept, but let the programmer choose to either implement access as functions, or to not hide the associated variable. Other languages, like C# and Objective-C, actually support this system through constructs of the language itself.

Imagine we are developing a class that represents a user on a forum. This class has an “age” property, that keeps the age (by year) of the user. Imagine we also want to add some special code to prevent the registration of those that are under the age of 13, which is a common rule for Internet forums.

In C++, the associated getter and setters would be as follows:

int UserAge;
 
int GetAge()
{
	return UserAge;
}
 
void SetAge(int NewAge)
{
	if(NewAge >= 13)
		UserAge = Newage;
}

In total, these 10 lines of code are simple, clean, and clear. C#, on the other hand, uses the get/set design built-in the language:

public int UserAge
{
	get
	{
		return UserAge;
	}
	set
	{
		if(value >= 13)
			UserAge = value;
	}
}

This C# is code is 12 lines of code, roughly the same code-density of C++. Maybe the difference in code isn’t the size or language-level support, but how it is accessed?

In C++, to set data that is private, you must use an accessor, while in C# you can directly access it through these get/set properties. A benefit is if the property you are setting isn’t a primitive data type (such as a Color object, that has three channels of red, green, blue), then you can also directly access these sub-properties. In C++, you would have to get a copy of the object through a single get, change it, and set it back, leading to unnecessary code size.

Simply put, in C++, you cannot change values of returned variables, though in C# with the get/set support, you can in certain situations.

In the end, direct property access, hidden through C#’s language-level support of get/set, can be a handy tool to reduce code size. Though C++ has the benefit of forcing you the explicitly write these rules, it quickly bloats the code with it’s large overhead.

This entry was posted in News & Updates. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

Sites map