how can I do if many class inherit one interface with Ninject.Extensions.Conventions - ninject

In my item,there are multi class inherit one interface, and many interface like this.
for example,class A|B|C inherit interface Ilog, class F|E|G inherit interface IData, and class H|I|J inherit IBase, and so on. now ,I want bind All Interface use Ninject.Extensions.Conventions,how can I do. if use conventions can't do it,please tell me the best way to do it. and I want somebody tell me how use Ninject.Extensions.Conventions in Item,don't tell me the concrete syntex,I want to know how to organize my class and Interface let bind interface easier,Thank you for your help!
code example like this:
public interface Ilog
{
//... ...
}
public class A:IIlog
{
//... ...
}
public class B:ILog
{
//... ...
}
public class C:ILog
{
//... ...
}
public interface IData
{
//... ...
}
public class H:IData
{
//... ...
}
public class E:IData
{
//... ...
}
public class G:IData
{
//... ...
}
public interface IBase
{
//... ...
}
public class H:IBase
{
//... ...
}
public class I:IBase
{
//... ...
}
public class J:IBase
{
//... ...
}
now,I want resolve interface Ilog to A,IData to E,IBase to H,how can I Do with Ninject.Extensions.Conventions? if many interface like this,how can I do?

Related

Is it ok to override a virtual method but provide no implementation?

I'm trying to create a class heirachy for a game, there is an Item class which is the base class for all items in the game. The problem is that some derived items (like potion) might not implement some of the abstract methods defined by the item.
Is it ok for derived classes to implement an abstract method with "do nothing"?
Example: https://dotnetfiddle.net/jJABN1
using System;
using System.Collections.Generic;
public abstract class Item
{
public abstract void Use();
}
public class Potion : Item
{
public override void Use()
{
// do nothing
return;
}
}
public class Sword : Item
{
public override void Use()
{
Console.WriteLine("Sword used!");
return;
}
}
public class Program
{
public static void Main()
{
List<Item> items = new List<Item>();
Item potion = new Potion();
Item sword = new Sword();
items.Add(potion);
items.Add(sword);
for (int i = 0; i < items.Count; i++)
{
Item item = items[i];
item.Use();
}
}
}
One of Robert Martin's SOLID Principles - Interface Segregation Principle addresses this situation. It basically says that a client should not be exposed to methods it doesn't need.
An example of violating the Interface Segregation Principle:
// Abstraction
public abstract class Printer
{
public abstract void Print();
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
// Basic printers can't scan
}
}
This is usually solved by separating an abstract class to multiple smaller abstract classes that can optionally inherit one other:
// Abstractions
public abstract class Printer
{
public abstract void Print();
}
public abstract class AllInOnePrinter : Printer
{
public abstract void Scan();
}
// Implementations
public class SomeAllInOnePrinter : AllInOnePrinter
{
public override void Print()
{
Console.WriteLine("Printing...");
}
public override void Scan()
{
Console.WriteLine("Scanning...");
}
}
public class SomeBasicPrinter : Printer
{
public override void Print()
{
Console.WriteLine("Printing...");
}
}
Technically, there could be an edge-case (should be uncommon!) where a deriving class doesn't need to implement all the methods, in such a case I'd rather it to override and throw an error to signal the user that this method should not be used.
That said, in the provided example there is only one method, so the question is: if a derived class doesn't need this method - why do you need to inherit the abstract class to begin with? if it's just in order to provide an example that's understandable - but better improve the example to include other methods that are used in the derived class.

OOP - Override init method called in constructor

I have a simple class hierarchy of two classes. Both classes call an init-method specific to that class. Therefor the init-method is overriden in the subclass:
class A
{
public A() { this->InitHandlers(); }
public virtual void InitHandlers() { // load some event handlers here }
}
class B: public A
{
public B() { this->InitHandlers(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
I know this is evil design:
The call of an overriden method from constructor is error-prone.
B::InitHandlers() would be called twice with this setup.
But semantically it makes sense to me: I want to extend the behaviour of class A in class B by loading more handlers but still keeping the handlers loaded by class A. Further this is a task that has to be done in construction. So how can this be solved with a more robust design?
You can do something like this:
class A
{
protected boolean init = false;
public A() { this->Init(); }
public virtual void Init() {
if (!this->init) {
this->init = true;
this->InitHandlers();
}
}
public virtual void InitHandlers() {
// load some event handlers here
}
}
class B: public A
{
public B() { this->Init(); }
public virtual void InitHandlers() {
// keep base class functionality
A::InitHandlers();
// load some other event handlers here
// ...
}
}
You can see it as a design pattern template method.

ninject binding for specify class

if I have the interface interfaceA
public interface IInterfaceA
{
void MethodA();
void MethodB();
}
and I have the classA
class ClassA:IInterfaceA
{
public void MethodA()
{
}
public void MethodB()
{
}
}
it's ok that I use ninject's bind,but when it comes that I have a method that called MethodC,I think the method should only exists in classA(just for classA) and should not be defined in InterfaceA,so how to use ninject'bind when just calling like this:
var a = _kernel.get<IInterfaceA>()
should I convert the result into ClassA ? (is that a bad habbit?) or there are another solution
Usually this is needed when you want interface separation but need both interfaces to be implemented by the same object since it holds data relevant to both interfaces. If that is not the case you would be able to separate interfaces and implementation completely - and then you should do so.
For simplicitys sake i'm going to asume Singleton Scope, but you could also use any other scope.
Create two interfaces instead:
public interface IInterfaceA {
{
void MethodA();
}
public interface IInterfaceC {
void MethodC();
}
public class SomeClass : IInterfaceA, IInterfaceC {
....
}
IBindingRoot.Bind<IInterfaceA, IInterfaceB>().To<SomeClass>()
.InSingletonScope();
var instanceOfA = IResolutionRoot.Get<IInterfaceA>();
var instanceOfB = IResolutionRoot.Get<IInterfaceB>();
instanceOfA.Should().Be(instanceOfB);
Does this answer your question?

use 2 class by only calling a single class

class merged(){
//i want to be able to use class sample1 and sample2 by just calling this merged class
}
class sample1(){}
class sample2(){}
Or doing this isnt ideal? can you please suggest how can I implement this more efficiently?
Composition?
Class merged(){
sample1 s1 = new sample1();
sample1 s2 = new sample2();
void doSomething1()
{
s1.dosomething();
}
void doSomething2()
{
s2.dosomething();
}
}
You can go one of the ways (or a mixture of a couple of ways) as shown below (Note: Java convention is to have the first letter of class names capital):
public interface Sample1() {
// abstract methods
}
public class Sample2() {
// whatever
}
public class Merged() extends Sample2 implements Sample1 {
// whatever
}
OR
public class Sample1() {
// abstract methods
}
public class Sample2() {
// whatever
}
public class Merged() {
Sample1 ob = new Sample1();
Sample2 ob2 = new Sample2();
}
OR
public interface Sample1() {
// abstract methods
}
public abstract Sample2() {
// abstract and other methods
}
public class Merged() extends Sample2 implements Sample1 {
// whatever
}
OR
public interface Sample1() {
// abstract methods
}
public interface Sample2() {
// abstract methods
}
public class Merged() implements Sample1, Sample1 {
// whatever
}
You should do this with interfaces. Modern Object-Oriented programming languages don't support multiple inheritance (believe me, it's a good thing that they don't) so you need to fix this by using interfaces.
Here's an example in Java:
public interface GasolineUser {
public double getGasolineGallonsLeft();
}
public interface MusicPlayer {
public void playMusic();
}
public class Car implements GasolineUser, MusicPlayer {
public double getGasolineGallonsLeft(){
// return gallons left
}
public void playMusic(){
// play music
}
}
Note that Car in this case is both a GasolineUser AND a MusicPlayer, so it can be passed to any method that requires one or any method that requires the other. Similar inheritance exists in C#. For more information on the usefulness of interfaces, do a google search on OOP Interfaces.

How to design around lack of multiple inheritance?

Using interfaces won't work because I want a single implementation. Using this solution would end in a lot of redundant code because I plan on having quite a few sub classes (composition vs inheritance). I've decided that a problem-specific design solution is what I'm looking for, and I can't think of anything elegant.
Basically I want classes to have separate properties, and for those properties to be attached at design time to any sub class I choose. Say, I have class 'ninja'. I would like to be able to make arbitrary sub classes such as 'grayNinja' where a gray ninja will always have a sword and throwing stars. Then possibly 'redNinja' who will always have a sword and a cape. Obviously swords, stars, and capes will each have their own implementation - and this is where I can't use interfaces. The closest solution I could find was the decorator pattern, but I don't want that functionality at runtime. Is the best solution an offshoot of that? Where inside the Black Ninja class constructor, I pass it through the constructors of sword and throwingStar? (those being abstract classes)
haven't coded in a while and reading hasn't gotten me too far - forgive me if the answer is simple.
Edit: Answered my own question. I can't mark it as 'answer' until tomorrow. Please let me know if there's a problem with it that I didn't catch. All the reading this problem forced me to do has been awesome. Learned quite a bit.
You want classes to have separate properties. Have you considered coding exactly that?
For example, you want a RedNinja that is-a Ninja that has-a sword and cape. Okay, so define Ninja to have an inventory, make it accessible through Ninja, and pass in an inventory through RedNinja's constructor. You can do the same thing for behaviors.
I've done once a similar app. with a earlier "C++" compiler that supported only single inheritance and no interfaces, at all.
// base class for all ninjas
public class Ninja {
// default constructor
public Ninja() { ... }
// default destructor
public ~Ninja() { ... }
} // class
public class StarNinja: public Ninja {
// default constructor
public StarNinja() { ... }
// default destructor
public ~StarNinja() { ... }
public void throwStars() { ... }
} // class
public class KatannaNinja: public Ninja {
// default constructor
public KatannaNinja() { ... }
// default destructor
public ~KatannaNinja() { ... }
public void useKatanna() { ... }
} // class
public class InvisibleNinja: public Ninja {
// default constructor
public InvisibleNinja() { ... }
// default destructor
public ~InvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class FlyNinja: public Ninja {
// default constructor
public FlyNinja() { ... }
// default destructor
public ~FlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class InvincibleNinja: public Ninja {
// default constructor
public InvincibleNinja() { ... }
// default destructor
public ~InvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class SuperNinja: public Ninja {
StarNinja* LeftArm;
InvincibleNinja* RightArm;
FlyNinja* LeftLeg;
KatannaNinja* RightLeg;
InvisibleNinja* Body;
// default constructor
public SuperNinja() {
// -> there is no rule to call composed classes,
LeftArm = new StarNinja();
RightArm = new InvincibleNinja();
LeftLeg = new FlyNinja();
RightLeg = new KatannaNinja();
Body = new InvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
Im afraid, that the most close example is the composition design pattern. In order, to become more similar to inheritance, I make a generic base class that all composite classes share, and I make a main class that will be the result of the multiple inheritance, that has a copy of all the public methods of the component classes.
If you want to use interfaces, to enforce that main class have all important methods,
then make an interface that matches each composing class, and implemented in the main class.
public interface INinja {
public void NinjaScream() { ... }
} // class
public interface IStarNinja {
void throwStars();
} // class
public interface IKatannaNinja {
void useKatanna();
} // class
public interface IInvisibleNinja {
void becomeVisible();
void becomeInvisible();
} // class
public interface CFlyNinja {
void fly();
void land();
} // class
public interface IInvincibleNinja {
void turnToStone() { ... }
void turnToHuman() { ... }
} // class
// base class for all ninjas
public class CNinja: public INinja {
// default constructor
public CNinja() { ... }
// default destructor
public ~CNinja() { ... }
public void NinjaScream() { ... }
} // class
public class CStarNinja: public CNinja, INinja {
// default constructor
public CStarNinja() { ... }
// default destructor
public ~CStarNinja() { ... }
public void NinjaScream() { ... }
public void throwStars() { ... }
} // class
public class CKatannaNinja: public CNinja, IKatannaNinja {
// default constructor
public CKatannaNinja() { ... }
// default destructor
public ~CKatannaNinja() { ... }
public void NinjaScream() { ... }
public void useKatanna() { ... }
} // class
public class CInvisibleNinja: public CNinja, IInvisibleNinja {
// default constructor
public CInvisibleNinja() { ... }
// default destructor
public ~CInvisibleNinja() { ... }
public void becomeVisible() { ... }
public void becomeInvisible() { ... }
} // class
public class CFlyNinja: public CNinja, IFlyNinja {
// default constructor
public CFlyNinja() { ... }
// default destructor
public ~CFlyNinja() { ... }
public void fly() { ... }
public void land() { ... }
} // class
public class CInvincibleNinja: public CNinja, IInvincibleNinja {
// default constructor
public CInvincibleNinja() { ... }
// default destructor
public ~CInvincibleNinja() { ... }
public void turnToStone() { ... }
public void turnToHuman() { ... }
} // class
// --> this doesn't need to have the same superclass,
// --> but, it helps
public class CSuperNinja: public CNinja,
IKatannaNinja,
IInvisibleNinja,
IFlyNinja,
IInvincibleNinja
{
CStarNinja* LeftArm;
CInvincibleNinja* RightArm;
CFlyNinja* LeftLeg;
CKatannaNinja* RightLeg;
CInvisibleNinja* Body;
// default constructor
public CSuperNinja() {
// -> there is no rule to call composed classes
LeftArm = new CStarNinja();
RightArm = new CInvincibleNinja();
LeftLeg = new CFlyNinja();
RightLeg = new CKatannaNinja();
Body = new CInvisibleNinja();
}
// default destructor
public ~SuperNinja() {
// -> there is no rule to call composed classes
delete LeftArm();
delete RightArm();
delete LeftLeg();
delete RightLeg();
delete Body();
}
// --> add all public methods from peers,
// --> to main class
public void throwStars() { LeftArm->throwStars(); }
public void useKatanna() { RightLeg->useKatanna(); }
public void becomeVisible() { Body->becomeVisible() }
public void becomeInvisible() { Body->becomeInvisible() }
public void fly() { LeftLeg->fly() }
public void land() { LeftLeg->land() }
public void turnToStone() { RightArm->turnToStone(); }
public void turnToHuman() { RightArm->turnToHuman(); }
} // class
I know this solution is complex, but, seems that there is not another way.
Cheers.
Alright so mix-ins through extension methods are going to be my preferred route. I couldn't figure out how to use dynamic proxies in vb.net (seemed to require libraries with lots of documentation that didn't cover specifically what I needed). Dynamic proxies also seems to be a bit dirtier of a solution than using extension methods. Composition would have been what I defaulted to if the previous two didn't work.
So one problem with extension methods, is that the code gets a little dirtier if you want to hold variables. Not much though. Another problem is that all the extension methods must be defined in modules, so the code might look a little goofy to a new eye. I will solve this by defining my interface and module with the corresponding extension method in the same file.
finally, here's some sample vb.net code if you don't want to see a full fledged example through the link.
Imports System.Runtime.CompilerServices 'for extension methods
Public Interface ISword
End Interface
Public Interface IThrowingStar
End Interface
Module ExtensionMethods
<Extension()>
Public Sub swingSword(ByVal hasASword As ISword)
Console.WriteLine("Sword has been swung")
End Sub
<Extension()>
Public Sub throwStar(ByVal hasAStar As IThrowingStar)
Console.WriteLine("Star has been thrown")
End Sub
End Module
Public Class RedNinja
Inherits Ninja
Implements IThrowingStar, ISword
Public Sub New()
End Sub
End Class
Public MustInherit Class Ninja
private curHealth as Integer
Public Sub New()
curHealth = 100
End Sub
Public Function getHP() As Integer
Return curHealth
End Function
End Class
Module Module1
Sub main()
Console.WriteLine("Type any character to continue.")
Console.ReadKey()
Dim a As New RedNinja
a.swingSword() 'prints "Sword has been swung"
a.throwStar() 'prints "Star has been thrown"
Console.WriteLine("End of program - Type any key to exit")
Console.ReadKey()
End Sub
End Module
Dirty solution, if you simply must have multiple inheritance, is using something like dynamic proxies in Java.
But I guess you're probably programming in C#, and this is language agnostic question, so here goes language agnostic answer: check out composite and factory design patterns, that should give you some ideas.
Also, it might not be needed to pass everything in constructor. Check out IoC pattern as well.