FXCop warning CA1801: "Parameter is never used..." on overridden inherited supressed property - interface

On a continued mission to clean up the codebase I inherited, via stylecop and fxcop, and one of the warnings from fxcop was CA1801: Parameter 'value' of Something.MyProperty.set(string) is never used. Remove the parameter or use it in the method body.
The code it complains about is:
public class Something : ISomeInterface
public new string MyProperty
{
get
{
throw new InvalidOperationException("MyProperty is not implemented.");
}
set
{
throw new InvalidOperationException("MyProperty is not implemented.");
}
}
This property is defined in the interface, but in this case is not needed in the derived class - Aside from the slightly questionable use of InvalidOperationException instead of NotImplementedException, which I believe is common, I wonder if I should just exclude the warning in FXCop with a note explaining why?
I don't see what else I could do do in terms of best practice, to prevent the warning in FXCop, other than refactoring this particular property out into a second interface, and then updating all the other classes that use this interface? I think I may have just answered my own question? :D

I believe it is because of the "new" keyword that you are receiving this warning. Try replacing removing new with override and see if the warning disappears.
public class Something : ISomeInterface
public string MyProperty
BTW, I recommend using NotImplementedException instead of InvalidOperationException as well.

Related

Why should I avoid wrapping fields in getters and setters?

I am building a Flutter app. I have a class that looks like this:
class ToDo {
String _title;
bool _done;
String get title => _title;
void set title(String newTitle) { _title = newTitle; }
bool get _done => _done
void set done(bool done) { _done = done; }
}
But the Dart linter is complaining that I should "Avoid wrapping fields in getters and setters just to be safe". However, this doesn't make much sense to me. Right now the getters are useless, but what if in the future I need to do some kind of processing before accessing a variable from outside? All I'll have to do is update the getters. However, if the properties were public and being accessed directly, I would have to update the whole codebase if some business rule changed.
So what is the point of this warning? Or, in other words, why creating "useless getters" would be a bad practice?
However, if the properties were public and being accessed directly, I would have to update the whole codebase if some business rule changed.
Ask yourself this: what exactly would you need to change in your Dart codebase if you had to change a public member to use an explicit getter and setter instead?
In most languages, getters and setters look like method calls to consumers. If you wanted to replace a public data member with a public getter and setter, that would be a breaking API change, requiring changes to everything that uses it.
Dart is not like that. Getters and setters do not look like method calls to consumers; they are indistinguishable from direct member access. (Having a public data member implicitly declares a corresponding getter and setter as part of the class's interface.) Changing a public data member to a public getter and setter would not require any changes to callers, so providing trivial getters and setters around private member variables provides no benefit.
(This is also explained by the documentation for the unnecessary_getters_setters lint that you encountered.)
Incidentally, the unnecessary_getters_setters lint should occur only if you provide both a getter and a setter (which is not what your example code does). If you provide only one, then it would no longer be equivalent to a public data member.
Just to add to this I would like to make an additional comment. This error goes away if you do something else within the setter, not just set the value. In my use case I was setting a value in a Provider and was calling notifyListeners().
By adding this additional functionality the lint warning disappears. I guess because the setter is doing more than just setting the value.

FakeItEasy setting property with no get accessor?

I'm trying to use FakeItEasy 2.0.0 to fake a property in a simple interface:
public interface IPerson
{
int Age { set; }
}
Note that I don't have a get accessor. The test I'm trying to write is:
public void SetsAge()
{
var fakePerson = A.Fake<IPerson>();
A.CallToSet(() => fakePerson.Age).To(42).MustHaveHappened();
fakePerson.Age = 42;
}
But the line containing A.CallToSet fails to compile with:
which is fairly self-explanatory, but confusing since I'm not trying to get the property's value.
Do I have to provide a get accessor to get this to compile (even though I don't want a get accessor)? What is the reason that it requires the get accessor in this case (the same compiler error happens when I replace MustHaveHappened with DoesNothing)? Or am I doing something fundamentally wrong?
Or perhaps I shouldn't lose too much sleep over this and do the right thing in the first place?
Do I have to provide a get accessor to get this to compile?
No, you can use
A.CallTo(fakePerson).Where(call => call.Method.Name == "set_Age" &&
call.GetArgument<int>(0) == 42)
.MustHaveHappened();
This is documented in Specifying a call to any method or property.
What is the reason that it requires the get accessor?
The reason is that because you can't use a = in a lamdba expression, there's no easy way to refer to the property setter. In 2.0, we added A.CallToSet to allow you to cheat by using the getter, but of course it only works when there is a getter.
We've not yet come up with an elegant way to refer to a getterless setter, so you have to use the powerful version of A.CallTo above.
Or am I doing something fundamentally wrong?
Well, in addition to the problem with referring to the property, the whole A.CallTo…MustHaveHappend() has to occur after fakePerson.Age = 42, or it will report a failure, because you haven't yet set fakePerson.Age to 42.

eclipse null analysis field initialization

Using the Null Analysis of Eclipse:
It it possible to define other methods as initializing methods than Constructors?
I have a class like this:
public class Foo {
#NonNull
private Object fooObject;
public Foo() {
super();
}
public void onCreate() {
fooObject = //Something which is not available in the Constructor;
}
Here i get the warning that the NonNull field may has not been initialized. Is there any possibility to kind of declare the init-method as an initalizing one?
I could use #SuppressWarnings("null") for the constructor. But then I ignore all fields, which may instanciated somewhere.
Second chance i see is to make fooObject as #Nullable - but then i need check for null each time i use fooObject.
So is there any better solution?
Null-checking object initialization beyond the constructor is inherently difficult. Several sophisticated approaches exist, all of which require additional annotations.
In your example it seems to be near-impossible, to prove to the compiler, that onCreate() is always called before accessing the field.
A weaker solution has been proposed: #LazyNonNull, an annotation to be used on fields that are initially null, but once initialized can never go back to null. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=414237
Obviously, a static factory method, that gathers all necessary values before invoking a constructor (with arguments) would be a lot easier to get right.

FxCop CA2227 warning and ReadOnlyCollection<T>

In my VS2008 SP1, .NET 3.5 SP1 project, I have different classes that contain different properties.
I use C#3.0 auto properties a lot.
Some of these properties need to be collections. Since I want to make it simple, I use ReadOnlyCollection<T> for these properties.
I don't want to use IEnumerable<T> since I want random access to the elements.
I use Code Analysis (FxCop rules) and I get the CA2227 warning.
I don't understand why does ReadOnlyCollection<T> should have a set method while it can't be changed... The set method can only do exactly what the property can do.
Example:
using System.Collections.ObjectModel;
namespace CA2227
{
public class MyClass
{
public ReadOnlyCollection<int> SomeNumbers { get; set; }
}
}
CA2227 : Microsoft.Usage : Change 'MyClass.SomeNumbers' to be read-only by removing the property setter. C:\Users...\Visual Studio 2008\Projects\CA2227\MyClass.cs 7 CA2227
A ReadOnlyCollection cannot be changed, but there's no reason why a property with a setter that is of type ReadOnlyCollection can't be changed to refer to a different ReadOnlyCollection. If you want the SomeNumbers property to be immutable, then it needs to be both of a read-only type, and also have a non-public setter.
EDIT
If you're convinced in what you want, then although FxCop is correct to warn you, you are happy with the warning. If you want to get rid of it, then include a SuppressMessage attribute at that point - as long as you also define a CODE_ANALYSIS constant in the project properties before you build, FxCop will honour that attribute and just not issue that particular warning on that particular occasion.
It's rather odd to block changes to the contents of the collection without also blocking changes to the collection itself. If you want to be able to set the collection from within your class while conserving the use of automatic properties, you could use a private setter. e.g.:
public ReadOnlyCollection<int> SomeNumbers { get; private set; }
Consider using
public class MyClass
{
public IReadOnlyList<int> SomeNumbers { get; set; }
}
ReadOnlyCollection = http://msdn.microsoft.com/en-us/library/ms132474(v=vs.110).aspx
IReadOnlyList = http://msdn.microsoft.com/en-us/library/hh192385(v=vs.110).aspx
The problem with ReadOnlyCollection, is that it still inherits from ICollection, and still has .Add, even though documentation say it will throw - http://msdn.microsoft.com/en-us/library/cc672239(v=vs.110).aspx

generic type dependency injection: How to inject T

I want to handle different types of docs the same way in my application
Therefore:
I have a generic interface like this.
public interface IDocHandler<T>where T: class
{
T Document { get;set;}
void Load(T doc);
void Load(string PathToDoc);
void Execute();
void Execute(T doc);
}
And for different types of documents I implement this interface.
for example:
public class FinanceDocumentProcessor:IDocumentHandler<ReportDocument>
{}
public class MarketingDocumentProcessor:IDocumentHandler<MediaDocument>
{}
Then I can do of course something like this:
IDocumentHandler<ReportDocument> docProc= new FinanceDocumentProcessor();
It would be interessting to know how I could inject T at runtime to make the line above loosly coupled...
IDocumentHandler<ReportDocument> docProc = container.resolve("FinanceDocumentProcessor());
but I want to decide per Configuration wether I want to have my FinanceDomcumentProcessor or my MarketingDocumentProcessor... therefore I would have to inject T on the left site, too ...
Since I have to use c# 2.0 I can not use the magic word "var" which would help a lot in this case... but how can I design this to be open and flexible...
Sorry for the misunderstanding and thanks for all the comments but I have another example for my challenge (maybe I am using the wrong design for that) ...
But I give it a try: Same situation but different Explanation
Example Image I have:
ReportingService, Crystal, ListAndLabel
Three different Reporting Document types. I have a generic Handler IReportHandler<T> (would be the same as above) this Handler provides all the functionality for handling a report Document.
for Example
ChrystalReportHandler:IReportHandler<CrystalReportDocument>
Now I want to use a Framework like Unity (or some else framework) for dependency injection to decide via configuration whether I want to use Crystal, Reportingservices or List and Label.
When I specify my mapping I can inject my ChrystalReportHandler but how can I inject T on the left side or in better word The Type of ReportDocument.
IReportHandler<T (this needs also to be injected)> = IOContainer.Resolve(MyMappedType here)
my Problem is the left Site of course because it is coupled to the type but I have my mapping ... would it be possible to generate a object based on Mapping and assign the mapped type ? or basically inject T on the left side, too?
Or is this approach not suitable for this situation.
I think that with your current design, you are creating a "dependency" between IDocumentHandler and a specific Document (ReportDocument or MediaDocument) and so if you want to use IDocumentHandler<ReportDocument or MediaDocument> directly in your code you must assume that your container will give you just that. The container shouldn't be responsible for resolving the document type in this case.
Would you consider changing your design like this?
public interface IDocumentHandler
{
IDocument Document { get; set; }
void Load(IDocument doc);
void Load(string PathToDoc);
void Execute();
void Execute(IDocument doc);
}
public class IDocument { }
public class ReportDocument : IDocument { }
public class MediaDocument : IDocument { }
public class FinanceDocumentProcessor : IDocumentHandler { }
public class MarketingDocumentProcessor : IDocumentHandler { }
If I understand you correctly, you have two options.
if you have interface IDocHandler and multiple classes implementing it, you have to register each type explicitly, like this:
container.AddComponent>(typeof(FooHandler));
if you have one class DocHandler you can register with component using open generic type
container.AddComponent(typeof(IDocHandler<>), typeof(DocHandler<>));
then each time you resolve IDocHandler you will get an instance of DocHandler and when you resolve IDocHandler you'll get DocHandler
hope that helps
You need to use a non-generic interface on the left side.
Try:
public interface IDocumentHandler { }
public interface IDocumentHandler<T> : IDocumentHandler { }
This will create two interfaces. Put everything common, non-T-specific into the base interface, and everything else in the generic one.
Since the code that you want to resolve an object into, that you don't know the type of processor for, you couldn't call any of the T-specific code there anyway, so you wouldn't lose anything by using the non-generic interface.
Edit: I notice my answer has been downvoted. It would be nice if people downvoting things would leave a comment why they did so. I don't care about the reputation point, that's just minor noise at this point, but if there is something seriously wrong with the answer, then I'd like to know so that I can either delete the answer (if it's way off target) or correct it.
Now in this case I suspect that either the original questionee has downvoted it, and thus either haven't posted enough information, so that he's actually asking about something other than what he's asked about, or he didn't quite understand my answer, which is understandable since it was a bit short, or that someone who didn't understand it downvoted it, again for the same reason.
Now, to elaborate.
You can't inject anything "on the left side". That's not possible. That code have to compile, be correct, and be 100% "there" at compile-time. You can't say "we'll tell you what T is at runtime" for that part. It just isn't possible.
So the only thing you're left with is to remove the T altogether. Make the code that uses the dependency not depend on T, at all. Or, at the very least, use reflection to discover what T is and do things based on that knowledge.
That's all you can do. You can't make the code on the left side change itself depending on what you return from a method on the right side.
It isn't possible.
Hence my answer.