LINQ: Why use ...Take(1).SingleOrDefault()? [closed] - c#

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 4 years ago.
Improve this question
I'm currently examining some code I'm going to maintain.
I see a few occasions of
.Take(1).SingleOrDefault()
Why would you use that instead of simply
.First() or .FirstOrDefault()
(I'm not sure whether .Take(1) would throw an exeption if the result set is empty, which imho would make the difference between the two .First... Methods?)

It is impossible for us to know for sure the inner implementation of whatever LINQ provider you may be using. They all vary in how they do it. Some may be more performant in cases like this whereas others may be less performant. You should get the same result either way.
It is not possible for us to read someones mind to determine why they would have done it this way in this case.
With that said, if you want to dig in deeper and it is a SQL provider, you can see what SQL it generates and compare the two cases.

The main objection is that .Take(1).SingleOrDefault() defeats the purpose of SingleOrDefault, which is to throw an exception when the LINQ query returns more than one element.
To illustrate this, when running LINQ against a Sql Server backend Single(OrDefault) will translate into SELECT TOP (2) ... in order to determine whether there actually is one record. Preceding this by Take(1) will never return more than one record, so the "multiple result" exception will never occur although the code seems to require it. This code looks like a (premature) optimization by someone who's worried about returning two objects instead of one.
So the answer to your question "Why would you use that?" is: there's absolutely no reason to do it this way. There are only reasons not to do it.

Related

Use a single dictionary object instead of multiple method parameters (similar to args[] in Main method) [closed]

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 2 years ago.
Improve this question
Can a single dictionary object be used in place to replace method parameters (similar to args in Main method) is this a good idea or if bad? what would be a better approach than this?
private async Task<OperationResult> AddOrUpdateRecord(Dictionary<string, object> args)
{
args.TryGetValue("record", out object record);
...
... etc
var recordExists = new RecordExists(record as RecordDto, _dnsCommonActionsRepo);
}
is this a good idea or if bad
This is in the vast majority of cases a very bad idea. The caller will have no idea what parameters are needed. You cannot pass any typed object, so you lose all type safety. You will have no compiler checks to catch potential errors. You are also likely to reduce performance if that is a concern.
what would be a better approach than this?
In most cases, regular parameters. In some cases, where you have way to many parameters, and is unable to refactor the method, a parameter object that gathers many different parameters might be motivated. The only use case I can think of for something like this is when you are getting untyped parameters from some source, for example, key-value pairs from a database or file.
If the problem is breaking builds due to signature changed, that is intentional. The compiler saves you from shooting yourself in the foot. Good refactoring tools, like R# allows modification of signatures, but if you add a parameter, chances are you need to fix call sites by hand.

When to create a new function? [closed]

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.

Does HashSet preserve order between enumerations? [closed]

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
This StackOverflow answer completely describes that a HashSet is unordered and its item enumeration order is undefined and should not be relied upon.
However,
This brings up another question: should I or should I not rely upon the enumeration order between two or more sebsequent enumerations? Given there are no insertions or removals.
For example, lets say I have added some items to a HashSet:
HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);
set.Add(4);
set.Add(5);
Now, when I enumerate this set via foreach, let us say I receive this sequence:
// Result: 1, 3, 4, 5, 2.
The question is: will the order preserve if I enumerate the set times and times again given I do no modifications? Will it always be the same?
Practically speaking, it might always be the same between enumerations, but that assumption is not provided for in the description of IEnumerable and the implementor could decide to return then in whichever order it wants.
Who knows what it is doing under the hood, and whether it will keep doing it the same way in the future. For example, a future implementation of HashSet might be optimized to detect low memory conditions and rearrange its contents in memory, thereby affecting the order in which they are returned. So 99.9% of the time they would come back the same order, but if you started exhausting memory resources, it would suddenly return things in a different order.
Bottom line is I would not rely on the order of enumeration to be consistent over time. If the order is important to you then do your foreach over set.OrderBy(x => x) so that you can make sure it is in the order you want.

Best Practices - Is it necessary to check for certain preconditions if another method does so? [closed]

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 4 years ago.
Improve this question
Here's an example. I saw a "ReadOnlyDictionary" class online and it had the following code:
void ICollection.CopyTo(Array array, int index)
{
ICollection collection = new List<KeyValuePair<TKey, TValue>>(this._source);
collection.CopyTo(array, index);
}
For example, should I check array for a null argument, or should I let the the CopyTo method do that for me? It just seems a bit redundent, but if best practices say to check everything in your own method, then that's what I want to do. I'm just not sure what "best practices" says to do.
I think it wise to say if you plan to do something with array that relies on it NOT being null then you should check this. But if it just a pass through then I don't see a reason why you should check.
Another thought is if the method gets complicated in the future. You might still want to check for it because someone may modify the code and use array without realizing that it might be null. This is only for maintaining good code in my opinion.
If somebody else's library or API* is going to complain about my inputs, I don't want to give it those inputs, I want to validate and/or complain first. This is especially important if calls into external APIs are expensive, such as a database or web service call.
You know what inputs the API is going to reject. Don't send those, invalidate them in your own public API.
*Note: I consider my own public boundaries to be the same thing. If I have class Foo that does not like given arguments, if I invoke Foo, at some level before doing so, I'm going to validate my arguments. You don't do this at every level (assume there are layers of indirection, maybe, private methods calling into private methods, etc.), but at some reasonable public boundary, I will validate. Validate early, don't let complicated logic or work be done when it's just going to be rejected anyway.

General method placement [closed]

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 4 years ago.
Improve this question
Is it best practice to place method bodies before or after they are called ? I generally place them after; interested in what others are doing ?
I prefer after. The reason for this is because it makes the flow of your code more logical. Code flows from top to bottom anyway, so it's logical that methods called appear after the current method.
This has the added advantage of the entry point of your program/class being at the top, which is where you start looking anyway.
When developing Java, I place the method bodies after they are called. This will typically result in classes that have a small number of public methods at the top, followed by quite a few private methods at the bottom. I think this makes the class easier to read and understand: you just need to read those few public methods at the top to understand what the class does — in many cases you can stop reading once you get to the private methods.
I also note that Java IDEs typically place the method body after the current method when you refactor code. For example in Eclipse, if you select a block of code and click Refactor | Extract Method... it will place that selected code in a new method below the current one.
It is entirely a matter of personal preference. For most people, the code navigation facilities of a modern IDE mean that it hardly makes any difference how the methods are ordered.
The method placement is largely irrelevant to me (of course in case of some static methods that need to be defined before invoked):
The code formatters are usually in place (and running automatically - if not for you, turn them on) which results in the source being ordered nicely by type of the method and then alphabetically, rather without the regard to the method call sequence
I use the modern IDE, where finding the proper method is done in a different way than sequentially going through the whole source

Categories