Why would someone use Private get set over a Puplic Variable? - c#

I had a Problem lastly while i was working in Unity
I had a public Variable hidden in the Editor
this caused me some Proplems which i reported as Bug
because for me it looked like one
I did it like this:
public bool Variable_1 = true;
The Unity Support member than said to me that nothing is wrong with my Code but i should do it like this because this would be prefered:
private bool Variable_1{
get
{
return this.Variable_1;
}
set
{
this.Variable_1 = value;
}
}
public void Set_Variable_1(bool bool){
this.Variable_1 = bool;
}
I wanted to make it public because i want to access it from a other class
So my Question is why would some one use the second Example Code over the first one. What is the Advantage of that?
Because in my eyes the first example is much simpler and takes less lines
[Edit] 21.7.17: I understand that getter and setter Methods are much more flexible but in this case it won't be needed.
Thanks for taking the Time and Reading this Post.
Have a nice Day and keep Coding
[Edit] 21.7.17:
Also i like to point out that i teached Programming myself so i didn't look into set and get till now. I tried to understand the example from this site www.dotnetperls.com/property which is ruffly the same as my Example now. I don't know how good this site is but i understood it best there

There´s indeed no reason to make the field a private property and set its value by a public setter-method. Instead you should create a property with a public getter and setter.
public bool Variable_1 { get; set; }
Apart from this none of your two solutions is a good idea, a public field enables anyone to set the value to any value, making it impossible to perform any validation on the new value. This of course also applies to an auto-implemented property like the above. However if you decide some time to do implement some validation any existing client-code won´t be affected as the public API stays the same. Doing this with a public field on the other side would be a breaking change, as you´d replace a field by a property.
The second one however is overcomplicated and does not provide any advantage.

Related

Plain attribute or attribute with field?

I see a lot of code snippets with this example:
private string _possessor;
public string Possessor
{
get { return _possessor; }
set { _possessor = value; }
}
My questions is, why not just use plain property as in:
public string Possessor { get; set; }
I was reading on the internet, but could not really see the difference? You can either way set values in both examples and second example requires less coding and looks cleaner.
In the case that you are showing, it's true, there are no differences on doing each approach and the second one is cleaner. Knowing the first approach is useful because sometimes you need a property to do more than just get/set so in that case you will need to use the first approach.
You can also see here that with each new c# version, different ways of implement properties were created. The second approach is Auto-implemented properties
The main purpose of doing this is to help achieve data Encapsulation, which helps us by hidden the data in a class from other classes. this is also known as data-hiding.
Another good reason why this is done is when there some special validation or special business rules that needs to be checked before we set that particular value.
You can read more on Encapsulation from this site https://www.geeksforgeeks.org/c-sharp-encapsulation/

Is it bad practice to use accessors from within a class? [duplicate]

This question already has answers here:
Accessing members in your own class: use (auto)properties or not?
(5 answers)
Closed 9 years ago.
So I have a simple class, User, which is something like this (ignore horrible whitespace use, wanted to keep it brief to read online):
public class User
{
private string username;
public string Username
{
get
{
return username;
}set{
if(Validate.usernameIsValid(value)){username = value;}
else{throw new InvalidArgumentException("Username is invalid");}
}
}
//some more fields
public User(String argUsername)
{
this.Username = argUsername;
//OR validate again before:
username = argUsername;
}
}
Is it better to use the public accessor within the class to use its validation? Or is that bad practice and in that case, should I re-validate before setting the private username field?
I'd recommend using the public setter over local setting of the variable, simply because there'll be one place - the setter - where all the logic related to validation is handled. But this is only effective if you follow this convention every where within the class and all the derived versions strictly.
One cannot assume that a member variable is not manipulated elsewhere in the class ( or its derived versions, if it is protected). Imagine another programmer debugging an error related to username validation. It can be a pleasant surprise to find out upon search, that all validations take place via the setter - so she doesn't haven't to debug multiple validation logic.
The answer depends on where the data is coming from. Since the driving point behind using a setter is to avoid duplicating your validation code, you have two basic cases:
When the data is coming from outside your class (i.e. through a method parameter, as in your example) then you should call the setter, which would perform validation for you.
When the data has been "sanitized" at the point where you are ready to assign, go straight to the variable, bypassing the validation.
The former case extends to situations where you read user input.
The later case includes situations where you restore object's state from a snapshot, or generate object's state internally. For example, if your setter has null/empty string validation, and your method wants to set the string to a string representation of a GUID, it's OK to skip the setter.
In most cases I use the public property because what is done there usualy needs to be done all the time. But there are exceptions (for example if validations needs to be done once). So you can't really can't tell in general.
Using public accessors within a class is OK, as well as using any public method. (After all, properties are just syntax sugar for getter/setter methods.)
Using accessors internally might be preferred if accessing a property from within a class has the same semantics as accessing it from outside.
In addition, accessors bring a consistent way to deal with regular and auto-implemented properties. (Auto-implemented ones just do not expose backing fields explicitly.)
Also, outside of constructors, almost for sure, accessors should be used for virtual properties.
Direct use of backing field is needed rather for back-door property manipulations.
But there is no general rule which approach to choose.
actually you have done well, self encapsulate fields make you set the value of property based on your needs easily: for example take a look at this:
private readonly ProductManufacturer _productManufacturer = new ProductManufacturer();
private readonly IList<ProductCategory> _productCategories = new List<ProductCategory>();
public ProductManufacturer ProductManufacturer
{
get { return _productManufacturer; }
}
public IEnumerable<ProductCategory> ProductCategory
{
get { return _productCategories; }
}
now you can get the list of product category list else where, or you can only do some other operation on product category like this:
public void AddProductCategory(ProductCategory productCategory)
{
_productCategories.Add(productCategory);
}
for more information about self encapsulate fields take a look at this:
http://www.refactoring.com/catalog/selfEncapsulateField.html

Parameters and Constructors

I've read a lot of detailed things throughout Stack Overflow, Microsoft Developer Network, and a couple of blogs. The general consensus is "A Constructor shouldn't contain large quantities of parameters." So encountering this got me thinking-
Initial Problem: My application contains around fifteen variables that are constantly being used throughout the application. The solution I came up with is I'll create a single class that will inject the values to the Properties.
So this seemed to work quite well, it made my life quite easy as I could pass the object into another class through the Constructor without having to assign all these variables to each method. Except this lead to another issue-
public class ServerParameters
{
// Variable:
private string template;
private string sqlUsername;
private string sqlPassword;
private string sqlDatabase;
private string sqlServer;
public ServerParameter(string _template, string _sqlDatabase, string _sqlServer,
string _sqlUsername, string _sqlPassword)
{
template = _template;
sqlUsername = _sqlUsername;
sqlPassword = _sqlPassword;
sqlDatabase = _sqlDatabase;
sqlServer = _sqlServer;
}
// Link the private strings to a group of Properties.
}
So already this Constructor has become significantly bloated- But now I need to implement even more Parameters.
Problem Two: So I have a bloated Constructor and by implementing other items that don't entirely fit with this particular Class. My solution to this, was to create a subclass or container to hold these different classes but be able to utilize these classes.
You now see the dilemma, which has aroused the all important question- When you can only inherit once, how can you build a container that will hold all of these subclasses?
And why shouldn't you use so many parameters in a Constructor, why is it bad exactly?
My thought on how to implement a Container but I feel like I'm doing it wrong- Because I constantly get Null Reference Exception when I try to use some of these Parameters.
public class VarContainer
{
private ServerParameter server;
private CustomerParameter customer;
public VarContainer(ServerParameter _server, CustomerParameter _customer)
{
server = _server;
customer = _customer;
}
}
I'm assuming it is because the internal class itself isn't actually getting those assigned variables, but I'm completely lost on the best approach to achieve my goal-
The main intent of "don't do work in your constructor" is to avoid side effects where you create an object and it does a significant amount of work that can impact global state unexpectedly or even take a long time to complete which may disrupt the caller's code flow.
In your case, you're just setting up parameter values, so this is not the intention of "don't do work", since this isn't really work. The design of your final container depends on your requirements - if you can accept a variable list of properties that are set on your class (or struct) then perhaps an initializer when you construct the object is more appropriate.
Assuming that you want all of your properties from the get go, and that you want grouping like you called out in the question, I would construct something similar to:
public class Properties
{
public ServerProperties Server { get; private set; }
public CustomerProperties Customer { get; private set; }
public Properties(ServerProperties server, CustomerProperties customer)
{
Server = server;
Customer = customer;
}
}
I'm leaving the implementation of ServerProperties and CustomerProperties to you, but they follow the same implementation pattern.
This is of course a matter of preferences but I always give my constructors all the parameters they need so that my objects has basic functionality. I don't think that 5 parameters is bloated and adding a container to pass parameters adds much more bloat in my opinion than adding a few more parameters. By new bloat I mean that you will probably have a new file for that, with new classes and new imports. Calling code has to write more using directives and link to correct libraries which needs to be exported correctly as well.
Adding a wrapping class for parameter masks the real problem, that your class might be too complicated, it does not solve it and generally aggravates it.
You can have any amount of parameters you want in a constructor. It's just that if you have too many (how many is too much? that's really subjective), it gets harder and harder to make a new instance of that class.
For example, suppose you have a class with 30 members. 27 of them can be null. If you force it to receive a value for each member in the constructor, you'll get code like this:
Foo bar = new Foo(p1, p2, p3, null, null, null, null, null, null /*...snip*/);
Which is boring to write and not very readable, where a three parameter constructor would do.
IMO, this is what you should receive in your constructors:
First, anything that your instance absolutely needs in order to work. Stuff that it needs to make sense. For example, database connection related classes might need connection strings.
After those mentioned above, you may have overloads that receive the stuff that can be most useful. But don't exagerate here.
Everything else, you let whomever is using your code set later, through the set accessor, in properties.
Seems to me like you could use dependency injection container like Unity or Castle Windsor.

Are automatic properties for private variables unnecessary?

I was look at somebody else's code and came across this piece of code
private string _deviceName { get; set; }
private string _deviceAlias { get; set; }
My thinking is that those automatic properties for private variables are unnecessary. Am I right in thinking so ?
My thinking is that those automatic properties for private variables are unnecessary. Am I right in thinking so ?
They aren't necessary, but they also don't really hurt anything. That being said, they don't really help anything either, as they're purely an implementation detail, so switching from a field to a property later wouldn't be a breaking change.
The only real reason to potentially do this would be if you knew, in the future, you would want custom logic on get or set, and you were using something that required the syntax to be different for properties, such as reflection. In this case, making them auto-properties now would prevent any need for changing the code later.
Its just that instead of creating a variable, you created a property on which in future you want some custom work while setting and retrieving value.

c# properties with repeated code

I have a class with a bunch of properties that look like this:
public string Name
{
get { return _name; }
set { IsDirty = true; _name = value; }
}
It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I can write my properties something like this and still get the same behaviour:
[MakesDirty]
public string Name { get; set; }
No. Not without writing considerably more (arcane?) code than the original version (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.
MS has the same need for raising events when a property is changed. INotifyPropertyChanged that is a vital interface for change notifications. Every implementation I've seen yet
does
set
{
_name = value;
NotifyPropertyChanged("Name");
}
If it was possible, I'd figure those smart guys at MS would already have something like that in place..
You could try setting up a code snippet to make it easy to create those.
If you really want to go that way, to modify what the code does using an attribute, there are some ways to do it and they all are related to AOP (Aspect oriented programming). Check out PostSharp, which is an aftercompiler that can modify your code in a after compilation step. For example you could set up one custom attribute for your properties (or aspect, how it is called in AOP) that injects code inside property setters, that marks your objects as dirty. If you want some examples of how this is achieved you can check out their tutorials.
But be careful with AOP and because you can just as easily create more problems using it that you're trying to solve if not used right.
There are more AOP frameworks out there some using post compilation and some using method interception mechanisms that are present in .Net, the later have some performance drawbacks compared to the first.
No, when you use automatic properties you don't have any control over the implementation. The best option is to use a templating tool, code snippets or create a private SetValue<T>(ref T backingField, T value) which encapsulates the setter logic.
private void SetValue<T>(ref T backingField, T value)
{
if (backingField != value)
{
backingField = value;
IsDirty = true;
}
}
public string Name
{
get
{
return _name;
}
set
{
SetValue(ref _name, value);
}
}
The other alternative might be a code generator such as codesmith to automate creating the properties. This would be especially useful if the properties you are creating are columns in a database table
I can recommend to use Enterprise Library for that purpose. Policy Application Block delivers the infrastructure to do "something" (something = you can code that on your own) whenever you enter/exit a method for example. You can control the behavior with attributes. Take that as a hint an go into detail with the documentation of enterprise library.
There's a DefaultValueAttribute that can be assigned to a property, this is mainly used by the designer tools so they can indicate when a property has been changed, but, it might be a "tidy" way of describing what the default value for a property is, and thus being able to identify if it's changed.
You'd need to use Reflection to identify property changes - which isn't actually that expensive unless you're doing lots of it!
Caveat: You wouldn't be able to tell if a property had been changed BACK from a non-default value to the default one.
I'd say that the best way of solving this is to use Aspect-Oriented Programming (AOP). Mats Helander did a write up on this on InfoQ. The article is a bit messy, but it's possible to follow.
There are a number of different products that does AOP in the .NET space, i recommend PostSharp.
If you do go with Attributes, I'm fairly certain you'll have to roll your own logic to deduce what they mean and what to do about them. Whatever is using your custom class objects will have to have a way of performing these attribute actions/checks, preferably at instantiation.
Otherwise, you're looking at using maybe events. You'd still have to add the event to every set method, but the benefit there would be you're not hard-coding what to do about dirty sets on every property and can control, in one place, what is to be done. That would, at the very least, introduce a bit more code re-use.
ContextBound object. If you create a class that extends context bound object and you create a ContextAttribute you can intercept the calls made to such a property and set the IsDirty. .NET will create a proxy to your class so all calls go over something like a remoting sink.
The problem with such an approach though is that your proxy will only be invoked when called externally. I'll give you an example.
class A
{
[Foo]
public int Property1{get; set;}
public int Property2{get {return variable;} set{ Property1 = value; variable = value; }
}
When property1 is called from another class, your proxy would be invoked. But if another class calls property2, even though the set of property2 will call into property1 no proxy will be invoked, (a proxy isn't necessary when you're in the class itself).
There is a lot of sample code out there of using ContextBoundObjects, look into it.

Categories

Resources