Related
public abstract class Unit
{
public abstract List<Move> allowedMoves{get;}
}
public class Javelineer : Unit
{
public List<Move> allowedMoves =>
new List<Move> {Move.Impale, Move.JavelinThrow, Move.ShieldBlock};
}
public class Dragon : Unit
{
public List<Move> allowedMoves =>
new List<Move> {Move.BreatheFire, Move.Swipe, Move.Bite, Move.Devour, Move.TailBash};
}
The X:
Given the above code, if and how can I retrieve the allowed moves of a given unit without necessarily instantiating a new object?
I know I can retrieve the property with this code:
typeof(Javelineer).GetProperty("allowedMoves")
But if and how can I retrieve the definition of this property?
The Y:
The client (web browser) must send the game server the player's unit. This includes the unit's type and moves this unit is able to perform (4 out of all available; similarily to Pokemon).
While the validation (of course) is performed on the server, the browser still needs to get a list of available unit types and allowed moves.
In order not to duplicate code, I would like to avoid hard-coding this data in Javascript.
Having read some excellent SO questions & answers I think I can retrieve all available units with code similar to this:
Assembly.GetExecutingAssembly().GetTypes().Where(
type => type.BaseType == typeof(Unit)
).Select(type => type.Name).ToList()
I'd call this code on server startup, cache the result and send the cached result to every connecting client, because I have feeling this code is likely expensive to call.
But how can I retrieve the list of allowed moves?
You have a couple of options, but TL;DR: Construct the object instance and read the property.
In any case, here are some options, creative minds might be able to find a couple more even.
Construct the instance, read the property.
This is your best option code-wise because it will be easy to understand, maintain, bugfix.
Rewrite the code to allow for easy detection of the values using reflection
One way to do this would be to use attributes, tagging the property or object with the legal moves. However, to avoid having the bug that the attributes does one thing, the code another, you might have to change the code to use the attributes as well, which would be a performance hit.
Additionally, reading those attributes would likely construct many more objects than your original object.
Use mono.cecil or some other IL-inspection library to decode the code of the property getter and finding the construction of that list, extracting the values being added to the list. You would essentially either have to dumb down the code of that property to be on par with what you have right now (and never allow it to become more complex) or basically simulate execution of code.
This is like constructing a flotilla of space warships with enough firepower to demolish a local starsystem, just to kill an ant.
Bottom line, construct the object instance, read the property.
What is the best way of initializing objects for properties without setters in C#?
For example I have property of type UserData and I can initialize it:
In constructor
In getter
private UserData _user;
public UserData User
{
get
{
return _user?? (_user= new UserData ());
}
}
Initialize field:
private UserData _user = new UserData()
I found few similiar threads:
Create an object in the constructor or at top of the class
C# member variable initialization; best practice?
But it is consideration between 1st and 3rd option - no one thinks about 2nd option - do you know way? From some time it is my preffered option to get objects, but I wonder if there are some cons that I don't know.
Could you tell me what is the best option and what problem could make use of 2nd option?
It all depends on what you want to do with it, so there is definite answer for that.
One difference between 1+3 and 2 is predictability.
With 1+3, you know exactly where your object is created and at which point during instantiation of your class. That can be desirable in some circumstances.
With 2, you depend on external influences (who accesses the property at which time) to initialize the field.
With the delayed creation in approach 2 (only create the object if needed), you could save some time when creating an object of the containing class.
If the UserData's creation takes a lot of time, like, when you have to query a database for it, you might want to delay its creation until really necessary. The object that contains the UserData object is constructed faster since it doesn't need to wait for the UserData object to be created. If the property isn't always accessed, you might even get to completely avoid creating a UserData instance.
If you're simply using plain data, initializing the backing field at its definition (if possible) is preferred:
// when you create constructor N+1, no worries about forgetting to set the value
private UserData _userData = new UserData();
public UserData User
{
get { return _userData; }
}
If you need initialization to be deferred, your best option is using Lazy<T>:
private Lazy<UserData> _userData = new Lazy<UserData>(() => new UserData());
public UserData User
{
get { return _userData.Value; }
}
The constructor for Lazy<T> contains overloads which can address your thread safety needs:
None: access from multiple threads is "undefined behavior"
PublicationOnly: the first thread to complete initialization "wins"
ExecutionAndPublication: locks ensure only one thread initializes the value
One issue with #2 is if the property could be accessed by multiple threads you could potentially create two copies of the UserData object. An additional consideration with #2 is if UserData is expensive to create you will be paying the cost of creating that object when the property is accessed rather than when the containing object is created. That may or may not be desirable depending on your use case.
In a question about Best practices for C# pattern validation, the highest voted answer
says:
I tend to perform all of my validation in the constructor. This is a must because I almost always create immutable objects.
How exactly do you create an immutable object in C#? Do you just use the readonly keyword?
How exactly would this work if you want to validate in the constructor of your Entity Framework generated model class?
Would it look like below?
public partial readonly Person
{
public Person()
}
The interesting question here is your question from the comments:
What kind of object would you have that you do not need to modify the values at some point? I'm guessing not a model class, correct? I've had to change the name of a person in my database - this wouldn't fit with this idea.
Well, consider things that are already immutable. Numbers are immutable. Once you have the number 12, it's 12. You can't change it. If you have a variable that contains 12, you can change the contents of the variable to 13, but you are changing the variable, not the number 12.
Same with strings. "abc" is "abc", and it never changes. If you have a variable that contains "abc", you can change it to "abcd", but that doesn't change "abc", that changes the variable.
What about a list? {12, "abc"} is the list that is 12 followed by "abc", and that list never changes. The list {12, "abcd"} is a different list.
And that's where things go off the rails. Because in C# you can do it either way. You can say that there is referential identity between those two lists if lists are allowed to mutate their contents without changing their identity.
You hit the nail right on the head when you talk about the "model". Are you modeling something that changes? If so, then it is possibly wise to model it with a type that changes. The benefit of that is that the characteristics of the model match the system being modeled. The down side is that it becomes very tricky to do something like a "rollback" functionality, where you "undo" a change.
That is, if you mutate {12, "abc"} to {12, "abcd"} and then want to roll back the mutation, how do you do it? If the list is immutable you just keep around both values and choose which one you want to be the "current" value. If the list is mutable then you have to have the undo logic keep around an "undo function" which knows how to undo the mutation.
As for your specific example, you certainly can create an immutable database. How do you change the name of someone in your immutable database? You don't. You create a new database that has the data you want in it. The trick with immutable types is to do so efficiently, without copying billions of bytes. Immutable data structure design requires finding clever ways to share state between two nearly-identical structures.
Declaring all fields readonly is a good step towards creating an immutable object, but this alone is not sufficient. This is because a readonly field can still be a reference to a mutable object.
In C# immutability is not enforced by the compiler. You just have to be careful.
This question has two aspects:
Immutable type when you instantiate object
Immutable type when EF instantiate object
The first aspect demands sturcture like this:
public class MyClass
{
private readonly string _myString;
public string MyString
{
get
{
return _myString;
}
}
public MyClass(string myString)
{
// do some validation here
_myString = myString;
}
}
Now the problem - EF. EF requires parameterless constructor and EF must have setters on properties. I asked very similar question here.
Your type must look like:
public class MyClass
{
private string _myString;
public string MyString
{
get
{
return _myString;
}
private set
{
_myString = value;
}
}
public MyClass(string myString)
{
// do some validation here
_myString = myString;
}
// Not sure if you can change accessibility of constructor - I can try it later
public MyClass()
{}
}
You must also inform EF about private setter of MyString property - this is configured in properties of enitity in EDMX file. Obviously there will be no validation when EF will materialize objects from DB. Also you will not be able to use methods like ObjectContext.CreateObject (you will not be able to fill the object).
Entity Object T4 template and default code generation create factory method CreateMyClass instead of constructor with paremeters. POCO T4 template doesn't generate factory method.
I didn't try this with EF Code first.
An immutable value object is a value object that cannot be changed. You cannot modify its state, you have to create new ones
Check out Eric Lippert's blog:
Kinds of Immutability
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/immutability-in-c-part-one-kinds-of-immutability
Have a look at
Immutable object pattern in C# - what do you think?
How exactly would this work if you want to validate in the constructor of your Entity Framework generated model class?
It wouldn't work in this context because EF requires the properties of the entity class be public otherwise it can't instantiate it.
But you're welcome to use immutable objects further in your code.
C# 9 is coming up with new feature names as Record. Init-only properties are great if you want to make individual properties immutable. If you want the whole object to be immutable and behave like a value, then you should consider declaring it as a record:
public data class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
The data keyword on the class declaration marks it as a record.
Reference: https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#records
#Eric Lippert Good comment, but in addition in answer to the question:
What kind of object would you have that you do not need to modify the
values at some point? I'm guessing not a model class, correct? I've
had to change the name of a person in my database - this wouldn't fit
with this idea.
Let's say you have a large datastructure and you want to query its information, but it's changing all the time. You need some kind of locking system to make sure that you don't say try and count the total in the system while somebody is depositing something from one place to another. (Say a warehouse management system)
And that's hard to do because these things always affect things in unexpected ways, the data changing under your feet.
What if you could freeze your large datastructure when you're not updating it, so that no memory can be altered and it is paused at a consistent state? Now when you want to change it again you have to copy the datastructure to a new place, and it's fairly large, so that's a downside, but the upside is you won't have to lock anything because the new copy of the data goes unshared until it has been updated. This means anyone at any point can read the latest copy of the datastructure, doing complex things.
So yep very useful concept if you hate dealing with concurrency issues and don't have too much data to deal with. (E.g. if 1MB of data and updating 10/sec that's 10MB of data being copied)
I have several entities that have calculated fields on them such as TotalCost. Right now I have them all as properties but I'm wondering if they should actually be methods. Is there a C# standard for this?
public class WorkOrder
{
public int LaborHours { get; set; }
public decimal LaborRate { get; set; }
// Should this be LaborCost()?
public decimal LaborCost
{
get
{
return LaborHours * LaborRate;
}
}
}
It's OK to use calculated properties rather than methods, as long as the calculation doesn't take a noticeable time
See Property usage guidelines
I think methods should perform actions on the object, typically change the state of the object. Properties should reflect the current state of the object even if the property is calculated. So you should keep your properties IMO.
I think they should all be properties. As long as it doesn't change the state of the object, I'm cool with it as a property.
Additionally, if I'm using your class for data binding (WPF, etc.), then I can bind directly to your property without having to modify/extend the class.
If they are a) lightweight and b) have no side effects, I would make them Properties.
Lightweight is a bit fuzzy of course, but the rule of thumb is: If I ever have to worry calling a Property (be it in a loop or anywhere else), it should possibly be a method.
I would leave them as properties. But there's not "standard" reason to do things one way or another. If you're by yourself, do whatever you like best. If you're on a team, then follow conventions the rest of your team are following.
If a property is particularly expensive to calculate, I might change it to a GetWhatever() method. This serves as a hint to whoever uses my class that this value requires some significant work to arrive at, and the caller should cache the value rather than calling the method multiple times.
Trivial calculations are perfectly appropriate inside of properties.
In my opinion, it's a preference; it's what you want to do. I do propreties in most cases, unless there is logic involved. Additionally, if you need to pass in parameters to change the functionality then obviously a method would apply...
Depends, if your "properties" become mammoths and require a whole slew of business logic they shouldn't be properties, there should be a method.
The example you posted looks ok to be a property. No standard way of doing it, go with your gut instinct; if it looks like it needs to do a lot you probably need a method.
It's largely just syntactic sugar anyway, so do want you is convention in your team, or what you prefer, as long as it is just returning information about the object and not changing it or interacting with other objects.
MSDN gives information about this here
Class library designers often must
decide between implementing a class
member as a property or a method. In
general, methods represent actions and
properties represent data.
Which one do you think it is? An action calculate/getLaborCost or data?
WorkOrder workOrder = new WorkOrder();
workOrder.LaborHours = 8;
workOrder.LaborRate = 20;
decimal cost = workOrder.LaborCost; // This is OK here
but if you are going to do this for the same object also:
worOrder.LaborHours = 18;
decimal newCost = workOrder.LaborCost
Now this cannot be a property. It would be a lot better to be a method.
Sometimes, you have to consider also what you're modeling... On some domains, the calculated values are often or expected to be an attribute of the model -- a Property. If this were the case, then write it as a Property even though the calculation is not at all trivial or a little bit expensive to compute. Just document it on your API or implement some caching mechanism to minimize recomputation for this property.
Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?
We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:
public void SetLabel(string text)
{
Label.Text = text;
}
In the example, Label is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.
I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given.
From the Choosing Between Properties and Methods section of Design Guidelines for Developing Class Libraries:
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.
Yes, if all you're doing is getting and setting, use a property.
If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.
In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how you do it (or how your team does it).
They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.
Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property.
Searching through MSDN, I found a reference on Properties vs Methods that provides some great guidelines for creating methods:
The operation is a conversion, such as Object.ToString.
The operation is expensive enough that you want to communicate to the
user that they should consider caching
the result.
Obtaining a property value using the get accessor would have an observable
side effect.
Calling the member twice in succession produces different results.
The order of execution is important. Note that a type's properties should
be able to be set and retrieved in any
order.
The member is static but returns a value that can be changed.
The member returns an array. Properties that return arrays can be
very misleading. Usually it is
necessary to return a copy of the
internal array so that the user cannot
change internal state. This, coupled
with the fact that a user can easily
assume it is an indexed property,
leads to inefficient code.
If you're setting an actual property of your object then you use a property.
If you're performing a task / functionality then you use a method.
In your example, it is a definite property being set.
If however, your functionality was to AppendToLabel then you would use a method.
Properties are a way to inject or retrieve data from an object. They create an abstraction over variables or data within a class. They are analogous to getters and setters in Java.
Methods encapsulate an operation.
In general I use properties to expose single bits of data, or small calculations on a class, like sales tax. Which is derived from the number of items and their cost in a shopping cart.
I use methods when I create an operation, like retrieving data from the database. Any operation that has moving parts, is a candidate for a method.
In your code example I would wrap it in a property if I need to access it outside it's containing class:
public Label Title
{
get{ return titleLabel;}
set{ titleLabel = value;}
}
Setting the text:
Title.Text = "Properties vs Methods";
If I was only setting the Text property of the Label this is how I would do it:
public string Title
{
get{ return titleLabel.Text;}
set{ titleLabel.Text = value;}
}
Setting the text:
Title = "Properties vs Methods";
Symantically properties are attributes of your objects.
Methods are behaviors of your object.
Label is an attribute and it makes more sense to make it a property.
In terms of Object Oriented Programming you should have a clear understanding of what is part of behavior and what is merely an attribute.
Car { Color, Model, Brand }
A car has Color, Model and Brand attributes therefore it does not make sense to have a method SetColor or SetModel because symantically we do not ask Car to set its own color.
So if you map the property/method case to the real life object or look at it from symantic view point, your confusion will really go away.
You need only look at the very name... "Property". What does it mean? The dictionary defines it in many ways, but in this case "an essential or distinctive attribute or quality of a thing" fits best.
Think about the purpose of the action. Are you, in fact, altering or retrieving "an essential or distinctive attribute"? In your example, you are using a function to set a property of a textbox. That seems kind of silly, does it not?
Properties really are functions. They all compile down to getXXX() and setXXX(). It just hides them in syntactic sugar, but it's sugar that provides a semantic meaning to the process.
Think about properties like attributes. A car has many attributes. Color, MPG, Model, etc.. Not all properties are setable, some are calculatable.
Meanwhile, a Method is an action. GetColor should be a property. GetFile() should be a function. Another rule of thumb is, if it doesn't change the state of the object, then it should be a function. For example, CalculatePiToNthDigit(n) should be a function, because it's not actually changing the state of the Math object it's attached to.
This is maybe rambling a bit, but it really boils down to deciding what your objects are, and what they represent. If you can't figure out if it should be a property or function, maybe it doesn't matter which.
Properties should only be simple set and get one liners. Anything more and it should really be moved to a method. Complex code should always be in methods.
I only use properties for variable access, i.e. getting and setting individual variables, or getting and setting data in controls. As soon as any kind of data manipulation is needed/performed, I use methods.
As a matter of design Properties represent Data or Attributes of class object, While methods are actions or behaviors of class object.
In .Net, world there are other implications of using Properties:
Properties are used in Databinding, while get_ / set_ methods are not.
XML serialization user properties as natural mechanism of serilization.
Properties are accessed by PropertyGrid control and intern ICustomTypeDescriptor, which can be used effectively if you are writing a custom library.
Properties are controlled by Attributes, one can use it wisely to design Aspect Oriented softwares.
Misconceptions (IMHO) about Properties' usage:
Used to expose small calculations: ControlDesigner.SelectionRules's get block runs into 72 lines!!
Used to expose internal Data structures: Even if a property does not map to an internal data member, one can use it as property, if its an attribute of your class. Viceversa, even if its an attribute of your class properties are not advisable, to return array like data members (instead methods are used to return deep copy of members.)
In the example here it could have been written, with more business meaning as:
public String Title
{
set { Label.Text = text; }
}
Also big plus for Properties is that value of property can be seen in Visual Studio during debugging.
I prefer to use properties for add/set methods with 1 parameter. If parameters are more, use methods.
Properties are really nice because they are accessible in the visual designer of visual studio, provided they have access.
They use be used were you are merely setting and getting and perhaps some validation that does not access a significant amount of code. Be careful because creating complex objects during validation is not simple.
Anything else methods are the preferred way.
It's not just about semantics. Using properties inappropriate start having weirdness occur in the visual studio visual designer.
For instance I was getting a configuration value within a property of a class. The configuration class actually opens a file and runs an sql query to get the value of that configuration. This caused problems in my application where the configuration file would get opened and locked by visual studio itself rather than my application because was not only reading but writing the configuration value (via the setter method). To fix this I just had to change it to a method.
Here is a good set of guidelines for when to use properties vs methods from Bill Wagner
Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
They should be settable in any order
The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
Use a method if the member returns an array.
Repeated calls to the getter (without intervening code) should return the same value.
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.
*Taken from my answer to a duplicate question.
This is simple.
1: use property when you want your data should be validated before storing in field. So in this way property provides encapsulation for your fields. Because if you leave your fields public end user may assign any value which may or may not be valid as per your business requirement like age should be greater than 18. So before value is store corresponding field we need to check its validity. In this way properties represent data.
2: Use method when you want perform some action like you are supplying some data as parameter and your method is doing some processing on the basis of supplied values and returning processed value as output. Or you want to change value of some field by this calculation. "In this way method represents action".
I come from java an i used get.. set.. method for a while.
When i write code, i don't ask to my self: "accessing this data is simple or require a heavy process?" because things can change (today retrive this property is simple, tomonrow can require some or heavy process).
Today i have a method SetAge(int age) tomonrow i will have also method SetAge(date birthdate) that calculate the age using the birthdate.
I was very disappointed that the compiler transform property in get and set but don't consider my Get... and Set.. methods as the same.