Cost of small method calls in C# and optimization - c#

I was wondering what the overhead of calling short methods were or if the code would get optimized either way and if it was different than the cost of getters?
I'll just give an example because it is hard to explain.
I have a ClaimsManager for a website that gets particular claims and returns them. The process for getting one claim from another differs only by a ClaimsType string.
public string GetClaimValueByType(string ClaimType)
{
return (from claim in _claimsIdentity.Claims
where claim.ClaimType == ClaimType
select claim.Value).SingleOrDefault();
}
/*Again would this be better or worse if I wanted to be able to choose if
I want the claim versus the value?
public Claim GetClaimByType(string ClaimType)
{
return (from claim in _claimsIdentity.Claims
where claim.ClaimType == ClaimType
select claim).SingleOrDefault();
}
public string GetClaimValueByType(string ClaimType)
{
return GetClaimByType(ClaimType).Value;
}
*/
public string GetEmail()
{
return GetClaimValueByType(ClaimTypes.Email);
}
/* Or should I use getters?...
public string Email
{
get
{
return return GetClaimValueByType(ClaimTypes.Email);
}
}
*/
So is this bad practice to have these short get methods? Should there be a large call overhead because it is so short or will this be optimized? Finally, does it make more sense to actually use getters here?..
Thanks

In my opinion, what ever marginal overhead there may be with using setters and getters is outweighed by the clean and more easily maintainable code that would most likely be easier for any .NET developer off the street to pick up and run with.
But I guess it also depends on how huge your Claim object is. :)

Performance wise there is no difference between a getter and a method. A getter is just syntactic sugar, and is converted to a method during compilation. There are some general guidelines as to when to use a getter and when to use a method. This msdn page advices to use a method instead of a property when:
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.

I wouldn't use a getter for this, properties are intended to return a constant value. This means that that sequenced calls should return the same value. This is just a conceptual thing.

Related

Using a lot of hardcoded strings in code

When I am looking at my code and I am writing things like..
if (role == "Customer")
{
bCustomer = true;
}
else if (role == "Branch")
{
bIsBranch = true;
}
Or
foreach(DataRow as row in myDataSet.Tables[0].Rows)
{
row["someField"]=somefield.Tostring()
}
Are you guys doing this? When is this ok to do and when shouldn't you be doing this? What if any would be a better approach to write this if any?
Thanks For the Comments: I guess I should add what if (for this example purposes) I am only using this role comparison once? Is it still a better idea to make a whole new class? Also should I have 1 class called "constants" are multiple classes that that hold specific constants, like "roles" class for example?
No. Don't use "magic strings". Instead create a static class with constants, or an enum if you can.
For example:
public static class Roles
{
public const string Customer = "Customer";
public const string Branch = "Branch";
}
Usage:
if (role == Roles.Customer)
{
}
else if (role == Roles.Branch)
{
}
Here's a good discussion on various solutions.
It is always better to declare the hard coded strings separately as constants rather then declaring a new string every time. It keeps code clean and reduce errors which are caused by typing mistakes.
Regarding should or shouldn't be done totally depends on scenario.
I would make a Roles static class:
public sealed class Roles
{
public const string BRANCH = "Branch";
public const string CUSTOMER = "Customer";
public static bool IsCustomer(string role)
{
return role == CUSTOMER;
}
}
Then in your code:
bCustomer = Roles.IsCustomer(role);
Alternatively, this requires a little more setup but the RoleProvder (depending on Web or Not) provides a lot of good methods.
I believe a better approach is to use application settings which means you won't ever need to recompile your code if "Customer" or "Branch" values change. Magic values are obviously bad, and this would be a good first step/option getting away from them. Additionally it keeps your values in one place, and I also believe you can reload the settings at runtime without restarting the application (although I haven't tried this myself).
E.g.:
if (role == Properties.Settings.Default.CustomerRole)
{
bCustomer = true;
}
else if (role == Properties.Settings.Default.BranchRole)
{
bIsBranch = true;
}
Eliminate the use of magic strings in your C# code by using the nameof expression
Using the nameof expression, you can retrieve the literal casing of types, classes, structs, properties, methods, functions, fields, arguments, parameters, locals, and more to the casing they appear in the code at compile time. This will not eliminate or solve all your "magic string" problems, but its a good start and worth discussing.
For example, getting the literal casing of an enum value.
public enum ExportType
{
CSV,
Excel
}
nameof Usage
nameof(ExportType.CSV); // "CSV"
nameof(ExportType.Excel); // "Excel"
nameof(ExportType); // "ExportType"
Returns the literal casing of the expression in the argument.
No more "magic strings"
If you are referring the code names of specific type names, classes, etc., strongly consider replacing those fragile magic strings with nameof. You will not fear changing the name of a internal type, or property without fear of breaking the code. Using renaming features IDEs like Visual Studio has will rename all references anywhere in your code base referring to that expression.
Type Safety
This operation is done at compile time. Ultimately, if you are relying on the names of types, classes, etc. in your code, you can introduce compile time type safety via nameof expression into your code when referring to them.
Performance
You can eliminate a lot of reflection in your code as well that gets the names of these objects or types.
Caveats
Getting the name of generic types
nameof(T); // "T"
nameof(TEntity); // "TEntity"
In these cases, you must continue to use reflection to get the name of the type at runtime. typeof(T).Name.
For example:
var enumValuesNames = typeof(ExportType).GetProperties().Select(p => p.Name).ToArray();
Polimorphism is one thing, but using hardcoded strings along your code is not good at all. It's way better to define a variable holding the string and use this variable along the code. This case if you need to change something (believe me you will), you can just change the value of this variable and it's done (less errors too!)
For the sake of maintainability, you should formalize string comparators when possible, either as named constants or as an enumeration. The benefit for the programmer is that you can localize changes. Even when using a refactoring tool, finding all the places a string is used can be tedious and error prone. You may only have one place where you're doing this comparison today, but you or a future maintainer may extend this to other parts of the code. Also, the class itself may grow and need to be broken apart. These things tend to creep up on a program over time.
I would simply declare these strings as constants close to where they're used, but together. Don't bother with a new abstraction like Roles until you know you need it. If the number of roles you need to compare grows, or is needed outside of this class, then you can create a Roles enum or Roles class, depending on the complexity of the comparison.
Also, by using constants, you signal the intended use to the compiler, so you get some minor memory management benefits, which, given your comparison is in a loop, is generally a good practice.
Well, in my opinion it is up to you and it depends on your application design.
I uaully look at it from the positive side- if application works the way it supposed to work, it is all good. IMHO

In DDD, why they often make use of methods instead of properties?

In DDD examples I often see the use of methods where I would probably have used a property. Why is this?
For example (from Strengthening your domain: Aggregate Construction)
public class Order
{
public bool IsLocal()
{
return Customer.Province == BillingProvince;
}
}
One argument for choosing methods instead of properties is when there would be any code that does something. If it just returns some internal field value then use property. If it has any logic inside or does any calculation use method. This makes it clearer to client of code that there is something happening when you call this method.
I think I've read in CLR via CSharp that Microsoft regrets making DateTime.Now a property instead of method. It returns new value every time you call it. That should be method not property.
There are no reasons for replacing getters with methods specific to DDD. The general guidelines apply here (do that when a heavy computation is performed or state is changed).
Setters are a different case though. Some people even consider them a code smell. You should get suspicious each time you see a setter. In an ideal case the state of the object is changed only in methods whose names coincide with verbs in the domain.

return value style question

Lets say I have the following code
public static string GetXMLValue()
{
XDocument settingsFile = XDocument.Load("Settings.xml");
return settingsFile.Element("Settings").Element("GenericValue").Value;
}
It simply reads an XML Settings file and returns the GenericValue value. It can't be any simpler than that. Now my question is, would it provide any benifit (readability, performace, syntactically, maintainablitiy, etc.) to first place the return value in a string variable then return? Or is it best left the way it is?
To be honest, the simplicity of the methods makes it readable even in "one" line:
public static string GetXMLValue()
{
return XDocument
.Load("Settings.xml")
.Element("Settings")
.Element("GenericValue")
.Value;
}
There are a couple situations in which I see value in creating an auxiliary variable:
I want to assert something about it as a precondition (e.g. not empty string; a minimum/maximum length; etc.)
I am having trouble and I want to debug the value more easily.
Even in the absence of these, for such a nontrivial expression, I would create a local variable, to make the function more readable.
would it provide any benifit [...] to
first place the return value in a
string variable then return? Or is it
best left the way it is?
The function is so simple it just does not matter, so don't lose sleep about it. Once the function becomes more complex, you can always rethink this.
If for example you later need to run checks on the value before returning it, or want to log it for auditing reasons, a separate variable will make sense. Until then, leave it as it is.
As an aside:
What I find much more questionable is that you are reading an external resource (file) in a getter method. Invoking operations that can have side effects (such as reading a file) in a getter is bad style IMHO. That way for example every caller of the getter will have to handle IOExceptions from reading the file.
Consider changing this, for example by passing in the information via the constructor (either read the file from the constructor, or pass in an object that takes care of supplying the information). This will decouple your design, and simplify e.g. reuse and unit testing.
From a readability perspective, assigning the values to a variable and returning it would definitely help.

Method vs Property in C# - what's the difference [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Properties vs Methods
In method you can type some code and in properties too. For example I have a property Name. When class name changes I would like to get some data from database and change state of my object. I can add this code to set part of my property. Other solution is to change set part to private and add method called SetName and in this method add my code.
So what is the difference? When is the point when it's not good to put some code to getter / setter and when to create own method that is used to change my property and other parts of my class?
Here is a good set of guidelines for when to use properties vs methods from Bill Wagner (fixed link)
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.
Given a property like this
private string _name;
public string Name { get { return _name; } set { _name = value; } }
it is possible to write the following two methods:
public string get_Name() { return _name; }
public void set_Name(string value) { _name = value; }
which act identically. And in fact, this is exactly what the compiler does for you when you create a property.
Generally speaking, I steer away from properties when the code within them starts to feel "expensive", if that makes any sense. I want properties to feel like fields (with controlled side effects that happen at specific times), so they should be lightweight.
A property is nothing but some syntactic sugar.
In some cases, it is better to define a property instead of a method because it is clearer / more readable.
Design guidelines state that, when the functionality you're implementing is expensive, a method should be preferred over a property.
in fact, a property is implemented as one or two methods; depending whether your property has a setter or not. The property is translated into a get_xxx and a set_xxx method.
Coming to think of it, Properties are more than just syntactic sugar. They are the public face of your member data to you member code.
Thus, giving you a clean layer for retrieval or input of a single aspect of you member data from you code.
A DTO for example is nothing but a bunch of well written properties, cleaving data and behavior efficiently.
Without a DTO would you imagine tightly coupling your DataGrid or Dropdown to complex business logic method?
Put it simply, Methods are actually doing the work...Properties either instigate action or get the status.
Though, you can use method code inside your properties ...it is not what they are meant for. Even, if you have to you are better of making a clean call to another method inside the property instead of actually writing you code in it. HTH!
Whenever I've come across the need to put code in a getter/setter I put the code in a private method and call that method from within the getter/setter. That way the code is available in a method call should I need it elsewhere. Not sure if this is the answer you were seeking but it is just a methodology I use.
There is basically no difference (except for the reserved identifier "value" in a setter).
Getters and setters get internally translated into standard methods such that the runtime has no idea whether some getter or setter is associated with a certain property. The term syntactic sugar is often used for convenience constructs like these.
However, there is an important software engineering benefit: your code tends to be easier to understand if you restrict yourself to use getters and setters with get and set semantics. I.e. do only the steps necessary to provide the respective property.
A common use case for doing a bit of extra work is for instance the setting or getting of a property which is not directly backed by a member field. For example, you've got a class that contains say a value that represents a distance. Your class could provide two Properties: Kilometers and Miles with respective setters and getters. Then you would do simple conversions in one pair and save yourself to store the value twice.
As a general rule of thumb, you should not put any code in a getter that has side effects. Also, the only side effect that code in a setter should have is the change of state in the object the setter refers to.
Essentially a property is a couple of methods - getProperty and setProperty. It is only the convention / simplification of the thing.
It is assumed that property getter has no side effects (well - they might have certain side effect, like lazy loading).
This probably isn't the most important difference, but one of the differences is that the debugger can be configured to step over properties (assuming their code is trivial).

"Tell, don't ask": what is the difference between a non-void method and a getter?

How might I justify using a non-void method while not using any property getters? What is the distinction between these two concepts such that getters are evil but non-void methods are acceptable?
EDIT:
int CalculateSomething();
int Calculation { get; }
The fact that I can change the signature of CalculateSomething and pass values into it if I wanted to completely slipped my mind. So my question is changed to: Is the fundamental distinction between getters and non-void methods that arguments can be passed into non-void methods?
Microsoft has guidance for choosing between properties and methods.
Consider using a property if the member represents a logical attribute of the type.
Do use a property, rather than a method, if the value of the property is stored in the process memory and the property would just provide access to the value.
Do use a method, rather than a property, in the following situations.
The operation is orders of magnitude slower than a field set would be. If you are even considering providing an asynchronous version of an operation to avoid blocking the thread, it is very likely that the operation is too expensive to be a property. In particular, operations that access the network or the file system (other than once for initialization) should most likely be methods, not properties.
The operation is a conversion, such as the Object.ToString method.
The operation returns a different result each time it is called, even if the parameters do not change. For example, the NewGuid method returns a different value each time it is called.
The operation has a significant and observable side effect. Note that populating an internal cache is not generally considered an observable side effect.
The operation returns a copy of an internal state (this does not include copies of value type objects returned on the stack).
The operation returns an array.
Isn't the big difference, that you can't pass a variable to a getter?
a function:
private int Getyear(datetime date) { }
a property:
private DateTime GetDate {
get {return _date};
}
you can't do that with a getter property can you?

Categories