-
What's with all the Get/Set lines?
I'm new to this so excuse me if this question is obvious.
A lot of the examples I am seeing for variables are using get set methods.
In C++ you only needed to declare the variable in the header file of the class and then assign it a value with the = operator.
But in C# I see this:
Code:
private string m_csTitle;
public string Text
{
get
{
return m_csTitle;
}
set
{
m_csTitle = value;
}
}
And yes I understand private / public but never really used it that much so just used public most of the time in the past.
This way of doing varriable assignment seems to take up so much more room ( 12 lines instead of 2 ) !
Do I have to do it this way? I have a program with several hundred variables in one class due to the large number of controls on the form.
-
Re: What's with all the Get/Set lines?
for simple properties like that I usually just put it all on one line:
Code:
private string m_csTitle;
public string Text { get { return m_csTitle; } set { m_csTitle = value; } }
-
Re: What's with all the Get/Set lines?
in c# you can also just make vars public and access them without using get and set
using get and set is called properties
http://www.c-sharpcorner.com/UploadF...rtiesInCS.aspx
and is generaly seen as a prettier way of handling member functions
for classes
-
Re: What's with all the Get/Set lines?
It's called Encapsulation. Imagine the following:
Code:
public class Example
{
public int Month;
public Example()
{
}
}
....
public class GetExample
{
public GetExample()
{
Example e = new Example();
e.Month = 13;
}
}
The above example demonstrates that anyone / anything can create an instance of "Example" and set the public variable "Month" to what ever they please. In the below example you can see why it makes sense to use get and set for class properties:
Code:
public class Example
{
private int m_Month;
public int Month
{
get
{
return m_Month;
}
set
{
if (value !> 12)
{
m_Month = value;
}
else
{
throw new Exception("Invalid Month");
}
}
}
public Example()
{
}
}
....
public class GetExample
{
public GetExample()
{
Example e = new Example();
e.Month = 13; // this now throws an exception
}
}
In summary, never allow class variables to be publicly accessible or bad stuff WILL happen!
-
Re: What's with all the Get/Set lines?
Using get and set allows you to make properties write only (i.e. only allow a set) or make them read-only (only allow a get). If you're ever designing a reusable library, you will have to make extensive usage of these.
Suppose you have an int which tracks how many times the user of your library can do a certain thing, if you made that int public, then your user can just go: myInt = 100000; and do it as many times as he wants. However if you exposed the int using a property with only a getter, the user couldn't do that.
Secondly, you now have Automatic Properties, so you can declare your 12 lines in just one:
public string CsTitle { get; set; }
or for readonly:
public string CsTitle { get; }
-
Re: What's with all the Get/Set lines?
Great, thanks for that example and link.
The name of the link was "Understanding Properties in C#"
If I had known that member vars are called "properties" maybe I could have found it easier :ehh:
This whole thing is like the VBism of C++ sheesh.
Hope this learning curve pays off.
-
Re: What's with all the Get/Set lines?
Well, you have member variables *and* you have properties
A member variable looks like this:
Code:
private int myInt;
internal string myString;
protected char myChar;
public float myFloat;
A property could be used to access those
Code:
public int MyInt
{
get { return myInt; }
set { myInt = value; }
}
Properties have getters and setters, member variables are still member variables like in C++. This is actually a really nice feature as you don't have to write stupid methods like: SetMyInt() GetMyInt() anymore like you do in C++, you can make it look a lot prettier ;)
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Consola
In the below example you can see why it makes sense to use get and set for class properties:
So, you're using validation as the case for the voluminous get/set lines?
Not a very good case if you ask me.
int nNum;
if(nNum > 12)
message
This is/was much shorter and easier.
Quote:
Originally Posted by Consola
In summary, never allow class variables to be publicly accessible or bad stuff WILL happen!
Um prove it?
I used public variables often in millions of lines of code in classes sharing variables cross classes, etc... never had a problem
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Mutant_Fruit
Using get and set allows you to make properties write only (i.e. only allow a set) or make them read-only (only allow a get). If you're ever designing a reusable library, you will have to make extensive usage of these.
Suppose you have an int which tracks how many times the user of your library can do a certain thing, if you made that int public, then your user can just go: myInt = 100000; and do it as many times as he wants. However if you exposed the int using a property with only a getter, the user couldn't do that.
Secondly, you now have Automatic Properties, so you can declare your 12 lines in just one:
public string CsTitle { get; set; }
or for readonly:
public string CsTitle { get; }
Sorry not understanding only read or only set. WHen I use vars I always get and set them both. So... guess I would always use automatic?
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Mutant_Fruit
Well, you have member variables *and* you have properties
Properties have getters and setters, member variables are still member variables like in C++. This is actually a really nice feature as you don't have to write stupid methods like: SetMyInt() GetMyInt() anymore like you do in C++, you can make it look a lot prettier ;)
Ok, the property concept is starting to come back to me from my VB days (which I would prefer to forget).
I never wrote the stupid methods and don't care about pretty, other wise I would have a career as a graphics designer lol.
I do care about efficiency (less lines, condensing code, etc..)
But I get it a little more now.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
I used public variables often in millions of lines of code in classes sharing variables cross classes, etc... never had a problem
I'm sure Steve McConnell and Erich Gamma wouldn't agree ;)
http://www.amazon.co.uk/Design-patte...2435733&sr=8-1
http://www.amazon.co.uk/Code-Complet...2435800&sr=1-1
You don't have to take my advise and I am often wrong, but just because you've never had any problems does not mean they do not exist in your code!!
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Consola
Just color me the cynical programmer. I'm not into phrases like "this is the way its done".
I want proof, reason, details. I'm stubborn that way. If someone can show me a better way , I'm receptive, but I have to see why its better.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
I want proof, reason, details. I'm stubborn that way. If someone can show me a better way , I'm receptive, but I have to see why its better.
The reasons for using properties, and ALWAYS keeping data private, is that it gives you the flexability to change the internal representation without effecting your clients. It also provides "hooks" for intercepting all read/write accesses.
There is (almost) nevery a reason to have data members directly exposed.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
I want proof, reason, details. I'm stubborn that way. If someone can show me a better way , I'm receptive, but I have to see why its better.
Quote:
Originally Posted by Mutant_Fruit
Suppose you have an int which tracks how many times the user of your library can do a certain thing, if you made that int public, then your user can just go: myInt = 100000; and do it as many times as he wants. However if you exposed the int using a property with only a getter, the user couldn't do that.
Is that reason enough for you? If you made that int public, how could you control how many times your user does action X? You couldn't. This is why it's better.
Quote:
Sorry not understanding only read or only set. WHen I use vars I always get and set them both. So... guess I would always use automatic?
You have three types of properties:
1) Readonly: This type of property *only* has a get method, so you can "get" the value.
2) Writeonly: This type of property *only* has a set method, so you can "set" a new value. However you can never check what value is there.
3) Read/Write: This type of property has both a get and a set so you can read the value that's there and write a new one.
Automatic properties are a compile time trick. They allow you to write:
Quote:
public string CsString { get; set; }
and at compile time it magically turns into
Code:
private string m_csTitle;
public string Text
{
get
{
return m_csTitle;
}
set
{
m_csTitle = value;
}
}
This allows you to write less lines of code for the same result.
Of course, generally people do condense the gets and sets to something along the lines of this:
Code:
private string m_csTitle;
public string Text {
get { return m_csTitle; }
set { m_csTitle = value; }
}
One of the main advantages of using properties is that you control access to your variable while still being able to treat it as a regular object of that type. For example in c++ you might have to write:
int myInt = myobj.GetValue() * myobj.GetCost();
but in c# you write:
int myInt = myObj.Value * myobj.Cost;
However there are some cases where you can't use properties. Running from memory i think it's when you want to use the object as an "out" argument or "ref" argument. You'd want to double check that yourself ;)
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
I want proof, reason, details. I'm stubborn that way
I would highly recommend reading the two books I posted links for. Especially "Code Complete" this will give you enough proof, reason and details to last you a life time.
I too am anti "the right way" (especially concerning microsoft), but I do maintain the mentality that there is always a better way of coding something regardless of age, experience or salary ;)
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by TheCPUWizard
The reasons for using properties, and ALWAYS keeping data private, is that it gives you the flexability to change the internal representation without effecting your clients. It also provides "hooks" for intercepting all read/write accesses.
I'm sure you had some specific examples in mind as you were providing this broad and generalized statement. ? And it could be that your examples are not applicable to my scenarios but I'm willing to see if they are.
In the past i did most of my hooking after the var is assigned a value so I'm not sure of the benefit of before its assigned. Seem like 6-to-1 1/2 dozen to the other.
Quote:
Originally Posted by TheCPUWizard
There is (almost) nevery a reason to have data members directly exposed.
The words "quick", "easy", "full access" don't come to mind here?
-
Re: What's with all the Get/Set lines?
[QUOTE=alan93]I'm sure you had some specific examples in mind as you were providing this broad and generalized statement. ? And it could be that your examples are not applicable to my scenarios but I'm willing to see if they are.
In the past i did most of my hooking after the var is assigned a value so I'm not sure of the benefit of before its assigned. Seem like 6-to-1 1/2 dozen to the other.
Code:
private int m_Value;
public int Value
{
set
{
// Do things before the write
m_Value = value;
// Do things after the write
}
get
{
// Do things before the read
return m_Value;
}
}
Quote:
The words "quick", "easy", "full access" don't come to mind here?
Nope, all of those thiongs are "bad". "Correct", "Reliable", "Maintainable", "Encapsulated", "Minimal-Surface-Area"... those are terms that come to mind.
-
Re: What's with all the Get/Set lines?
I guess this article of a fellow thinking skeptic explains better for me the questions I have about encapsulation, hiding, etc...
http://www.tonymarston.net/php-mysql/good-bad-oop.html
Particularly this excerpt:
Quote:
Another common OOP feature that I deliberately chose to ignore is having a separate 'getter' and 'setter' for each of my entity variables. Why should I waste my time in feeding an object one item of data at a time when I can feed all data in a single associative array? Why should I waste my time in retrieving data from an object one item at a time when I can retrieve all data items in a single associative array?
Since my MDI app uses records in a formview class , I don't have different objects. The formview is always going to be the formview with the same controls and control vars. The document will always be the same object with the same record objects. I do have a record class object but I would prefer to assign the vars directly in the doc without all the pretty get/set properties. I can perform validation on it but I prefer to do all the vars of a record in one place, not each individually.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
...but I prefer....
If you are writing the code for your own personal use, you are (of course) free to do what ever you like, as only you will have to deal with the consequences.
If you are in a professional programming environment, then the goals change. The primary focus is to reduce cost over the entire lifecycle of the product. Bugs cost money.
As an example, if you validate your values any other place than in a set property, you will have a hard(er) time tracking down who/where/when the value is set incorrectly. The following will definately be quicker to diagnose problems:
Code:
int Month
{
set
{
if (value <1 || value>>12)
throw new InvalidArgumentException("Month Values Must be between 1 and 12");
m_Month = value;
}
}
Now you have guarenteed that the value will NEVER be invalid, even for a nanosecond. There will never be any time spent tracking down the issue.
In terms of class sizes. Large classes are inherently harder to maintain. You will save time (in the long run) by breaking up the classes into related portions and aggregating them.
Remember one of the rules of testing is that any time a file is modified in any way shape or form, the ENTIRE file must be completely tested. This means running tests that exercise all possible paths through the code, including all error detection paths. If you split up the source, then the amount of work to test a change will be drastically reduced.
Excerpted from the coding rules my firms use:
1) All data private. No exceptions without written approval
2) 25 public properties maximum per class. Some flexability
3) Strive for a 3-5 to 1 ratio of properties to methods
4) All methods should have some internal function. If everything can be done in terms of public properties, the method should be factored out of the class. Methods are for "what an object does" not "what you can do to an object".
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
I guess this article of a fellow thinking skeptic explains better for me the questions I have about encapsulation, hiding, etc...
He also has this to say:
Quote:
There are times when making a variable private instead of public, thus forcing you to use a 'getter' or a 'setter' is a good thing. In this way should it ever be necessary to adjust the data before it is input or output you only have to change the code inside the 'getter' or 'setter' rather than all those places which reference the 'getter' or 'setter'.
Out of interest, have you ever designed and implemented a library meant for widespread use and incorporation into many different apps? If so, did you make all your variables public and not use get/set methods on them? Also, have you any comments on the example i mentioned twice which shows a scenario where using get/set methods is a necessity?
-
Re: What's with all the Get/Set lines?
i believe that with components it's only the properties which show up on the heh properties list for the gui component
personaly i believe that no vars should ever be made public
back before properties were really around we used to make get and set functions ourselfs (allso in c++)
because c++ have less enforced rules is no reason to be lazy
and if you need to compare less rules of c++ with something dont use vb as eks. vb is a world of pain
but not very ruly
pascal on the other hand is the disciplinarian :P
sure irl rules are cut but it would be madness if eks. dident try to enforce any types of rules
in c++ you can still use goto 10 (10 being line nr)
some crazy person may feel that heck people do things like that irl
but not! on my watch! :P jk
-
Re: What's with all the Get/Set lines?
that link you provided was for OOP in PHP. PHP isn't quite the same as C++, C# or even java. it has a much more limited context and I'm not totally convinced that it works best in a strict OOP implementation. I love OOP and PHP but split OOP and standard PROC coding in it to about 50/50.
in .net having public members isn't going to hurt anything. it's definitely against what most consider "best practice" and it will limit some things that you can do with your object, but hey, its your baby, ignore or use anything you want to.
I always found it annoying to create getter / setter methods for member access.
It always felt awkward to me to reference a variable like a method. I really like the interface provided by .net properties because accessing an object's members "like" a public member feels a bit more logical in my eyes. there are things that you can do with properties that you cannot do with public members, but I cant think of one thing you can do with a public variable that you cannot do with a property.
things you cannot do with public variables that you can do with properties:
1. validate input / output
2. lazy initialization
3. access to read / write
4. virtualized members (mark the "variable" as virtual or abstract to allow for inheritors to implement their own functionality of what that member does for the concrete class).
4. notify observers on access (trigger events on get or set)
there are probably many more but these are what come to mind.
like I said, do what you want, but don't miss the forest for the trees.
-
Re: What's with all the Get/Set lines?
Out of interest, not knowing any php, wouldn't the technique described in the previous link (http://www.tonymarston.net/php-mysql/good-bad-oop.html ) not tie you to implementation detail?
For example, suppose you wanted to change the internals to a dictionary, or a sorted list, or a linked list, or a hashtable, or seperate member variables, could you? I think not. However using properties in C# you can make those changes and the user of your code *does not care*.
-
Re: What's with all the Get/Set lines?
php is a different beast. its not as strict an OOP language as .net is.
1. variables are not strongly typed.
2. there is no real encapsulation in the first place.
3. there aren't different container / collection types, so thats not really a valid use case.
anything you design whether ood or not is going to be tied to implementation at some level.
-
Re: What's with all the Get/Set lines?
Hi,
A property procedure is a set of code statements that are used to assign or retrieve the values of the member variables declared within a Class. Properties are types of variables that store the values for an object of a Class.
We can access properties either as public variables or by using Set and Get property procedures. However, it is advantageous to use property procedures instead of public variables, because using a property procedure we can define a property as read-only, write-only, or read/write type. There are two types of property procedures in C#.
• get method, which is used to retrieve the value from a member.
• set method, which is used to assign values to a member.
Try This book:Database programming using Visual Basic 2005 and Csharp 2005
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by krisk123
Hi,
A property procedure is a set of code statements that are used to assign or retrieve the values of the member variables declared within a Class. Properties are types of variables that store the values for an object of a Class.
We can access properties either as public variables or by using Set and Get property procedures. However, it is advantageous to use property procedures instead of public variables, because using a property procedure we can define a property as read-only, write-only, or read/write type. There are two types of property procedures in C#.
• get method, which is used to retrieve the value from a member.
• set method, which is used to assign values to a member.
Try This book:Database programming using Visual Basic 2005 and Csharp 2005
Still tring to determine the purpose of your post... :confused: :confused: :confused:
What is the "Value Added"? :rolleyes:
-
Re: What's with all the Get/Set lines?
Properties provide numerous advantages, many of which have been suggested here. The general idea of properties is that they behave from the outside like variables so they are easy to use in calling code, but they behave from the inside like methods so they provide all sorts of flexibility.
Take the Text property of the TextBox class. If that was a variable then when you set it in code its value would change but nothing else could possibly happen. Because it is a property, when it is set the class can update its display as well as raise the TextChanged event to notify the form that the property value has changed. That would all be impossible with just a variable. Without properties you would have to use a method to accomplish this as you do in Java, where there are countless pairs of get_SomeValue and set_SomeValue methods. This is less intuitive than .NET properties, which can be used just like variables in calling code.
Properties also facilitate data-binding in .NET apps. You can bind a collection of objects to a DataGridView or other control and have its property values displayed. You cannot do that with variables because data-binding requires event support that variables don't provide.
Another reason that has already been mentioned is the freedom to change the implementation of a class without changing its interface. All developers should care about that. There are many situations where using a property doesn't provide an immediate advantage but the mere fact that it does provide the freedom to change the implementation without breaking calling code should be enough to convince any conscientious developer to use them.
The fact that the C# IDE provides support to create property skeletons for you makes any complaint about too much code moot. You just type "prop" and hit the Tab key twice and the code snippet will create a property skeleton for you and even helps you edit that skeleton coherently.
There is no valid argument for not using properties that I can see. Writing less code is not valid as the amount of additional code you actually have to write yourself is very small. The advantages it offers far outweigh that small inconvenience.
-
Re: What's with all the Get/Set lines?
well you could use events to do actions when a public var was changed but it would be alot of needless troublesome work to implement
-
Re: What's with all the Get/Set lines?
In C++/CLI (that's C++ for .net) there's a syntax which lets you declare public properties for which the compiler automatically provides the internal field & implements the get/set accessors for you.
I believe the same is planned for C# v3.
Quote:
Originally Posted by TheCPUWizard
Still tring to determine the purpose of your post... :confused: :confused: :confused:
I think he's just agreeing that 'properties = good', 'public fields = bad'.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Rudegar
well you could use events to do actions when a public var was changed but it would be alot of needless troublesome work to implement
Rubbish. How would you do that? Events are raised from within the object. If you set a public field then no internal code is executed so no event can be raised. You would need to set the field via a method of the object, which is exactly what properties do. A property is implemented as two methods when compiled but it is used in code as though it was a field. That's the point: you get the best of both worlds.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Rudegar
well you could use events to do actions when a public var was changed but it would be alot of needless troublesome work to implement
Erm... but how your code know to fire the event when a public member variable changes.
If i have a class which has a public member variable Temperature, and i set Temperature = 100, how can you automatically fire an event to let people know i've changed Temperature. You can't. There is no way.
Quote:
In C++/CLI (that's C++ for .net) there's a syntax which lets you declare public properties for which the compiler automatically provides the internal field & implements the get/set accessors for you.
I believe the same is planned for C# v3.
Yes, they're called automatic properties, i've mentioned em a few times in this thread ;)
-
Re: What's with all the Get/Set lines?
Regarding Events on Modification...
1) Agreed it is impossible if you expost the data member itself, you MUST use properties, and put the logic inside the property (see alternate note below...)
2) Raising Events on "Data" changes is a common feature. In fact my firms entiry line of "SmartData" products make VERY heave use of this..
Now the exclusion to point #1...
(Free Typed, so syntax not guarenteed ;) )
Code:
class SmartData<DATA_TYPE>
{
public DATA_TYPE Value
{
get
{
return m_Value;
}
set
{
if (m_PreWriteEvent != null)
m_PreWriteEvent(this, m_Value, value);
DATA_TYPE oldValue = m_Value;
m_Value = value;
if (m_PostWriteEvent != null)
m_PostWriteEvent (this, m_oldValue, Value );
}
}
}
Code:
class SomeClass
{
public readonly SmartData<int> MyIntegerProperty;
}
Code:
SomeClass.MyIntegerProperty.PreWriteEvent += new PreWriteEventHandler();
SomeClass.MyIntegerProperty.Value = 123; // Will fire Event...
While this may seem complicated for trivial situations, the model is HIGHLY extensible. The actual library contains full Control Binding, DataBase Persistance, Dynamic Data Caching, XMjects, and more...
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Mutant_Fruit
Yes, they're called automatic properties, i've mentioned em a few times in this thread ;)
Sorry, I somehow missed that. :thumb:
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Mutant_Fruit
He also has this to say:
Out of interest, have you ever designed and implemented a library meant for widespread use and incorporation into many different apps? If so, did you make all your variables public and not use get/set methods on them? Also, have you any comments on the example i mentioned twice which shows a scenario where using get/set methods is a necessity?
Sorry getting a little overwhelmed with the plethora of ideas coming in here.
Let me see if I can address most of them here.
Btw I didn't get your 100000 example.
Yes we have a dll dialog app that is used by several different programs. The dialog class has MANY global variables shared amonst the functions in that class. I don't make everything global but when it has to be shared I do m_csSharedStringVar or m_bSharedBoolVar. So controlling access doesn't resonate with me. I just use them masterfully the way I see fit.
Some people have mentioned that apps can be buggy but if you don't do this but the bugs we usually get are related to missing dlls or system anomolies not because a variable was public.
If I understood everything jmcilhinney said I might be sold on it lol.
My thoughts about doing the validation within the property bothers me because I LIKE doing the validation WHERE the values gets assigned. Not in a property in a galaxy far far away.
I like the single line declaration of the property , especially until I decide if I even want to use it to fire another event or do "remote" validation because Like I said , in the large scale MDI, have LOTS of controls and membr vars.
SO my aversion to 12 lines of property code is having all these in my view class or whatever and then making my eyes bleed looking for one or scrolling my fingers to the bone.
I think my primary programming philosophy is EFFICIENCY & CONDENSATION.
And yes I have been known to see millions of trees and no forrest yet I can weed through details very skillfully.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by Mutant_Fruit
Out of interest, not knowing any php, wouldn't the technique described in the previous link (
http://www.tonymarston.net/php-mysql/good-bad-oop.html ) not tie you to implementation detail?
For example, suppose you wanted to change the internals to a dictionary, or a sorted list, or a linked list, or a hashtable, or seperate member variables, could you? I think not. However using properties in C# you can make those changes and the user of your code *does not care*.
Not following you .
Without details I'm pretty much deaf, dumb , and blind.
-
Re: What's with all the Get/Set lines?
Quote:
I just use them masterfully
I like the modesty in that. :D :D
Quote:
I LIKE doing the validation WHERE the values gets assigned
and
Quote:
EFFICIENCY & CONDENSATION
So what happens if you assign to the variable multiple times in the code ? Do you do the same validation at every point ? And what happens if something in the validation changes - or there's a bug you need to fix. Do you have to fix it in the x number of copied and pasted pieces of code ? Can you remember EVERYWHERE where you assign to the variable ?
Personally I work on the principle of never write the same code twice. That's pretty efficient and condenses the code down nicely. And fewer lines of code = fewer bugs I've found.
Doing validation everywhere you set a variable is, I would say, neither efficient nor condenses the code. In fact you'd end up with validations just about everywhere making the code very hard to read...
So that's a big thumbs up :thumb: for encapsulation from me. In the long run it makes my life so, so, so much easier. And anyone elses life who has to work on code I've written too....
I've found that just because you can do something you shouldn't necessarily do it. I could make every variable in my applications public and global but I don't. Just as I can walk across any road anytime I want : but I don't because otherwise a big lorry will come along and squash me.
Darwen.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by darwen
I like the modesty in that. :D :D
Well, lets just say there's no conceit in my family, I have it all. :p
Quote:
Originally Posted by darwen
So what happens if you assign to the variable multiple times in the code ? Do you do the same validation at every point ? And what happens if something in the validation changes - or there's a bug you need to fix. Do you have to fix it in the x number of copied and pasted pieces of code ? Can you remember EVERYWHERE where you assign to the variable ?
Good point, good questions. Let's talk. The vars in my app are populated two ways mainly. 1. user 2. from external library. I do it at those to entry points and the rest of the program is basically shuffling it around so I don't need to validate in very many places. Most validation changes occur at the same points and is usually due to a vendor changing their data sturcture on us or a user getting creative in a way we never imagined.
And no I don't do this a lot even though I may get facetious about it. I make most vars local in scope of a function but if multiple functions need it I make them members.
Quote:
Originally Posted by darwen
Personally I work on the principle of never write the same code twice.
Exactly! Whenever possible I make a separate function that is called by various routines so so the code in that function , such as Validate(), is only written once. But get/set for each var, this seems like overkill even though I know you can do a lot with that.
So mostly i just want to declare a var (lots of them), use it, assign it, and get from it without the 12 lines.
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
Sorry getting a little overwhelmed with the plethora of ideas coming in here.
Let me see if I can address most of them here.
Btw I didn't get your 100000 example.
Suppose you're writing a card game library. You only want to allow a player to switch cards 3 times. If you make your NumberOfSwitchesAllowed variable public, the user can just write: NumberOfSwitchesAllowed = 100000 and they'll get a royal flush every time because they'll just keep switching.
This is the (common enough) situation where public variables suck.
Code:
I just use them masterfully the way I see fit.
Fair enough, now what happens when your company hires a new guy to maintain your code and he doesn't understand your masterful plan and instead sees 200 global variables and hasn't a clue which of them belong to which class, what sanity checks need to be performed every time he assigns a value to them and suchlike. Which brings me on to this point:
Quote:
My thoughts about doing the validation within the property bothers me because I LIKE doing the validation WHERE the values gets assigned. Not in a property in a galaxy far far away.
You're right. I like doing validation only where the values get assigned. The value is *only* assigned in the property. So that's where the validation goes. For example, consider this property
Code:
private int m_Month;
public int Month {
get { return m_Month; }
set {
if (value > 12 || value < 1)
throw new Exception("Invalid Month");
m_Month = value;
}
}
That's 9 lines, including all validation. Now, there is no chance in hell that i could *ever* forget to validate the value. Everywhere else in my code i can just call: Month = myInt and i'm guaranteed Month will never take on an invalid value.
With a public variable i'd be forced to duplicate these two lines every time i want to set a value to Month:
Code:
if (value > 12 || value < 1)
throw new Exception("Invalid Month");
Of course, you hate code duplication (as do i) which is why i'm sure you'd much prefer to only have your validation in one easy to edit place! Now suppose in the future you want to change the valid months to exclude December, in my version you have to change 1 character. In your version you'd have to change 1 character many times, with the chance of accidentally missing one point where it was used.
If you can't understand the advantages to this method, then fair enough, it's not our fault, we've tried explaining using many simple examples. You might be better off getting a beginners book to OOP which may explain it better than us.
EDIT: Can i point out that a get/set does not take 12 lines. It takes 9 including validation. You can place your brackets wherever the hell you want and liberally add whitespace and make a get/set take 30 lines, but it still doesn't make it bloat.
Finally, AutomaticProperties reduce the code to just:
Code:
// This code allows public getting, but only internal functions can
// actually set the value. So public users see a GET only
// internally you have get and set
public int MyInt { get; internal set;}
-
Re: What's with all the Get/Set lines?
I certainly woulden't want to be this guys co-worker :)
Make variables wherever you want. You don't have to use get/set.
Code:
public int myPublicInt = 0;
Then use the = operator wherever you like.
Code:
myClass.myPublicInt = 0;
-
Re: What's with all the Get/Set lines?
Quote:
Originally Posted by alan93
Exactly! Whenever possible I make a separate function that is called by various routines so so the code in that function , such as Validate(), is only written once. But get/set for each var, this seems like overkill even though I know you can do a lot with that.
So mostly i just want to declare a var (lots of them), use it, assign it, and get from it without the 12 lines.
maybe this is a stupid question, but why use C# at all? using the logic you've been talking about: String.Length is pointless because I can call strlen("some string") and its better because I have a function that manipulates a string and isnt only available as a member on a string type. lets not wrap up string functionality in a string object, because one can write some global function that can do everything you need for you, and makes your data types more compact.
if this is the prevailing logic, then standard C is going to your best bet, not some language that runs in a framework, contains a lot of pointless code (I had a professor in school that complained about the STL because it was too bloated. He was a retired asm developer.) and functionality that doesn't fit your style.
I work with people who think just like you, and our code base is literally 3 to 4 times larger than it needs to be because instead of utilizing encapsulation, inheritance / polymorphism, they write one class to hold the data, another to modify the data, and another to persist it and in some cases a class that wraps the original data type (with the public members) for a "object oriented" feel to the class.
personally, that kind of design drives me mad. it is expensive to maintain, monotonous to code against, almost impossible to extend and doesn't follow any of the best practices that can make development more cost efficient.