Only implementations of method are used? - c#

In ISerialized, Resharper is complaining that "Only implementations of 'SerializeShape" are used. Is there something more I should be doing, or is my use of an interface simply over-kill in this instance? My 'requirements' are that any use of class Shape implement SerializeShape. I am attempting to use Interface in a plausible, conventional way, but maybe I am not?
I have an interface of such:
namespace Shapes
{
internal interface ISerialized<in T>
{
string SerializeShape();
}
}
I have a class of such:
using System.Runtime.Serialization;
using Newtonsoft.Json;
namespace Shapes
{
[DataContract]
public class Shape : ISerialized<Shape>
{
[DataMember] public double Perimeter { get; set; }
[DataMember] public double Area { get; set; }
[DataMember] public string ShapeName { get; set; }
[DataMember] public string ShapeException { get; set; }
public string SerializeShape(Shape shape)
{
return JsonConvert.SerializeObject(shape, Formatting.Indented);
}
}
}

In essence if all you do is have a class implement an interface, then there is no use for the interface. It must be referenced inlieu of the class to be of any real benefit. A brief contrived example to explain in code:
public interface IFoo
{
string Bar();
}
public class Foo : IFoo
{
public string Bar()
{
return "Foo";
}
}
public class FooTwo : IFoo
{
public string Bar()
{
Return "FooTwo";
}
}
public class FooBar
{
public void UseFoo()
{
IFoo foo = new Foo();
string result = foo.Bar();
}
public void UseFooTwo()
{
IFoo fooTwo = new FooTwo()
string result = fooTwo.Bar();
}
}
As you can see both methods in FooBar use IFoo instead of the actual implementation of Foo or FooTwo. This allows you (or someone who is implementing a portion of code you wrote) to honor the contract that is IFoo. If they had done FooTwo fooTwo = new FooTwo() then they aren't really getting any benefit of FooTwo implementing IFoo.

I know this is an old question, but I just ran into a similar situation.
It seems as if this warning pops up because you aren't using it from an outside class. Maybe you just haven't created the call to it or, in my case, it's being used only internal to the class implementing the interface.
If this warning pops up as soon as you write the interface or when implementing the interface, then you simply haven't used the method yet. Once you call the method from other code using the interface, then the warning will go away.
In my case, the method was possibly used outside the class at one point, but through iterations of the code, it's now only being used internally. If I wanted to, I could change the method from public to private and remove the method declaration from the interface.
Aside: Because I only have one class implementing the interface, I could delete the interface entirely and just have the implementing class on it's own, which would entirely avoid this warning altogether. However, this interface has several references, including automated tests. Removing the interface is beyond the scope of the changes I need/want to make, so I'm not going to do it.

Related

Add common method to classes inheriting from a C# Interface?

I have an interface such as this one:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
}
Some of my classes are deriving from this interface:
public class OneClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine(this.a.ToString());
}
}
public class AnotherClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine((this.a * 2).ToString());
}
}
Since I now need a (large) common method on all classes derived from my interface, I was trying to provide an additional base class for that:
public class MyBaseClass
{
public void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString()); // no 'a' on base class
}
}
This clearly doesn't work because the base class would also need to implement my interface in order to know about that a field.
I am now asking myself what the best approach would be here:
make MyBaseClass inherit from ITestInterface?
set LargeCommonMethod() to protected and provide all internal data it uses via arguments? (There's actually a lot of these..)
skip the interface all along and replace it with an abstract base class?
...?
C# 8 provides a feature precisely for this scenario.
Your classes all implement an interface
You want to add a method to the interface
You don't want a breaking change to all of the existing classes. If you add a method to the interface all of the classes will break unless you find some way to add the method to all of them. (That includes modifying them all to inherit from a new base class.)
That feature is default interface methods.
You can add your method and a default implementation to the interface:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString());
}
}
Your existing classes that implement the interface will not break. When cast as the interface, you'll be able to call the method which is defined in the interface. You can still modify any class to provide its own implementation, overriding the interface's default implementation.
For the method to be available the object must be cast as the interface - ITestInterface.
A lot of developers - including myself - found this to be an odd feature. But this is the scenario it's for.
Some documentation
The most common scenario is to safely add members to an interface already released and used by innumerable clients.
If you require a base implementation for a method then an interface is clearly not the way to go.
I would choose an abstract class instead and get rid of the interface. There is no need to complicate the design basically.
The Adapter pattern could fit your Use case, when you want to keep the ITestInterface consistent:
public interface ITestInterface
{
int a { get; set; }
void DoSomething();
}
public class TestInterfaceAdapter : ITestInterface
{
private readonly ITestInterface _testInterface;
public int a {
get => _testInterface.a;
set => _testInterface.a = value;
}
public TestInterfaceAdapter(ITestInterface testInterface)
{
_testInterface = testInterface;
}
public void DoSomething()
{
_testInterface.DoSomething();
}
public void LargeCommonMethod()
{
Console.WriteLine((this.a * 3).ToString());
}
}
public class OneClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine(this.a.ToString());
}
}
public class AnotherClass : ITestInterface
{
public int a { get; set; }
public void DoSomething()
{
Console.WriteLine((this.a * 2).ToString());
}
}

private interface, public child and public factory that can only instantiate members within its namespace that inherit from private interface

I was tinkering around with some code and out of curiosity I wanted to know how I can tackle this problem should I ever stumble upon it.
The problem is that I want to have an Interface and a generic (Factory) class that can only create objects that inherit from that interface. There exists concrete classes which implement that interface which are intended to be used by the generic factory; however, I do not want anyone to add to create their own implementations of the interface but I do want them to be able to create their own instances of the objects which inherit from that interface.
I have a piece of code which illustrates what I am trying to do; however, it does not compile because of the inconsistent accessibility. Here is a piece of code which illustrates what I am inquiring about
using System;
using InterfaceTest.Objects;
namespace InterfaceTest
{
class Program
{
static void Main(string[] args)
{
CreatureFactory<Person> p = new CreatureFactory<Person>();
p.Create();
Console.ReadLine();
}
}
}
namespace InterfaceTest.Objects
{
interface LivingCreature
{
int Age { get; set; }
}
public class Person : LivingCreature
{
public int Age
{
get;
set;
}
}
public class CreatureFactory<T> where T : class, LivingCreature, new()
{
public T Create()
{
return new T();
}
}
}

Can you model an interface where only it's descendants can be implemented?

Assume the following code:
namespace Example {
public interface IBase {
string CommonMember { get; set; }
}
public interface IDerived : IBase {
void DoSomething();
}
public interface IComplexDerived : IBase {
IEnumerable<object> Junk { get; }
}
}
I have a similar structure in the project I'm currently working on. The interface IBase primarily serves the purpose to be able to keep instances of IDerived and IComplexDerived in the same container (like a List<IBase>) and also not having to repeat common interface member definitions (like CommonMember in the example).
One way this would then be used would be something like this:
public class Foo {
public void Bar( IEnumerable<IBase> instances ) {
foreach( IBase instance in instances ) {
if( instance is IDerived ) { /* do something */ }
else if( instance is IComplexDerived ) { /* do something else */ }
}
}
}
So, nothing would stop the user from implementing IBase and passing instances of that class into the system. But doing that would be completely useless because the whole library only expects to deal with classes that implement interfaces that were derived from IBase.
This concept is of course fully documented and shouldn't cause any problems. However, I was wondering if it would be possible to communicate this through means of the language itself. Like having an abstract class, but for interfaces.
You might ask why not simply use an abstract class then. The reason for that is that we don't want to impose the requirement to inherit from our class.
I'm not sure if this is feasible in your actual case, but I think you could have
IComplexDerived inherit from IDerived instead of IBase.
You would then have a list of IDerived instead of IBase, so even a new implementation of IBase would not type-check (since you require an IEnumerable<IDerived>)
Your classes inheriting from IComplexDerived would simply implement DoSomething() in a different way. By doing this you would let your Bar method decide polymorphically what DoSomething it needs to call (and avoid checking on the type)
I mean something like this:
public interface IBase {
string CommonMember { get; set; }
}
public interface IDerived : IBase {
void DoSomething();
}
//IComplexDerived isnow a IDerived
public interface IComplexDerived : IDerived {
IEnumerable<object> Junk { get; }
}
public class Foo
{
// Bar requires IEnumerable<IDerived> so you can't call it with a collection
// of classes implementing IBase
public void Bar( IEnumerable<IDerived> instances ) {
foreach( IDerived instance in instances ) {
instance.DoSomething(); // DoSomething will "do something else" in
// classes implementing IComplexDerived
}
}
}
One possibility is to remove the common interface from IDerived and IComplexDervied and create a wrapper class which takes an instance of one of them and provides the common functionality:
public interface IDerived
{
void DoSomething();
string CommonMember { get; set; }
}
public interface IComplexDerived
{
IEnumerable<object> Junk { get; }
string CommonMember { get; set; }
}
public class EitherDerived : IBase
{
private readonly IDerived derived;
private readonly IComplexDerived complex;
private readonly bool isComplex;
public EitherDerived(IDerived derived)
{
this.derived = derived;
this.isComplex = false;
}
public EitherDerived(IComplexDerived complex)
{
this.complext = complex;
this.isComplex = true;
}
public string CommonMember
{
get
{
return isComplex ? complex.CommonMember : derived.CommonMember;
}
set
{
//...
}
}
public TOut Either<TOut>(Func<IDerived, TOut> mapDerived, Func<IComplexDerived, TOut> mapComplex)
{
return isComplex ? mapComplex(complex) : mapDerived(derived);
}
}
Then you can use this class instead of your IBase interface if you want to be sure you are dealing with one of those classes:
private object HandleDerived(IDerived derived) { ... }
private object HandleComplex(IComplexDerived complex) { ... }
public void Bar(IEnumerable<EitherDerived> instances)
{
foreach(var either in instances)
{
object _ = either.SelectEither(HandleDerived, HandleComplex);
}
}
The suggestion to look for a different design altogether was what I ended up doing. Since this is an open source project, we can look at the actual results.
IBase is ITimelineTrackBase and describes interface members that are common to all derived types.
IDerived is ITimelineTrack and it describes a track on a timeline which consists of a single element with a start and end.
IComplexDerived is IMultiPartTimelineTrack and it describes a track on a timeline which consists of multiple elements that each have a start and an end.
Contrary to my earlier plans, I'm not storing these in a List<IBase>, but I'm using List<IComplexDerived>. Or, in terms of the application, a List<IMultiPartTimelineTrack>.
Now I decided to not accept an IBase anywhere if that's not what I actually want to support in that method. So the ITimelineTrackBase is used purely as a base interface and isn't offered as an accepted parameter type anywhere in the library.
Instead the whole library deals either with single track elements (ITimelineTrack) or a collection of those (IMultiPartTimelineTrack). As needed, the former is wrapped into the latter by a helper construct SingleTrackToMultiTrackWrapper.
So instead of making it impossible to implement the interface, I just made it pointless to implement it.

Implement common behaviour in alternative to abstract base classes?

In C#, I have a class hierarchy with a couple of abstract base classes near the top and a fair number of derived classes. A few these concrete classes have some common properties and methods that are implemented identically. It strikes me as wasteful and so one solution might be to implement this common behaviour in another abstract base class.
abstract class Control;
abstract class SquareControl: Control
{
public int SquarishProperty;
public void SquarishMethod();
};
class Window: SquareControl;
class Button: SquareControl;
However, what if several other classes in the hierarchy shared some other behaviour but also share something in common with one of the controls from another base class? Perhaps there are lots of areas of commonality. It would become impractical to model this with abstract base class implementation wouldn't it?
abstract class FlashableControl: Control
{
public int FlashyProperty;
public void FlashMethod();
};
class StatusBar: FlashableControl; // but it's also a bit square too, hmm...
So how do you go about sharing such implementations across classes without using base classes?
I imagine I want to delegate the implementaion of an interface to another class and have that class implement those properties and methods on behalf of the desired classes, so that to the user, the StatusBar and Window appear to support a standard interface, but under the covers it's something else that implements it.
I can visualise aggregating classes that implement this behaviour, but is this appropriate and are there any pitfalls? What are the alternatives?
Thanks
You can use a pattern like this:
public interface ICommonServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
public static class CommonServiceMethods
{
public static void DoSomething(this ICommonServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
All classes that implement ICommonServices now also get some free behavior via the extension method, which depends solely on those features exposed by all ICommonServices implementers. If you need access to base class functionality, you can put that in its own interface and have ICommonServices implement that interface as well. Now you can create 'default' extension functionality for interfaces without having to use multiple base classes.
EDIT
If you want some of these methods to be internal, you can modify the pattern like this:
public class MyObject : IServices
{
public string PublicProperty { get; private set; }
string IServices.SomeProperty { get; set; }
void IServices.SomeMethod(string param)
{
//Do something...
}
}
public interface IPublicServices
{
string PublicProperty { get; }
}
internal interface IServices : IPublicServices
{
string SomeProperty { get; set; }
void SomeMethod(string param);
}
internal static class ServiceMethods
{
public static void DoSomething(this IServices services, string param)
{
services.SomeMethod(services.SomeProperty + ": " + param + " something extra!");
}
}
Basically we're exposing both public and internal interfaces. Note that we implement the internal interface methods explicitly, so that the methods are not available for public consumption (since the public client can't get access to the interface type.) In this case, the helper extension methods are internal, relying on the internal interface, though you could also create public helper methods that rely on the public interface.
You could use 'has-a' instead of 'is-a' and delegate to an internal square control
class Window : Control, ISquareControl
{
private SquareControl square;
public void SquareOperation()
{
square.SquareOperation();
}
}
class SquareControl : Control, ISquareControl
{
public void SquareOperation()
{
// ...
}
}
One way is to use Interfaces and Base Classes.
Flashable would make a good Interface instead of a class.

How to use a class as the base, but hide the class type publically?

I am currently just exposing the properties through a generic interface e.g.
public interface IBaseClass
{
int ID { get; set; }
}
internal class MyBaseClass : IBaseClass
{
public MyBaseClass() { }
public int ID { get; set; }
}
public class MyExposedClass : IBaseClass
{
private MyBaseClass _base = new MyBaseClass();
public int ID
{
get { return _base.ID; }
set { _base.ID = value; }
}
}
Then in my main application I can do:
IBaseClass c = new MyExposedClass();
c.ID = 12345;
But can't do:
MyBaseClass b = new MyBaseClass();
This is my desired behaviour.
However, I was just wondering if this is the correct approach? Or if there was a better way?
If you only want to prevent instantiation you could make MyBaseClass abstract (make it's constructor protected as well - it is a good design) and have MyExposedClass derive from it. If you want to completely hide the type your approach seems fine.
This look fine to me. Making small interfaces makes it easier to write decoupled code.
I don't know if this will help, but you can make your base class protected internal. This would mean that any internal class has access to it as if it were public, or any class (from within and without the assembly) can subclass the base class. It won't prevent people from implementing their own sub class though.
Alternatively, exposing through an Interface would be the best way I'd think.
For this you can opt for explicit implementation like this:
public interface IBaseClass
{
int ID { get; set; }
}
internal class MyBaseClass : IBaseClass
{
public MyBaseClass() { }
public int IBaseClass.ID { get; set; }
}
public class MyExposedClass : IBaseClass
{
private MyBaseClass _base = new MyBaseClass();
public int IBaseClass.ID
{
get { return _base.ID; }
set { _base.ID = value; }
}
}
You can refer to a similar post C# Interfaces. Implicit implementation versus Explicit implementation
Make your base class abstract.
You could expose the interface as public, implement an internal sealed implementation of that class, and use a factory approach to build instances of the desired interface. That way the client will never know when you change your implementation, or if you have multiple implementations of the same base interface plugged in the factory. You could also eliminate the set accessors in the interface and put them in the internal implementation to only expose the properties to the outside world. That way the exterior code has to make less assumptions over your implementation and you are better isolated. Please correct me if I'm having a poor/bad image of this approach.
Edit: The factory would be public and you'd need some sort of "transfer object" to pass data to the factory. That transfer object implementation would be public, together with it's interface.
Your example seems to include a poor example of taking advantage of inheritence. Since you included a single property it and couldnt come up with a better example i am guessing that its real. I would suggest in this case forget the base class and stick the property on the derived.

Categories

Resources