Sign in to follow this  
storage

[.net] [C#] Small get/set problem

Recommended Posts

I'm currently trying to learn C#, but I've run into a problem with the get/set functionality.
        public KernelState State()
        {
            get
            {
                return _state;
            }
            
            set
            {
                _state = value;
            }
        }


Give me these errors, just after the get or set:
Error	1	; expected
Error	2	; expected
I appreciate the help. Thanks, storage.

Share this post


Link to post
Share on other sites
if the property Stateis modifies _state unchecked, and without any side effects (no event is triggered, no value checking, etc), then why use it? Name _state as State and no need of the get/set property

Share this post


Link to post
Share on other sites
With the way you are doing things you might as well make _state public. Using it the way you did exposes it with out any protection. You should really verfy the value when you set it. Put in some error checking to make sure the value that you are setting is a valid value.

theTroll

Share this post


Link to post
Share on other sites
Quote:
Original post by orbano
if the property Stateis modifies _state unchecked, and without any side effects (no event is triggered, no value checking, etc), then why use it? Name _state as State and no need of the get/set property

You can't have fields in an interface.

Share this post


Link to post
Share on other sites
I never use public fields these days. With code snippets it's so quick to insert the Property anyway, and your code'll be primed for proper serialization, PropertyGrids, Attributes, conditional breakpoints when the value changes etc.

Share this post


Link to post
Share on other sites
It does contain some useful semantics to use a public field instead of a property (you know it's not going to trig any code), but "empty" properties are very rare in my code. I always have to go back and change it to a property if I start out with a field, so prop<tab><tab> has become my default lately.

But how much slower is it actually in execution? Empty properties that is. I would've imagined some compiler optimizations would pretty much remove the difference.

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
The reason that you use properties is the hide the internal data and to make sure that the data is valid. Just to use them becuase you can is a waste of time.

theTroll


and full requirements analysis before implementation is impossible. changing requirements may dictate increased functionallity in the property. initially implementing access to the field as a property simplifies the later change. Besides, the compiler inlines simple properties like that anyway. You lose nothing in runtime and gain in refactoring time.

Share this post


Link to post
Share on other sites
This is why we have so many bugs in code today. The biggest advantage of a property is to allow you to check the incomming value bedore you assign it to your member. Not writing error code and value checking when you write your class is being lazy and being a poor programmer. If everyone took the time to do this write code would be more robust and a lot less buggie. These are simple things that you should do for EVERY class and EVERY member. As the power of computers get more and more powerful people seem to get lazier and lazier about writing good and complete code.

I have worked in the industry for over 15 years, from what I have seen if you don't put in error checking when you create a function or class people rarely go back and do it until a bug shows up to bite them. This is one of the reasons that buffer overflows still exist, they could have been stomped out a long time ago by a little value and error checking.

theTroll

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
This is why we have so many bugs in code today. The biggest advantage of a property is to allow you to check the incomming value bedore you assign it to your member. Not writing error code and value checking when you write your class is being lazy and being a poor programmer. If everyone took the time to do this write code would be more robust and a lot less buggie. These are simple things that you should do for EVERY class and EVERY member. As the power of computers get more and more powerful people seem to get lazier and lazier about writing good and complete code.

I have worked in the industry for over 15 years, from what I have seen if you don't put in error checking when you create a function or class people rarely go back and do it until a bug shows up to bite them. This is one of the reasons that buffer overflows still exist, they could have been stomped out a long time ago by a little value and error checking.

theTroll


That contradicts what you previously said, when at the same time stating the obvious.
Yes you should always use properties. Always. Seeing a publically visible field in a class gives you pause to question the quality of the code.
And there is nothing wrong with having a property that simply wraps a field. As has been mentioned, this makes serialization a lot easier (think xml serializer), it allows the value to be visible in a property grid, it causes no performance loss, looks neater, and above all in the event you do need to limit the value range *or* change the underlying data representation, then there is no need to change the class externally.

as for:

Quote:

This is one of the reasons that buffer overflows still exist, they could have been stomped out a long time ago by a little value and error checking.


Buffer overflows are a moot point in .net, however in C++ the vast majority of the time they are caused by a method taking in a array pointer instead of a vector/list/what-have-you. Those sorts of things are very difficult to track down, and pretty much impossible to error check.
The other main time I've dealt with buffer overflows is when error values are ignored. A function returns -1 to signal an error, yet the value still gets used as an array index. Naturally managed exception's helps out enormously here.

And last thing I'll say is it's not possible to forsee every possible use of a class/property at the time of creation. It simply can't be done.

Share this post


Link to post
Share on other sites
RipTom you are missing the point. What I said was if you are going to just wrap a member with a property then you might was well just make the member public. By the way you should not do that because it breaks the rules of encapsilation, as does a property that just wraps a member.

The point I am trying to make and you seem to either not get or just refuse to see is that properties are the first line of defense for bad data. Lets say I am doing some basic graphics stuff, was a a POINT class, with just an x and y. Well we would not want a negative x or x, and we also would not want a x or y that is greater then the display max. A property can check the value before you write it and make sure that it is valid.

Should you always do this, YES. Every value coming into your program should have some type of checking on it. Why? Because then you can have anyone use your class and know that it will never have a value that can not be used. When you are writing code, at least in the buisness world, you will be working with others, they will use your class and might not be as careful as you would. You should always write your classes to protect themselves. Does it take more work and is about the most boring thing in the world to do, sure is, but if you do it you are writing much more robust code.

No you can not see every possible condition your class may face, but that does not mean that you should not do what you can to protect it. It is not hard to take a look at your class and figure out what will break it and test to make sure that your members are not invalid.

TheTroll

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
RipTom you are missing the point. What I said was if you are going to just wrap a member with a property then you might was well just make the member public. By the way you should not do that because it breaks the rules of encapsilation, as does a property that just wraps a member.
Incorrect, you should make every member that needs public access a public property. This is not only to correctly implement encapsulation, but also give you some options later on down the road when you decide to change the functionality of the property. The JIT compiler is also smart enough to translate the wrapper property as if it weren't wrapped at all.

Quote:
Original post by TheTroll
The point I am trying to make and you seem to either not get or just refuse to see is that properties are the first line of defense for bad data.
RipTorn and everyone else understand what you're getting at, and that's why we're trying to explain why encapsulation is important.

Quote:
Original post by TheTroll
Lets say I am doing some basic graphics stuff, was a a POINT class, with just an x and y. Well we would not want a negative x or x, and we also would not want a x or y that is greater then the display max. A property can check the value before you write it and make sure that it is valid.
You are correct, instead of just making the X and Y members public, you would put them within a property and check the value when setting. I was under the impression you were against the ideology of properties?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Imagine you want to debug some code.

You set a breakpoint into the Getter/Setter of a property that simply wraps a field.

What would you do when you just make the field public? Make it a property and after debuging change it back to a field?


And to add one thing, properties might not look very different in your code, but they are a big difference when it comes to reflection. Imagine you want to write an own serializer class like the XmlSerializer, for CSV files for example. It is a lot easier to limit it on properties than to use both, properties and fields.

Take a close look at the .NET framework. It is a very well formed library, especially when you look at the Windows.Forms. Do you see any public fields? Is it because of bad programmers? Or is it your turn to change your mind?

Share this post


Link to post
Share on other sites
I think the troll's saying the same thing we are except in a way that was easy to misinterpret.
"With the way you are doing things you might as well make _state public."
is actually analog to
"If you're starting to like James Blunt, you might as well kill yourself"
And we go "No, suicide is never a good solution!"

Share this post


Link to post
Share on other sites
Actually, TheTroll is arguing that if you're using properties you should verify incoming data. Even if the checks are mundane or technically impossible to have occur. The failure to provide these front line checks is what he's arguing about. (That, or he's trolling. <g>)

I don't agree, however. :)

The biggest reason I use properties instead of public fields is because it provides me with the ability to later add that error checking or, in some cases, variable synchronization or some other facade. Why create a property if I'm not going to do error checking or other work in it? Aside from encapsulation, it prevents me from crippling the class later on.

The first time this came up for me was when I tried to replace a public field with a property when the field had been passed by reference several times. No go, can't pass properties by reference. Similar situations exist, ready to make you smack your head against your desk.

Share this post


Link to post
Share on other sites
If you make a public property that does nothing but set the member you have not provided encapsulation, you have just made your member public. That is the point that I am trying to make. There is no difference between a public member and a public property that just does a set. You are doing the same thing.

Some of you may be wondering why this is such a big thing to me. I have spend thousands of hours fixing bugs because people did not add basic error checking in thier member sets. What would have taken 5 minutes at design and code time can take hours when debugging.

Now there is no reason that you have to take my advice, but in the end someone is going to pay for it.

theTroll

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
This is ridiculous

You suggest not using properties when you have nothing to validate and just set the member.

And the reason you give to do this is: people don't do good validation.


It's like:
If you write a program in C++ and you don't use polymorphism you should stick with C. Because people write bad code in C++.

Share this post


Link to post
Share on other sites
Once again people completely miss the point. I am not saying don't use properties. I am saying do some basic error checking. Wrapping a member set does nothing for you, nothing at all, and yes there will be some people saying it helps with serialization and other things but you can do those without wrapping the member. Your set property is the first line of defense to write some robust code. If you are not using it then you are really missing the point. Using something just becuase you can without adding benifits to your code is just a waste of typing. Sure properties look pretty, but they are there to give you the ability to protect yourself, not just to look pretty.

Now I am going to get blamed for "Trolling" but what part of this is so hard to understand? Is there a reason that I am missing that people do not want to write robust code? And before someone starts, yes you can find cases in which there can be not error checking, but these are the exception not the rule.

theTroll

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
Wrapping a member set does nothing for you, nothing at all, and yes there will be some people saying it helps with serialization and other things but you can do those without wrapping the member.

You can't databind to a field. You can't view fields in a PropertyGrid. You can't have fields in an interface. These are on their own perfectly good reasons for using a dumb property over a field. Period.

Share this post


Link to post
Share on other sites
When did I say use a data member? I have not. What I keep saying and you all seem to miss the point is add some error checking into your properties. This is not about choosing between and data member and property, this is about putting some simple error checking in your code.

I have no idea why you all think that I am saying to use a data member instead of a property. I have said many many times that it is a bad idea. What I am trying to get across is if you write a wrapper property and do NO error checking that it is a bad idea. Am I not explaining myself well?

theTroll

Share this post


Link to post
Share on other sites
Quote:
Original post by TheTroll
What I am trying to get across is if you write a wrapper property and do NO error checking that it is a bad idea.


There are plenty of reasons why you would have a wrapper property and do no error checking. Many of those reasons have already been mentioned in previous posts in this thread.

Share this post


Link to post
Share on other sites
Sometimes any value is fine, so no error check is required. If, to go back to the OP's example, KernelState is an enumeration, it is impossible to pass an invalid value (well, short of intentional abuse I guess, in which case it's best to assume the user knows what he's doing). If any possible value for the field/property type in question is valid in the context of the object, no error check would be needed, so what's the point in writing one?

Share this post


Link to post
Share on other sites
The case of the Troll on a sinking boat :)

Lets say i have a real 4D vector class (RxRxRxR):

class cRealVector3D
{
public double x;
public double y;
public double z;
public double w;
}

I dont need error checking, so, as The Troll said i make my fields public, because i dont understand the others saying: use properties to forcome later design issues.
I start using it in my graphics program to deal with homogenous coordinates, but later realise that, its not good to let people set an arbitrary 'w' value, so i do:
create a static private field that stores the "non ideal" value for 'w'. the only thing i have to do is limiting field access, so that code, that uses this class can only set 'w' to this specified value, so they cant create ideal elements, and possibly f**k up the whole program, and:
inside the class, let it do, but trigger an event/exception, when an ideal element is created.
how would you do itm if you didnt use properties?

its quite a silly example i think, but i think it shows the situation, you are talking about

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this