473,811 Members | 3,444 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reason for Accessor Methods

I have been programming using C# for over a year now and I still wonder
what is the importance of using accessor methods when the property is
read-write. It seems easier to just make it a public property of the
class, but I have read in more than one book that this is a bad
practice. The books did not mention the reason why this is a bad
practice. Can anybody give me some insight on this?

Nov 17 '05 #1
7 2365
Tenacious,

The general guideline I have seen in the class design recommendations
from MS say that you should use Get and Set methods when the change is a
significant operation, not just another property on an object.

Before C# 2.0, you had to use Get and Set methods if you wanted the
access levels to be different (private/public, for example).

In C# 2.0 now, you can have different accessor levels on the get and the
set, which eliminates that particular need for Get and Set accessor methods.

I would agree with the original design guideline though, that if the
operation is doing something significant, then it should be its own method.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Tenacious" <CT*******@yaho o.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
I have been programming using C# for over a year now and I still wonder
what is the importance of using accessor methods when the property is
read-write. It seems easier to just make it a public property of the
class, but I have read in more than one book that this is a bad
practice. The books did not mention the reason why this is a bad
practice. Can anybody give me some insight on this?

Nov 17 '05 #2
The idea, I believe, is that callers perceive properties as "cheap" to
call, and therefore have no qualms about calling them inside loops,
etc.

A method call, on the other hand, registers with callers as something
potentially expensive.

If doing this:

ProductCollecti on products = supplier.Produc ts;

causes a massive query to the database plus a whole whack of
DataRow-to-object conversions and a final sort to occur, then it should
probably be written like this:

ProductCollecti on products = supplier.GetPro ducts();

as a sort of visual warning that this could take a while.

supplier.Produc ts

looks too innocuous to draw much attention.

The other guideline that I recall is that in general properties
shouldn't throw exceptions. If your property is doing something complex
enough that it can generate exceptions then it should probably be a
method, for the same reason stated above: caller perception.

That said, these are general guidelines. Many properties can throw an
OutOfMemoryExce ption. Many others do considerable work. It's all a
question of knowing whether your callers are sophisticated enough to
know that even a simple property reference has the potential to chew up
cycles and throw exceptions. MS is betting that most don't.

Nov 17 '05 #3
I think that you're confusing properties with fields. The OP was asking
for reasons why you would prefer to write this:

Thing someThing = myObject.GetSom ething();

rather than this:

Thing someThing = myObject.Someth ing;

where Something is a property with a getter (and perhaps a setter).

Certainly, it's preferable to expose properties rather than expose
fields directly. The question was, why would you prefer to write a Get
method rather than use a property with a getter.

Nov 17 '05 #4
No confusion.

The question was generic, not database related. IMHO
:-)

"Bruce Wood" <br*******@cana da.com> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I think that you're confusing properties with fields. The OP was asking
for reasons why you would prefer to write this:

Thing someThing = myObject.GetSom ething();

rather than this:

Thing someThing = myObject.Someth ing;

where Something is a property with a getter (and perhaps a setter).

Certainly, it's preferable to expose properties rather than expose
fields directly. The question was, why would you prefer to write a Get
method rather than use a property with a getter.

Nov 17 '05 #5
Bruce Wood wrote:
I think that you're confusing properties with fields.
So do I.
Certainly, it's preferable to expose properties rather than expose
fields directly. The question was, why would you prefer to write a Get
method rather than use a property with a getter.


He did not mention "writing a Get method". Given:

public class c
{
private string _s;

public string s
{
get {return _s;}
}
}

I think the OP's actual question is "What is preferable about the indirection
here? Why not just have the field be "public string s"? I don't believe the
question involved methods (yet a third way to do it, sort of - "get" IS a method
as far as I am concerned) at all. I think it's more like "What's so great about
data hiding that everyone speaks of it as being 'certainly preferable' when most
of the examples given are as trivial as the one above?" A good tenacious
question, IMO.

-rick-
Nov 17 '05 #6
I stand corrected. I was in this instance, I don't have a formal MS
background, so my terminology doesn't always tally.

Perhaps Tenacious could restate the question. Do you mean "what is the
importance of using accessor methods when the field is
read-write" as I understood it in my own way? :-)
Rick wrote:
I think it's more like "What's so great about data hiding that everyone
speaks of it as being 'certainly preferable' when most of the examples
given are as trivial as the one above?" A good tenacious question, IMO.

-rick-


True for a trivial example, but only if you can guarantee that it will
remain so.

Dave
Nov 17 '05 #7
Tenacious wrote:
I have been programming using C# for over a year now and I still
wonder what is the importance of using accessor methods when the
property is read-write. It seems easier to just make it a public
property of the class, but I have read in more than one book that
this is a bad practice. The books did not mention the reason why this
is a bad practice. Can anybody give me some insight on this?


I think that properties should be used sparingly. The example I give is
the Control properties Height, Width, Left, Top. For example:

Form f = new Form();
f.Visible = true;
// do some stuff with default size and position, then change size and
position
f.Width = 200;
f.Height = 200;
f.Left = 100;
f.Top = 100;

Each of these properties is implemented with a call to SetBounds. It is
far better to write:

f.SetBounds(100 , 100, 200, 200);

SetBounds will raise events, and your intention is to size and position
the form, hence you want just one event to say the form has moved.

I think it was wrong of the Forms team to have provided these
properties, SetBounds (this one and the overload) do exactly what you
want them to; the properties help you to write incorrect code.

Richard
--
http://www.grimes.demon.co.uk/workshops/fusionWS.htm
http://www.grimes.demon.co.uk/workshops/securityWS.htm
Nov 17 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2007
by: jerrygarciuh | last post by:
Hello, I have been working for some time now on a PHP OOP database abstraction layer. Yes I know there are others out there which are maturing but I like reinventing this wheel. The task I have at hand is that I want to specify 'has a' and 'has many' relationships in an array for each class and use these to automagically create the accessor methods and perhaps mutator methods as well.
22
6795
by: mirandacascade | last post by:
When I look at how classes are set up in other languages (e.g. C++), I often observe the following patterns: 1) for each data member, the class will have an accessor member function (a Get<whatever> function) 2) for each data member, the class will have a mutator member function (a Set<whatver> function) 3) data members are never referenced directly; they are always referenced with the accessor and mutator functions My questions are:
2
2069
by: Todd A. Anderson | last post by:
I've inherited two "C++" code bases that I have to tie together and both of them make frequest use of public member variables in spite of all the information saying this limits flexibility. Well, their lack of foresight has bit me of course! I'd like to start off by converting all their public member variable accesses to the use of accessor methods. Then, I can reimplement selected accessor methods to provide the necessary glue between...
22
12042
by: Generic Usenet Account | last post by:
A lot has been said in this newsgroup regarding the "evil" set/get accessor methods. Arthur Riel, (of Vanguard Training), in his class, "Heuristis for O-O Analysis & Design", says that there is almost never an excuse for accessor methods. Personally, I do not go that far. I do feel that they serve a useful purpose (albeit in a limited manner). Personally I prefer dropping the "set" and "get" prefixes from the method names altogether. ...
3
4553
by: LuCk | last post by:
Can someone explain what these really are for example: ---------------------------------------------------------- void SetFrameRate(int iFrameRate) { m_iFrameDelay = 1000 / iFrameRate; }; ---------------------------------------------------------- I know what functions are and i know what void is and stuff but i dont get the whole `Accessor Methods` term i guess.
6
2974
by: Jason Shohet | last post by:
I have a class with protected variables and some accessor methods, , get, set ... Maybe I have a brain blockage today but I'm thinking, why not just make those variables public. After all, someone can do just as great harm by misusing a set { } accessor method as just doing myObj.lastname = "Big Bird"; which he could do in a second class, if the variable is public on the first class. IOTW, what does keeping with the protected /...
8
1787
by: AAJ | last post by:
Hi all I would like to have a class that can set/return values of different datatype via a single accessor, i.e. overload the accessor i.e. something like DateTime m_DateValue; string m_StringValue;
8
8244
by: Tim Sprout | last post by:
Why is it considerd best practice to use Properties rather than Get and Set accessor methods? -Tim Sprout
2
1382
by: rbjorkquist | last post by:
This is my first attempt at writing/using web services, so any and all comments will be greatly appreciated. With that said, I am also by no means saying this is the correct either. I have noticed that when returning a new TPastePart, created and filled by the web service, that if the "PastePartID" and "PastePart" properties do not have "set" accessor methods, their respective data is not returned, even though the object has contains...
0
9727
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10398
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9204
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3865
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3017
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.