usages of out parameter in conditional flow and CA1002 fxcop error - c#

I have a xml parsing code where I am parsing multiple nodes and attributes from xml. Using short circuit, I am able to avoid if in my code because I want to continue processing only in positive case. But I am getting fxcop error CA1002 for parameter as out usages.
How can I remove the fxcorp error?
public bool parseNode()
{
bool success = false;
string val1;
string val2;
string val3
success = TryGetAttributeValue(attribName1, out val1) &&
TryGetAttributeValue(attribName2, out val2) &&
TryGetAttributeValyue(attribName3, out val3);
if(success)
{
// do work
}
}
public bool TryGetAttributeValue(string attribName, out string value)
{
}

Assuming you're talking about CA1021 (Avoid out parameters) and not CA1002 (Do not expose generic lists), FxCop is complaining about the out parameter of your TryGetAttributeValue() method.
You can refactor that method so it returns the attribute value instead of storing it in an out parameter, and have it return nullif the attribute does not exist. From there, you can use the null-coalescing operator ?? to keep the same control flow:
public string TryGetAttributeValue(string attribName)
{
// Return attribute value, or null.
}
public bool ParseNode()
{
if ((TryGetAttributeValue(attribName1)
?? TryGetAttributeValue(attribName2)
?? TryGetAttributeValue(attribName3)) != null) {
// Do work.
}
}

Are you sure it's CA1002? Because that one is the Do not expose generic lists rule according to google. Anyway, I know that FxCop has rule which warns about using out (and also ref) parameters as they are not considered best practice for OO (your are supposed to return a object which represents the result).
In order to get rid of the warning you would need to change your method TryGetAttributeValue to not use out parameters.
As a side note: Microsoft apparently violated this rule in the various TryGet and TryParse methods. So just because FxCop says so, it does not make it necessarily a bad choice.

Assuming you are actually talking about CA1021, which fits your description better: This is the MSDN article about this violation. You can change the method type to something other than public or protected (internal ?)
Otherwise:
To fix a violation of this rule that is caused by a value type, have
the method return the object as its return value. If the method must
return multiple values, redesign it to return a single instance of an
object that holds the values.
If you are not able/willing to change the protection type or change the code to simply return the string, then you will have to ignore this fxcop rule . Which, is not a horrible thing. You have to decide which rules seem pertinent and which do not.
Your code would have to be something like GetAttributeValue, and use a check for null if you want to avoid this fxcop rule. Or, you could create a special class and use a Null object pattern, but that seems to be way too much overkill.
In the end, you are in control of your code, and not all rules are meant for everybody.

If you read the whole article, you can see at the end the following:
Methods that implement the Try pattern, such as
Int32.TryParse, do not raise this violation.
So as long as your methode return a bool and has a name like TryGetSomething, you are not violating the rule if you use the out parameter.

Related

C#: Why does List<String>.Equals(String) compile?

In my Java days I got used to doing .Equals() for comparisons instead of == (at least for cases where I knew / had tested for whether the object I called .Equals() on was not null).
I just ran into a problem with some C#.NET code that had been missed for a few versions because it compiled OK, but at runtime it always returned false, but I'm a bit confused about why it compiled, can somebody please explain? (I'm guessing it maybe has something to do with Equals() being inherited from object, but didn't see a good reference for this).
Story: I had a class I use for filtering database queries, called WorkFilter, and I converted the filter engine to support multi-value filters (as opposed to just single-value filters). So each filter field property of WorkFilter was converted from String to List<String>, and I converted most of the code (except this one case I missed) to deal with this, and it was fine for a while until I noticed that a certain condition was never true.
Filter class looks like this:
public class WorkFilter
{
public List<String> RecordType { get; set; }
public List<String> Product { get; set; }
... etc ...
}
The "bad" code was doing this:
if (workFilterInstance.RecordType != null && workFilterInstance.RecordType.Equals("REQUEST"))
{
// code that never gets fired because List<String> never equals String value
}
I fixed it to do this (basically):
if(workFilterInstance.RecordType != null && workFilterInstance.RecordType.Contains("REQUEST"))
{
// now this can handle logic for RecordType = "REQUEST" filters
}
I was kicking myself because I know that if I had used == instead, it would have failed at compile time, for example, if I did this: RecordType == "REQUEST" because you can't use the equality operator to compare List<String> and String.
But I was surprised by my misunderstanding of .Equals() because I expected RecordType.Equals(String) to also generate a compiler error (or at least a runtime error, instead of always returning false)... I mean, why would you ever compare List<> to String anyway, and why did this compile?
I poked around MSDN a bit but was hoping somebody could explain it in plain english. Thanks!
Because List<T> is an Object and Object provides Equals implementation. Which is defined as:
public virtual bool Equals(
Object obj
)
now since your parameter passed is a string which is again an object, it compiles.
For your comment:
But why would that not fail at runtime? Is there no protection against
doing what I did? –
It will return false. There is no reason for it to fail. (Although IMO, it should show a warning). If you use Resharper you will get a warning:
Suspicious comparison: there is no type in the solution which is
inherited from both
This code compiles because the Equals method of List<T> is an override of the Equals method of System.Object:
public virtual bool Equals(
Object obj
)
It would not fail at runtime because the contract for Equals requires that
x.Equals(y) returns the same value as y.Equals(x).
and System.String's Equals(Object) will return false if it is passed something that is not a string:
true if obj is a String and its value is the same as this instance; otherwise, false.
Yes; it would be nicer if you would get a warning or error for that.
However, the type system is not rich enough to express that.
You want to write
public virtual bool Equals(??? o);
Where ??? means any type convertible to the qualifier on which the method was called.
It should be fairly easy to write a Roslyn diagnostic to catch this.

Operation that can succeed/fail -- return type & naming convention

What return type is appropriate for a method that can either complete successfully or fail due to its business logic? And based on that return type, what would be the appropriate naming convention?
My instinct is that bool is most appropriate for a simple pass/fail. I've researched and found conventions for methods that infer a trait -- i.e. IsValid, HasFoo, ContainsBar, etc. But is that also the proper naming for an action like BuildHouse() or FlyKite() to clearly indicate whether the operation was successful?
I've tried it a few ways but each time I keep thinking that it looks weird and there must be a better practice....
bool IsHouseBuilt()
bool TryBuildHouse()
void BuildHouse(out bool success)
PassFailEnum BuildHouse() //seems a little excessive
bool IsKiteFlying()
bool TryFlyKite()
void FlyKite(out bool success)
PassFailEnum FlyKite()
All builtin methods in .NET that are trying to parse something to something else(e.g. int.TryParse) are called TryParse and return a bool and an out parameter.
So maybe:
public static bool TryBuildHouse(T input, out House house)
TryBuildHouse seems the most correct of your examples.
The often accepted format for a method that tries to return a value is:
bool TryBuildHouse(out object thing);
The often accepted format for a method with no parameters that tries to succeed in doing something is whatever you want it to be, really... Some people prefer the Try prefix since it usually implies that it may not succeed, but I like to think that a bool return type also implies that it may not succeed. To each their own.
If the failure to build something is catastrophic (it absolutely SHOULD succeed all of the time), you should consider a void method that throws an appropriate exception in the rare instances of failure, and then catch or don't catch it based on your unique situational and environment requirements.
I would suggest TryParse but you haven't stated whether the method actually returns an object as well. Conventionally, TryParse would suggest that there's an output. If you look at the HashSet.Add method, it returns a bool if successful but doesn't return an actual out value.
Therefore, from the sound of your case, I'd go for something like
/// <summary>
/// Builds a house
/// </summary>
/// <returns>true if house was built; false if house failed to build</returns>
public bool BuildHouse();
and document the fact that it returns a success/fail bool. If you plan to return an object, such as the house, then the TryParse option would make sense and your method would have an out parameter which will hold the newly created object.
You should consider building a class that represents the information that would be desired for any type of call in your system, such as this:
public class ActionResult
{
public bool Success { get; set; }
public List<string> Errors { get; }
public ActionResult()
{
// Initialize whatever you want here
Errors = new List<string>();
}
}
Then when "bad" or "unexpected" things happen in your methods you can populate the ActionResult return type with error information that might be useful to the caller.
In your example you would use it like this:
ActionResult BuildHouse()
{
}
Lots of possibilities. One I haven't seen mentioned is BuildHouse() returning a House object if it succeeds and returning null if it fails.

Showing warning when function result is not assigned to variable

I have a function that returns a modified copy of the object that was passed to this function. I often do something like this:
obj = obj.Foo(param);
Don't ask why, I simply have to. But sometimes, I (and others) forgot to assign the return value, doing this:
obj.Foo(param);
which repeatedly leads to time-consuming debugging.
Is there any way to show a warning or error every time when the function result is not assigned to a variable? Or any other suggestions on how to solve this issue?
You could use an out parameter, so the call would look like this:
obj.Foo(param, out obj);
You can use Resharper to assist with this issue; you need to decorate your method with the [Pure] attribute:
[Pure]
public static IList<T> RemoveItem<T>(this IEnumerable<T> thisList, T item)
{
var list = thisList.ToList();
list.Remove(item);
return list;
}
then when you call it without assigning the return value you will see:
The [Pure] attribute is defined in Resharpers Data Annotations: You need to copy the classes into your project so you can reference them (many very useful other annotations too)
It's totally legal and often desirable to not assign the return parameter so it would be wrong to have a warning for it. Henrik's answer to use an out parameter is what I'd recommend too to ensure the result is assigned everytime.
you can enable visual studio warings.
you can even customize the rule you want to apply.
you should see warnings in the case you don't assign the function to a variable
you can also decide to treat the waring as errors
Example:
public static class MyClass
{
public static string GetStr()
{
return "";
}
public static void Main()
{
GetStr();
}
}
I can't comment on answers, lacking stackoverflow credits. But I agree with Chris that it's totally legal and often desirable not to assign values returned from a method. It's also occasionally not desirable. e.g.
public static int Square(this int myValue)
{
return myValue * myValue;
}
It's clear that calling this method without assigning it is probably a bug. I think creating a code analysis rule that warned every time you didn't assign a value as Massimiliano suggested would be worse than not having the rule at all. In such cases it would be nice to be able to apply an attribute to the method...
[MustAssign]
public static int Square...
You could create a rule as Massimiliano suggested but only invoke the warning when the method is adorned with the attribute and the value returned from the method is not assigned. Not a trivial exercise though.

Is there a way to mark a method as ensuring that T is not null?

For example, if I have a method defined as...
T Create()
{
T t = Factory.Create<T>();
// ...
Assert.IsNotNull(t, "Some message.");
// -or-
if (t == null) throw new Exception("...");
// -or- anything that verifies that it is not null
}
...and I am calling that method from somewhere else...
void SomewhereElse()
{
T t = Create();
// >><<
}
...at >><<, I know (meaning me, the person who wrote this) that t is guaranteed to not be null. Is there a way (an attribute, perhaps, that I have not found) to mark a method as ensuring that a reference type that it returns or otherwise passes out (perhaps an out parameter) is guaranteed by internal logic to not be null?
I have to sheepishly admit that ReSharper is mostly why I care as it highlights anything it thinks could cause either InvalidOperationException or NullReferenceException. I figure either it's reading something that I can mark on my methods or it just knows that Assert.IsNotNull, simple boolean checks or a few other things will remove the chance of something being null and that it can remove the highlight.
Any thoughts? Am I just falling victim to oh-my-god-resharper-highlights-it-I-have-to-fix-it disease?
If ReSharper is why you care then you can mark the Factory.Create<T>() method with their [NotNull] attribute described in their web help
Not sure how R# handles this, but the Contract.Assert method may be what you're looking for
You could put a constraint on T to only allow struct.
You could use a language extension that allows you to make stronger definitions of pre/post conditions for your function (contract based programming), like SpecSharp, or Code Contracts. Code Contracts seems to leverage built-in systems from C# 4.0. I have no experience with either - only heard of them.
Could you cast T to an object then check if its null?
var o = (object)Factory.Create<T>();
if(o == null) throw new Exception();

Redundant condition check before assignment suggestion for C# in Resharper 5

Is the condition check really redundant in the following sample?:
public class MyClass {
public bool MyProperty { get; set; }
public void DoSomething(bool newValue) {
// R# says: redundant condition check before assignment
// on the following line:
if (MyProperty != newValue) { // <======
MyProperty = newValue;
}
}
}
I know that either way MyProperty will be set to newValue, but is the check redundant?
In Adobe Flex, the getter is called implicitly by the VM its running on whenever a setter is called even though no explicit check is being made. The end result is that checking before an assignment results in two checks, one explicit and one implicit, resulting in a redundant check. Does anything similar happen in C#?
There are only two situations where I've seen this type of check.
The first is when there is an additional line of code which sets another property on the object to True to indicate that the object has been modified. This is typically used when trying to decide whether to persist the state of the object to something like a database.
The second situation is when the types in question are immutable. You might want to avoid setting the value and therefore creating a new string, for example, when the values are the same. Even then, I've only seen it in certain apps where memory usage is critical.
In this specific case, it's logically redundant, since there is no code being executed in the getter - just a straight wrapper around a private field. If you're in the habit of putting stuff in your getter that would have side effects, I'd say to disable that R# warning.
Might be worth trying to put something in the getter of the property, and see if ReSharper still thinks it's redundant. If it does, then I'd call that a R# bug.
I would say that the check is redundant. It would make more sense if you had an implementation of INotifyPropertyChanged, but then the check would be in the setter to avoid triggering the event if no actual change is done.
if (MyProperty != newValue) IS redundant, leaving the line will yield the same result

Categories

Resources