Resharper offered to turn my loop:
foreach (JObject obj in arr)
{
var id = (string)obj["Id"];
var accountId = (double)obj["AccountId"];
var departmentName = (string)obj["DeptName"];
i++;
}
…into a LINQ statement. I acquiesced, and it produced this:
int i = 1 + (from JObject obj in arr let id = (string) obj["Id"] let accountId = (double) obj["AccountId"] select (string) obj["DeptName"]).Count();
Gee whillikers, jumpin’ Jehoshaphat, and Heavens to Murgatroid!
This makes me wonder if the robots becoming smarter than me is a good thing; how maintainable is that? Answer: it’s not, since I can’t understand it; R# may just as well have converted it to machine code, for all I can grok it.
I have to admit, though, it’s “cool.”
At what point does the perfect become the enemy of the good in this kind of scenario?
UPDATE
On a second pass through, R# tells me for that line of LINQ, “Local variable “i” is never used”
Letting it remove it, the line becomes:
var arr = JsonConvert.DeserializeObject<JArray>(s);
Hmm! Now that’s grokkable; the reason I was breaking the elements down into individual vars before was so that I could see what was in them:
MessageBox.Show(string.Format("Object {0} in JSON array: id == {1}, accountId == {2}, deptName == {3}", i, id, accountId, departmentName));
…but with that messagebox commented out, I guess the above is better after all.
2
LINQ is very powerful. But we should always be cautious on jumping on it. Don’t get me wrong, I love LINQ and for many cases, it is a beautiful tool. In your case, your code was perfectly readable, and yet the LINQ version obfuscates your intentions and suddenly the programmer has to figure out exactly what is going on.
Your version is clear, concise, and full of intent.
The LINQ version is an abomination, by comparison.
One rule of thumb I use is: “is this code easier to read?”
A refactoring may initially look cool, it may use something different than what you would normally do. However, at the end of the day, you’re better off with code which is easier to understand than the “hotness” a computer gives you.
So, if a computer gives me code which is difficult for me to grok quickly, I’d likely reject its suggestion.
Automated refactoring tools are not automated thinking tools. Just because you can apply some refactoring on a piece of code (you always can) doesn’t mean you should. Never think you should do something just because a tool suggests it. You and your team are responsible for deciding what is maintainable and what is not.
That being said, automated refactorings are great and ReSharper might be best tool I have used. Refactoring tools can save you a lot of time, but they don’t free you from thinking 🙂