Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm working on a project that was made by another developer, and I've been assigned the job to add extra functionality, although this question isn't about one application, it's about a language.
In C#, I find myself running across this probably around 50 times a day, I need to grab a value from a method and store it to a variable, or I need to store a variable, or even if I just need to hard code a variable to something.
Do I go with my head or my heart? My head says store it in a variable incase I need to use it more than once in the future, but then my heart says lets be lazy and just add it to the if check, instead of calling the variable, let me give you an example...
Example 1:
var name = SomeClass.GetName();
if (name.Contains("something"))
{
// do something
}
Example 2:
if (SomeClass.GetName().Contains("something"))
{
// do something
}
I guess what I am asking is, does it have any sort of advantage? Or does it not really matter?
Am I using memory by storing these? especially if I'm storing hundreds across a solution in all different types of methods?
Is it worth just using it inside the if directly for an advantage, or should I just have a variable just in case? Can anyone explain the difference? If there is any that is.
I'm talking about if I only ever use the variable once, so don't worry about the "having to change in multiple locations" issue, although if anyone does want to go into that aswell, I would appreciate it.
I think there will not be any notable advantages in performance wise as well as in memory-wise. But when we look into the following scenarios storing return values have some advantages.
The calling method(SomeClass.GetName() in this case) may return null
Consider that the SomeClass.GetName() may return null subject to some conditions, then null.Contains() will definitely throw NullReferenceException [This will be same in both examples that you listed] in such case you can do something like the following:
var name = SomeClass.GetName();
if (name!= null && name.Contains("something"))
{
// do something
}
Need to use the return value more than one time:
Here you are using the return value only for checking the .Contains("something"), consider that you wanted to use the return value later in the calling method, then it's always better to store the value in a local variable instead for calling the method repeatedly. If it's only for checking contains then change the return type to boolean and finish the job within the method
Ask yourself this question about this line of code:
var name = SomeClass.GetName();
How expensive is GetName() method? Is it going over the internet and downloading a file from somewhere and it takes seconds to minutes to download the file? Or is it doing some crazy computation that takes a few seconds to minutes. Or is it getting data from the database? These answers will help you decide if you should store it in a variable and then reuse the variable.
The next question even if the above answers were "Na! It is pretty quick and does nothing fancy" is to ask yourself this: "How many places in the current class are you making this call? 1? 10? 100? If your boss comes one day and says, "You know that method GetName(), well we are not going to use it anymore. We will use another method named GetName2()". How long will it take? Well imagine if you need to make the changes in 100 different places.
So my point is simple: It all depends.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I guess this question is for a large part a matter of what you prefer aswell as being very situational, but I just came across a path to a gameobject today with a pretty long reference, and I thought if a temp reference wouldn't be better for this situation.
The code:
if (enlargeableButtons[i][j].gameObject.activeSelf && enlargeableButtons[i][j].IsHighlighted())
{
enlargeableButtons[i][j].gameObject.SetIsHighlighted(true, HoverEffect.EnlargeImage);
}
In a case where the path is this long with multiple array indexes to check, it would definitely be faster, but because of the extra object also be more expensive to do it like this:
GameObject temp = enlargeableButtons[i][j].gameObject;
if (temp.activeSelf && temp.IsHighlighted())
{
temp.SetIsHighlighted(true, HoverEffect.EnlargeImage);
}
But how much and would it be worth it?
I seriously doubt you will see any performance gain using a direct reference instead of going through the jagged array.
Maybe if this code is running in a very tight loop with lots and lots of iterations, you might get a few milliseconds of difference.
However, from the readability point of view, the second option is much more readable - so I would definitely go with it.
As a rule - You should design your code for clarity, not for performance.
Write code that conveys the algorithm it is implementing in the clearest way possible.
Set performance goals and measure your code's performance against them.
If your code doesn't measure to your performance goals, Find the bottle necks and treat them.
Don't go wasting your time on nano-optimizations when you design the code.
and a personal story to illustrate what I mean:
I once wrote a project where I had a lot of obj.child.grandchild calls. after starting to write the project I've realized it's going to be so many calls I just created a property on the class I was working on referring to that grandchild and my code suddenly became much nicer.
Declaring GameObject temp just creates a reference to enlargeableButtons[i][j].gameObject. It is extra overhead, but not much. You won't notice a difference unless you're repeating that thousands of times or more.
As a personal rule, if I just need to reference it once, I don't bother with declaring a variable for it. But if I need to use something like enlargeableButtons[i][j].gameObject multiple times, then I declare a variable.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I had an argument with my teammate about the following.
We need to parse a symbol in a string to int(it is always a digit), this particular functionality is used in a number of places. So this can be done this way:
var a = int.Parse(str[i].ToString());
The argument was: do we need to create a function for this.
int ToInt(char c) {
return int.Parse(c.ToString());
}
that can be used:
var a = ToInt(str[i]);
My opinion is that creating such a function is bad: it gives no benefits except for typing couple characters less (no, as we have autocomplete), but such practice increase a codebase and makes code more complecated to read by introducing additional functions. My teammate's reason is that this is more convinient to call just one such function and there is nothing bad in such a practice.
Actually question relates to a general: when it is ok(if at all) to wrapp combination of 2-3-4 functions with a new function?
So I would like to hear your opinions on that.
I argee that this is mostly defined based on personal preferences. But also I would like to hear some objective factors to define a convention for such situations in our project.
There are many reasons to create a new sub-routine/method/function. Here is a list of just a few.
When the subroutine is called more than once.
If it makes your code easier to read/understand.
Personal preference.
Actually, the design can be done in many ways of course, and depends on the actual design of the whole software, readability, easy of refactoring, and encapsulation. These things are to be considered on each occasion by its own.
But on this specific case, I think its better to keep it without a function and use it as the first example for many reasons:
Its actually one line of code.
The overhead of calling a function in performance will be far more the benefit you get from making it.
The compiler itself probably will unwrap it again into the one line call if you make it a function, though its not always the case.
The benefit you get from doing so, will be mainly if you want to add error checking, TryParse, etc... in the function.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So I'm creating a connection library for a colleague of mine to save him time on his current project. My colleague will use this library in his c# application to connect to a rest api. Within the library I created Handlers for each request(GET / POST / PUT / DEL). When his application talks to my library i will return the response like this:
return client.PostAsync(url, content).Result;
This returns a dynamic object from the rest api.
Today he used my library and couldn't get it to work in combination with his application for some reason. I told him to use a var and that it would work like this:
var x = API.CreateTraject(parameter1,parameter2);
He refused to use var and ended up spending about 40 min figuring out how to get it to work without it. Then he blamed me for returning a dynamic object and that he will never use var because explicit is better so he told me.
Im normaly working as mobile developer (IOS / Android) where i use var all the time.
Now my question is:
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
var, in C#, is merely a compiler "trick". There is no dynamic typing involved, and the compiled code is exactly the same. When you hover your mouse over the variable, the IDE will tell you the "real" type that gets used.
Whether he uses var or your actual return type shouldn't matter at all in terms of how you create your library.
If your library is returning dynamic unnecessarily, that may be a different issue, and one which the user may have valid complaints. Unlike var (which is merely a compile time trick), dynamic does change the behavior significantly.
Alternatively, if you're returning anonymous types from your library, you may want to consider making an actual class for your values. Anonymous types are really only intended to be used within a local scope, and shouldn't be part of any public API.
There is nothing illegal with using var, it just lets the compiler figure out what data type the object should be.
The only danger is that you, the programmer, don't know what it is until you mouse over. This can lead to problems where you thought it was one thing, but it turned out to be something else.
It is okay to use var, it's not illegal or anything.
But I think if you know the type of variable, declare the variable with the type. This will make your code easier to read.
It's not bad to use implicit typing, it's just a matter of style. I personally use it a lot simply because it makes all my variable declarations take up the same amount of space, regardless of type.
However, using dynamic definitely can be bad, especially when it's used excessively. It means that type safety checks that can be performed compile-time need to be deferred until run time. Occasionally that's useful, but it can have performance impacts. Unless you really need to return a dynamic, I'd strongly recommend returning a specific type from your API method.
For what it's worth, if your coworker is so opposed to implicit typing he could've just used this:
dynamic x = API.CreateTraject(parameter1,parameter2);
var has nothing to do with dynamic. var is about type inference.
Your methods should not return dynamic to begin with. In any case create Generic Methods and let the consumer (your Colleague) decide what type of object the method will return.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I using c# winforms and wanted to know how it's better to write and why.
if(txtName.Text == "John")
;
or
String name = txtName.Text
if (name == "John")
;
Edit: Thanks guys you helped me a lot!!!
The second version is pointless - it is longer, less readable and introduces one extra variable (though a good compiler would get rid of it, assuming it is not used elsewhere).
Of the two choices, this one is better:
if(txtName.Text == "John")
Though I would go with a third:
if(txtName.Text.Equals("John", StringComparison.InvariantCultureIgnoreCase)
You may want the StringComparison option to be a different enumeration value, depending on how you want the comparison to occur.
For simplicity sake I would go with:
if(txtName.Text.Equals("John"))
Maybe I'm wrong, but others are answering to some complex scenario which isn't the case of one suggested by OP.
What's better?
In fact, it's the same. There's a single difference: first approach, you're storing control's text in a variable and later you check if it's equal to John. Second approach does the same thing, but it gets control's text accessing its string value directly by calling Text property.
When to use a variable and when to access to the property directly? It's just an assumption, because this will depend on each particular use case, but in common terms, call Text property directly if you're accessing its object (the text) just for checking it in a moment of time, otherwise, you'd want to store it in some variable if:
If you want to do some concatenation with Text without affecting the text held by this (if you concatenate it to the Text, you're going to modify it in your app user interface too!).
You're in a multi-threaded environment and you want to get Text in its current state because it can change since user interface is available to the user and it can change its value during some operation.
You just like variables!. If you find using variables clarifies your code better and adds meaning, why not? Nowadays' computers, even mobile phones, have a lot of memory and one, two or three variables wouldn't change anything (maybe 1KB more? wohoo!).
That's all.
Read Best Practices for Using Strings in the .NET Framework.
if (String.Equals(txtName.Text, "John", StringComparison.OrdinalIgnoreCase)) {
// ...Code.
}
For string comparison i would suggest:
string.compare(strA, strB, stringComparisonMethod)
For accessing the text it doesn't matter, the second way is more friendly but both will do the same
I think the later is better because you will be using a less variable i.e. name . Except that I don't see any difference (the styling is obviously upto yourself)
If you're using the value in other parts of your code, I'd go with defining a variable. Otherwise, use the shorter version.
In C# you don't have to use .Equals to compare strings (in response to a comment). == does the same thing.
if(txtName.Text == "John")
This is more conventional and efficient way of these you have shown.
String name = txtName.Text
if (name == "John")
;
Declaring extra variable "name" will increase the code size with any benefit except increasing the program memory. Once I tried and found declaring extra variable and assigning text to it and later accessing this variable instead of text property txtName.Text makes it less efficient then accessing through property.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I want to know how many parameters can be passed to function, I mean what is good programming practice, regarding passing the parameters to function?
Code Complete suggests a maximum of 7. This is because of The Magical Number Seven, Plus or Minus Two:
...the number of objects an average human can hold in working memory is 7 ± 2; this is frequently referred to as Miller's Law.
Here's an excerpt from Code Complete 2nd Edition:
Limit the number of a routine’s parameters to about seven
Seven is a magic number for people’s comprehension. Psychological research has found that people generally cannot keep track of more than about seven chunks of information at once (Miller 1956). This discovery has been applied to an enormous number of disciplines, and it seems safe to conjecture that most people can’t keep track of more than about seven routine parameters at once.
The fewer the better, but only if it still makes sense. I've never heard of a standard number of params to be passed, but I have heard of ways to keep them down better.
For example, don't do this:
public void DoSomething(string name, int age, int weight, ...) { }
but rather:
public void DoSomething(Person person) { }
but hopefully that goes without saying. But also, I would recommend not creating a weird class just to trim down the parameter count.
IMHO 5 at MAX.
6 is too much for me and 7 overwhelming!
According to Clean Code - maximum 3
If you have many things you would like to pass to a function you may want to look at some other means of transferring that data as opposed to simple parameter passing. For example in certain cases it may be better to generate an XML file and then pass values related to getting data around that XML file. If you are running a web app it may be simply passing data through sessions or post rather than get or function calls that will simplify your life.
Also you may want to store some of that information as member variables.
I would recommend no more than 4. You don't want your lines to get much longer than 30 characters long unless you are generating some massive string, but even then it becomes really unreadable and gross (although necessary especially for javascript).
It's good programming practice to write programs so that they are easy to read. Personally I try not to write functions which have more parameters than can be displayed on one line on the screen. Usually that is no more than five or six parameters at most.
some ARM compilers pass three or less parameters using registers and any more than three are stacked. The stacked type call is slower than the call using registers so in this case you should use three or less parameters, for speed.
Depending on the architecture, more than 1-3 will cause passing on the stack. This is slower than passing via registers. From a performance standpoint, it is best to pass either a pointer to a wrapper class or a pointer to a struct. This ensures that only one value is passed in and saves some writes/reads to memory.
If you don't know how many parameters you are going to pass to a function use param for sending variable arguments to a method.