Advertisement

C# Workshop - Week 1 (Ch. 1 & 2) - Advanced

Started by July 01, 2007 12:15 AM
337 comments, last by paulecoyote 17 years, 1 month ago
Quote: Original post by dusty_one
One thing that's puzzled me in any oop language, the idea behind protecting class members. I don't see why one would want to mak esome things inaccessable, or if you can get to it, you do it only through getters and setters. What's the logic in making a member protected?


I'll assume you mean "protected" as in inaccessible to outsiders, rather than the protected access level:

Basically, it reduces a chance of bugs. Suppose a class in a library has some member that all of its operations depend on. Changing this would have a disastrous effect, so you make it private so others can't change it.

You could just put a message in the documentation saying "changing member x would be a Bad Thing", but there's no need to put the burden of remembering that on the programmer when it could be placed on the compiler.
Think of this simple example, dusty_one. Your boss tells you to rename all internal variables to have _ prefixing their names, so instead of "someVariable", you now have "_someVariable." If you had allowed public access to your member variables, you would have to search all throughout the program looking for where you had referenced the variable by its old name. With getters and setters, all you have to do is change what is inside the class.

In software engineering terms, it helps decrease coupling.
Advertisement
Quote: Original post by dusty_one
One thing that's puzzled me in any oop language, the idea behind protecting class members. I don't see why one would want to mak esome things inaccessable, or if you can get to it, you do it only through getters and setters. What's the logic in making a member protected?

As mentioned above, it can reduce bugs.

It's also a means of abstracting things away. Objects are like black boxes with which you communicate using a fixed language. This makes it possible to modify their internals without breaking the code that makes use of these objects.

Languages not only need to help you write correct code, they also need to assist you in modifying your code. Keeping this in mind will help you understand many "odd" design choices in languages.
Quote: Original post by visage
Think of this simple example, dusty_one. Your boss tells you to rename all internal variables to have _ prefixing their names, so instead of "someVariable", you now have "_someVariable." If you had allowed public access to your member variables, you would have to search all throughout the program looking for where you had referenced the variable by its old name. With getters and setters, all you have to do is change what is inside the class.

In software engineering terms, it helps decrease coupling.


Wow and thank you! That's the most make-sense explanation I've heard for setters/getters in forever.

I left a gift in your ratings section.

Beginner in Game Development?  Read here. And read here.

 

no questions yet but i will have for sure. i am posting the first work assigned.
namespace MyName{    class MyName    {        static void Main(string[] args)        {            string strMyName = ("Chris");             Console.Write("Please press Enter to find out my name");            Console.ReadLine();            Console.WriteLine("My name is " + strMyName);                    }    }}

i spiced it up a lil asking for some user input, nothing major but just a lil something. also this is my first time learning any language really. i started actionscript for a few months but i have been convinced to go with C#. i have 2 books i have been currently reading by Charles Petzold. i really want to know the ins and outs of the C# language by years end. i am really like this workshop and this forum and i cant wait to complete it all.

also i really like the concept behind the final project. lets do this!

[Edited by - lstcorona on July 1, 2007 8:33:43 PM]
As mentioned above, getters and setters can also help to make sure that a class's internal state is kept within valid bounds.

For example, let's say that you have a window, and you set it's maximum size to 100,100. Now, let's say that you change the actual width of the window to 120. If you just use a plain variable, how is the window supposed to know that you changed the value, in order to keep it within the valid bounds, as well as to update the actual size itself.

@lstcorona:

Just a friendly reminder: when posting code, use the source tags ([ source lang="C#" ]) so that your code doesn't come out all wrong.

namespace MyName{    class NyName    {        static void Main(string[] args)        {            string strMyName = ("Chris");            Console.Write("Please press Enter to find out my name");            Console.ReadLine();            Console.WriteLine("My name is " + strMyName);        }    }}


Also, I was wondering if people would be posting questions in the rest of the forum, or just as replies to this thread? Because they kind of get all jumbled together, and some may be repeated or missed. Making them as separate topics, and maybe posting links to them for common questions might make things easier.
Mike Popoloski | Journal | SlimDX
Advertisement
The concept of "setters" and "getters" is not a new one, but serves a few purposes.

First, as visage explained, setters and getters allow access to protected data, while reducing coupling. What this means exactly is not immediately obvious, but it means that tracking down changes to the data becomes much easier. Lets say that you're running your application and you discover that the value of some public field is being changed to an incorrect value. To determine WHERE it's being changed to an incorrect value you would need to set breakpoints at nearly EVERY place that public variable is set, and step through each to ensure correct functionality. ZOMG!

On the other hand, if you used a setter/getter for the field, then you could simply put a breakpoint within your accessor and POOF! With a single breakpoint you can monitor all changes to the protected data.

Also as visage pointed out, using accessors you can easily rename your variables, or even the data types of your variables without it being exposed to the users of your class. This ability to hide the internal workings of a class from the outside world is called encapsulation, and is key to OOP. A nice side effect of this is that changes to the internal implementation, field names, data types, etc...doesnt require a recompile by every assembly that uses your class. With public fields, a change in name or data type would be a change in the class's interface, and thus, would require a recompile by all clients.

In addition to being able to change the name and data type of the protected data without having to "fix" the changes everywhere, getters/setters also allow you to create data procedurally. For example, lets say you have the following class:
public class Rectangle{    public int Area     {        get { return m_Height * m_Width; }    }    protected int m_Height;    protected int m_Width;   }


In the example above I use a Property (C#'s Getters & Setters) to provide access to the Area data of the class. In this case, however, the area of the rectangle isnt actually stored anywhere, and is instead computed dynamically every time someone requests it.

If I had created a public field called Area, I would have had to make sure that its value was always in sync with the height and width fields. That is, if anyone, anywhere changes EITHER height or width, I would have had to recompute the area field also. That's a lot to keep in sync, even for such a simple example.

And Finally, setters/getters are useful for validation. Lets say that I have a class such as the follows:
class Character{    public float m_Health; // Health is a %, from 0.0 to 1.0}
In the above example, I have a character who's health is a % from 0 to 1. Now, floats, by definition, allow me to use values beyond the range of 0 to 1. If I were to expose the above field as written, every time/place someone were to set the health of my character, I'd also need to call some kind of validation function to make sure the health was set correctly. However, if I use setters/getters (aka Properties) I can do the following

class Character{    public float Health    {        get { return m_Health; }        set         {            if( value < 0.0 )                m_Health = 0.0;            if( value > 1.0 )                m_Health = 1.0;            else                m_Health = value;        }    }    protected float m_Health;}


Now you'll see that validation/correction of the protected data happens EVERY TIME someone modifies it, automagically, without the need to make explicit calls to a validation function.

As well, the conversation can go the other way as well. Although I dont have time to provide an example now, while validation gives the class an opportunity to make sure the data coming in is correct, formatting or conversion allows the class to make sure that data is being exposed to the user in an easy-to-use format.

Lets say a protected field of a class is some other complex class, however I dont want to expose all parts of it to the users, or I want to format it as a string, integer, etc...I can easily provide an accessor to the protected data which returns a nicely formatted value instead of a direct reference to the complex, user-defined type.

So here they are in a nutshell. Getters/Setters...
  • Decrease coupling, allowing easier maintenance

  • Increase encapsulation, allowing more flexible development

  • Allow for procedurally generated data

  • Allow for automatic validation

  • Allow for automatic conversion and/or formatting

Cheers!
Jeromy Walsh
Sr. Tools & Engine Programmer | Software Engineer
Microsoft Windows Phone Team
Chronicles of Elyria (An In-development MMORPG)
GameDevelopedia.com - Blog & Tutorials
GDNet Mentoring: XNA Workshop | C# Workshop | C++ Workshop
"The question is not how far, the question is do you possess the constitution, the depth of faith, to go as far as is needed?" - Il Duche, Boondock Saints
hey mike,

thanks for the heads up. i have corrected my posting.

thanks man
1. Do we get a listing of "correct" answers at some point?

2. Should we actually post answers here, or just compare our answers if "correct" answers are given?

3. When we do the exercises, will we have a "correct" version of the program listed? Well, I know there are many different ways to code things and achieve the same results.

4. Should we post our code for exercises in each weeks thread?

Thanks,

Shawn
Thanks for all the clarifcation. I also meant to call into question the access level of methods, fields was just the easiest way for me to think of an example. Why would a programmer set methods to be unaccessable outside of the class? I just want a clear reasoning concerning access levels in general so I'll know when I should be making some static/protected/private/etc..

This topic is closed to new replies.

Advertisement