Use base classes implementation with correct access modifiers - c#

I would like to have an interface for a problem called IProblem. With two methods: Solve() and CheckArguments(). The Problem class will implement the CheckArguments() function because it will be the same for all the problems. But then I have different types of problems like EasyProblem and HardProblem that have different implementations of Solve() method but the CheckArguments() method always be the same and I always want to use the base class Problem()'s implementation.
I would like to have correct modifiers and I'm a bit confused on which method being defined in which class/interface. Not to mention I also have a test project for both these functions.

I'm not sure if your question is "what to use", but I'd suggest an interface and an abstract class:
public interface IProblem {
void Solve();
void CheckArguments();
}
public abstract class Problem : IProblem {
public abstract void Solve();
public void CheckArguments() {
...
}
}
public class EasyProblem : Problem
{
public override void Solve()
{
....
}
}
This way, check arguments is implemented in the base class, all derived classes implement IProblem and every derived class must implement Solve.
If you leave out the interface and only support classes which derive from Problem, you'll make sure that a given class can't give it's own implementation of CheckArguments().
public abstract class Problem {
public abstract void Solve();
public void CheckArguments() {
...
}
}
public class EasyProblem : Problem
{
public override void Solve()
{
....
}
}
...
static Main(string[] args)
{
List<Problem> problemsToSolve = ...
foreach(var problem in problemsToSolve)
{
problem.CheckArguments();
problem.Solve();
}
}

You can try something like:
public interface ISupportArguments
{
bool CheckArguments();
}
public abstract class AbstractProblem : ISupportArguments
{
public bool CheckArguments() {
return true;
}
public abstract void SolveProblem();
}
so every your class derives from AbstractProblem and override it's own version of
SolveProblem(..)

The class structure has been shown by Matten very well.
As regards access modifiers: I'd propose a defensive approach, so that you use the most restrictive access modifier that solves the problem. It is easier to be less restrictive afterwards than to be more restrictive as you might have to explain to some users of your code why they cannot use it anymore.
So for the types (interface and classes): if you don't need them in other assemblies, rather define them as internal. If you want to access the types from your test project, you can use the InternalsVisibleTo attribute to be able to access them from specific assemblies. You add the attribute to the assembly containing the types and provide the name (and for strong named assemblies some additional data) of the test assembly as a parameter.
The same applies to the members. You can also think about implementing the interface explicitly, so you can access the methods only if you access the class via the interface.

Related

How to use a method from another class if both classes implement the same interface

So here's an example of what I'm trying to do:
public interface IFlyable
{
void Fly();
}
internal abstract class Insect { }
internal class Bee : Insect, IFlyable
{
public void Fly()
{
//some implementation
}
}
internal class Hornet : Insect, IFlyable
{
public void Fly()
{
//here I want the same implementation as in Bee.Fly()
}
}
As a complete newb not wishing to just copy-paste the implementation, the only meaningful way I could come up with was to make another asbtract class for flying insects and inherit everything needed from there:
internal abstract class Insect { }
internal abstract class FlyingInsect : Insect, IFlyable
{
public void Fly()
{
//implementation
}
}
internal class Bee : FlyingInsect
{
}
internal class Hornet : FlyingInsect
{
}
Even though this solves my problem, still I would like to know what could be better and alternative ways of doing this, especially if there's a way that allows to not create another "unifying" class, but instead calling/taking this already implemented method from another class that uses the same interface.
Thanks in advance.
It depends on what coupling you want, but your choice of an intermediate class seems reasonable if all flying insects will use that implementation (or just a few don;t, and you can override it as necessary). Here are a few other options:
Add an internal method to Insect that Bee and Hornet both call (this seems a little weird if it only applies to flying insects, though)
Add a static method to Bee that Hornet calls (Bee.Fly would have to call it as well)
Add a static method in some other location (a "utility" or "helper" method?) that both call.
Note that there's not a "clever" way to automatically call some other class's implementation just because they implement the same interface. An intermediate type to implement shared behavior seems like the best choice at face value.

Looking for other ways to hide abstract inheritance method from a subclass?

I want the inherited method Invoke() to be hidden from the final subclass ConcreteExecutablePlugin.
Whole situation:
public abstract class PluginBase
{
public abstract void Invoke(IDictionary parameters);
}
public abstract class JobPlugin : PluginBase
{
protected void CheckParameter(){//....}
public bool IsActive(){//....}
}
public class ConcreteJobPlugin : JobPlugin
{
public override void Invoke(IDictionary parameters){//...}
}
public abstract class ExecutableJobPlugin : JobPlugin
{
protected abstract void Initialize(IDictionary parameters);
public sealed override void Invoke(IDictionary parameters)
{
//final realization of Invoke() method
}
}
public class ConcreteExecutablePlugin : ExecutableJobPlugin
{
//here i want method Invoke() has been already hiden
//!!!OR use base.Invoke() better?
protected override void Initialize(IDictionary parameters)
{
//concrete plugin initialization
}
}
I have found only one solution. Now, I'm using sealed for this. What do you think about this solution?
Do you know another ways to hide abstract inheritance method?
Re: Visibility
A public method signals the design intention that it is visible to all - if this isn't the designed intention, change the method's visibility accordingly, e.g. protected (but obviously any subclass has access), or if all classes which are allowed to use Invoke are in the same assembly, then Invoke can be declared protected internal abstract.
Re: Sealed
As per Lasse's point, sealed override methods will disrupt the polymorphic virtual / override chain during inheritance, but still, it can not change the fact that the base method is public. However, applying sealed to a class will prevent other classes from inheriting it all, thus restricting access to all protected methods.
Solution
I believe the underlying problem relates to over-using inheritance - seemingly you want to inherit functionality to obtain reuse, but at the same time need to restrict access at some point in the chain to an "untrustworthy" subclass. Other than the point about making methods internal + moving all "trustworthy" subclasses into the base class assembly, you will have little control when using a full chain of subclasses.
I believe that decoupling your hierarchy via interfaces, and applying the principle of composition over inheritance, will better achieve what you are after. In fact, the Decorator pattern looks to be an option here.
You can also set the 'trustworthiness' boundary by making the 'last trustworthy' subclass (ExecutableJobPlugin) as sealed *.
Example:
// Expose just what is visible to your final Subclass on the interface
public interface IExecutableJobPlugin
{
bool IsActive { get; set; }
void CheckParameter();
void Initialize(IDictionary parameters);
}
// Sealed will prevent other classes from inheriting this class.
public sealed class ExecutableJobPlugin : JobPlugin, IExecutableJobPlugin
{
// Default implementation. NB, not abstract
public void Initialize(IDictionary parameters) {}
// This isn't visible on the interface
protected override sealed void Invoke(IDictionary parameters)
{
//final realization of Invoke() method
}
}
public class ConcreteExecutablePlugin : IExecutableJobPlugin
{
// Compose a decoupled IExecutableJobPlugin instead of direct inheritance
private readonly IExecutableJobPlugin _wrappedJobPlugin;
public ConcreteExecutablePlugin(IExecutableJobPlugin wrapped)
{
_wrappedJobPlugin = wrapped;
}
// Invoke() isn't on the interface so cannot be accessed here
public void Initialize(IDictionary parameters)
{
// Call 'super' if needed.
_wrappedJobPlugin.Initialize(parameters);
//concrete plugin initialization code here ...
}
public bool IsActive
{
get { return _wrappedJobPlugin.IsActive; }
set { _wrappedJobPlugin.IsActive = value; }
}
public void CheckParameter()
{
_wrappedJobPlugin.CheckParameter();
}
}
Notes
Because ConcreteExecutablePlugin is no longer a subclass of PluginBase, if you change method PluginBase.Invoke to protected, that ConcreteExecutablePlugin will have no access to it (aside from hacks like reflection).
All 'reused' methods and properties needed from the composed (née base) class ExecutableJobPlugin need to be rewired in the ConcreteExecutablePlugin. Although somewhat tedious, it does allow for additional interception, e.g. cross cutting concerns like logging.
The ExecutableJobPlugin class may no longer be abstract, since an instance will be needed for the composition to work.
Ideally, the ExecutableJobPlugin should be injected externally (as opposed to new within)
Decoupling via interfaces improves the testability of your class hierarchy
* Sealing ExecutableJobPlugin won't however prevent others from subclassing public superclasses like PluginBase and JobPlugin. To prevent this, you could keep all the base classes in the same assembly and mark these as internal, or continue to apply the interface decoupling / Decorator pattern instead of inheritance across the entire chain.
The pattern could obviously be repeated for multiple levels of your class hierarchy, and the interface segregation principle should be applied to ensure that your interfaces remain lean and focused.
It is impossible to hide public methods in derived classes. The whole point of public is that the method is accessible in the base class and any descendants of that class.
You could try using protected, and then simply have a public method like Initialize in your derived plugins, or you could try using internal (although that would probably not be preferable).

Declaring member function in interface

Firstly I am pretty new to C#. I would like to have an interface declare a member function like in the following piece of code
interface IMyInterface {
void MyAction() {
// do stuff depending on the output of function()
}
void Function();
}
here Function is pure virtual and should be implemented by children of IMyInterface. I could use an abstract class instead of an interface but then I could not inherit from other classes... Say for example that MyAction is recursiverly searching a directory for files and applying Function to any file found to make my example clear.
How to change my design in order to overcome the constraint that interfaces cannot implement classes ?
Edit : In C++ what I would do is using templates as such
template<class A>
static void MyAction(const A& a) {
// do stuff depending on the output of A::Function()
};
class MyClass {
void Function();
};
I was wondering if there were an elegant way to do this using interfaces in C#.
In C# you don't have multiple inheritance. You can circumvent this limitation by using composition.
Define your interface like this (Function needs not to be defined here):
public interface IMyInterface
{
void MyAction();
}
Declare an abstract class with an abstract Function and implementing this interface:
public abstract class MyInterfaceBase : IMyInterface
{
public void MyAction()
{
// Do stuff depending on the output of Function().
Function();
}
protected abstract void Function();
}
From this abstract class you can derive a concrete implementation. This is not yet your "final" class, but it will be used to compose it.
public class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
Now let's come to your "final", composed class. It will derive from SomeBaseClass and implement IMyInterface by integrating the functionality of ConcreteMyInterface:
public class SomeBaseClass
{
}
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
}
UPDATE
In C# you can declare local classes. This comes even closer to multiple inheritance, as you can derive everything within your composing class.
public class MyComposedClass : SomeBaseClass, IMyInterface
{
private readonly IMyInterface _myInterface = new ConcreteMyInterface();
public void MyAction()
{
_myInterface.MyAction();
}
private class ConcreteMyInterface : MyInterfaceBase
{
protected override void Function()
{
Console.WriteLine("hello");
}
}
}
The only way to directly handle this would be to use an abstract class, as the interface cannot contain "logic" of any form, and is merely a contract.
One alternative, however, would be to make an interface and a static class. You could then place your logic in an extension method using the interface.
public interface IMyInterface {
void Function();
}
public static class MyInterfaceExtensions {
public static void MyAction(this IMyInterface object)
{
// use object.Function() as needed
}
}
The main disadvantages here are more types, which reduces maintainability, and a lack of discoverability.
You can define MyAction as extension method:
public interface IMyInterface
{
void Function();
}
public static class MyInterfaceExtensions
{
public static void MyAction(this IMyInterface obj)
{
obj.Function();
}
}
Example:
public class HelloWorld : IMyInterface
{
public void Function()
{
Console.WriteLine("Hello World");
}
public static void Main(string[] args)
{
new HelloWorld().MyAction();
}
}
Output:
Hello World
Interfaces can't implement any behavior they are just contracts. If you want to implement some logic while defining a contract you could use an abstract class.
For that purpose . you need to define abstract class.
You can provide default implementations or you can leave the implementation to the derived class.
If the derived class want to override some thing they can always do that .
This gives them the flexibility to use base along with changes they want to override.
Declare the function's interface (Signature and return types), in an interface,
Then create an abstract class that is defined to implement that interface, and implement a basic default implementation in the abstract class. Then, create other concrete classes that inherit from the abstract class, but when necessary, override the abstract classes base implementation with different implementation.
This sort of problem might best be overcome by separating the external behaviours; MyAction in this case, from the internal implementation; MyFunction.
The point here is understanding what should be part of the interface/contract between this class and others, and what should be part of the implementation of that contract.
Here, the contract between this object and its consumers is defined;
interface IMyInterface
{
void MyAction();
}
Now, a base class which implements this interface, and also enforces a particular behaviour;
abstract class BaseClass : IMyInterface
{
public void MyAction()
{
// do some commmon action
// call derived implementation to deal with the outcome
}
protected abstract void MyFunction();
}
And finally, a concrete implementation which deals with the results of MyFunction in some specific way;
class ConcreteClass : BaseClass
{
protected override void MyFunction()
{
// concrete implementation here
}
}
An interface is a contract, and cannot contain implementation.
From your statement above:
I could use an abstract class instead of an interface but then I could not inherit from other classes
I believe you are hitting the "why does C# not support multiple inheritance" question.
Here is a CodeProject Article on Simulated Multiple Inheritance for C#. You should be able to follow this pattern to achieve a workaround to the simple inheritance model of C#.
This is a proposed feature for C# 8.0:
interface IA
{
void M() { WriteLine("IA.M"); }
}
class C : IA { } // OK
IA i = new C();
i.M(); // prints "IA.M"`
https://github.com/dotnet/csharplang/blob/master/proposals/default-interface-methods.md

Child use of interface

I have a user control that will handle images on a form. But depending on what the source is (web cam or ID scan or other video source) the user control is different.
But they share some common features so I want to create a base class.
My other controls all have some interface items that I need. I would like to declare the interface at the base level though and just implement at the class level. But virtual and override seems to be the closest way to get what I want. Is there any to do it, force the new class to implement the interface assigned at the base class? Looking around it look like making the class abstract (which I don't fully understand) might be a start. If it was just methods that might be alright, but I am also using properties. In that area I have hit a dead end in my searches for answers. Here is what I have so far. Am I on the right track? I just have not worked with abstract classes at all and only limited exposure to interfaces. From the research I think I have the method correct just not sure about the property.
public interface RequiredAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired{ get;}
}
public abstract partial class ExtImage : UserControl, RequiredAnswer
{
public virtual bool AnswerRequired
{
get
{
throw new NotImplementedException ("Answer Required");
}
}
public abstract void LabelRequiredFieldEmpty ()
{
//checkBox_AgreementAcceptedText.ForeColor = Color.Red;
}
So I would have a class
public partial class ExtImageWebCam : ExtImage
{
public override bool AnswerRequired
{
get
{
return valueFromThisClassThatMeansAnAnswerIsRequired;
}
}
public override void LabelRequiredFieldEmpty ()
{
// do something
}
}
When you declare a method abstract, you are basically saying that a child class must supply the definition of the method. You can make properties abstract. This sounds like it is exactly what you need.
Here is the MSDN article for further reference.
From MSDN
Properties
Abstract properties behave like abstract methods, except for the differences in declaration and invocation syntax.
It is an error to use the abstract modifier on a static property.
An abstract inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.
Continuing later
In this example, the class DerivedClass is derived from an abstract class BaseClass. The abstract class contains an abstract method, AbstractMethod, and two abstract properties, X and Y.
abstract class BaseClass // Abstract class
{
protected int _x = 100;
protected int _y = 150;
public abstract void AbstractMethod(); // Abstract method
public abstract int X { get; }
public abstract int Y { get; }
}
Abstract base class with an Interface
An abstract class must provide implementation for all interface members.
An abstract class that implements an interface might map the interface methods onto abstract methods. For example:
interface I
{
void M();
}
abstract class C : I
{
public abstract void M();
}
First of all, interfaces should start with an I by convention, so your interface would be IRequiredAnswer.
Second, if you want to force the inherited classes to implement their own methods rather than inheriting them, just make them abstract in the base class:
public abstract class ExtImage : UserControl, IRequiredAnswer
{
public abstract bool AnswerRequired { get; }
public abstract void LabelRequiredFieldEmpty ();
}
Your child classes would then have to implement the method and property.
You're on the right track. Here's a simple example of what you could do. Making the Bar() method abstract forces the inheritors to implement it.
public interface IFoo{
void Bar();
}
public abstract class BaseFoo : IFoo
{
public abstract void Bar();
public void Implemented(){
Debug.WriteLine("this is a shared implementation");
}
}
public class KungFoo : BaseFoo{
public override void Bar()
{
}
}
You are on the right track for the creation of an interface and then defining an abstract class for your purpose.
Standard naming conventions for an interface has been broken however, interfaces are usually prefixed with an I to help identify them
public interface IRequiresAnswer
{
void LabelRequiredFieldEmpty();
bool AnswerRequired { get; }
}
I would also suggest changing the AnswerRequired property to a function as your concrete class says "do somthing to find result". Properties are usually meant to be quick, so performing any calculation within a property is masking that real work takes place when you call the property. With a function it is more apparent to callers that the result will not be achieved immediately.

Interface wonder question

We define interface as below:
interface IMyInterface
{
void MethodToImplement();
}
And impliments as below:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
instead of creating a interface , why can we use the function directly like below :-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Any thoughts?
You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer
EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.
There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx
If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link
instead of creating a interface , why
can we use the function directly like
below
Are you asking what the point of the interface is?
Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.
When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.
The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.
public class SomeOtherClass
{
public void DoSomething(IMyInterface something)
{
something.MethodToImplement();
}
}
public class Program
{
public static void Main(string[] args)
{
if(args != null)
new SomeOtherClass().DoSomething(new ImplementationOne());
else
new SomeOtherClass().DoSomething(new ImplementationTwo());
}
}
Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.
To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.
Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.
However, there are advantages:
Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:
static void Main()
{
IMyInterface iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:
interface IVehicle
{
void MoveForward();
}
class Car : IVehicle
{
public void MoveForward()
{
ApplyGasPedal();
}
private void ApplyGasPedal()
{
// some stuff
}
}
class Bike : IVehicle
{
public void MoveForward()
{
CrankPedals();
}
private void CrankPedals()
{
// some stuff
}
}
Now say you have a method like this somewhere:
void DoSomething(IVehicle)
{
IVehicle.MoveForward();
}
The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.
Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.
The point of the interface is to define a contract that your implementing class abides by.
This allows you to program to a specification rather than an implementation.
Imagine we have the following:
public class Dog
{
public string Speak()
{
return "woof!";
}
}
And want to see what he says:
public string MakeSomeNoise(Dog dog)
{
return dog.Speak();
}
We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:
public interface IAnimal
{
public string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "woof!";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "meow!";
}
}
And run them both through:
public string MakeSomeNoise(IAnimal animal)
{
return animal.Speak();
}

Categories