"Dumb" Wrapper class - oop

I have a class, say Provider, that exposes its funcationality to the above service layers of the system. It has a public method, say GetX(). Now, there are two ways to get the X : XML way and non-XML way. Two "Library" classes implement these two ways, one for each.
Thus, the structure that happens is something as follows :
public class Provider
{
private XmlLib _xmlLib;
private NonXmlLib _nonXmlLib;
public X GetX( // parameters )
{
// validate the parameters
if ( // some condition)
X = _xmlLib.GetX();
else
X = _nonXmlLib.GetX();
return X;
}
// several other such methods
}
internal class XmlLib
{
public X GetX()
{
// Xml way to get X.
}
// several such things to get/send in XML way.
}
internal class NonXmlLib
{
public X GetX()
{
// NonXml way to get X.
}
// several such methods to get/send thing in non-XML way.
}
So its like, the Provider class becomes a sort of a dumb wrapper, which only validates the arguments, and based on one condition, decides which lib to call.
Is this a good implementation? Any better way to implement this?

Let the GetX method be in an interface. from that point on you can have as many classes that you want that implement the interface.
public interface ISomeInterface { X GetX(); }
Now build a class that will implement the factory design pattern (read about it if you do not know it) and let this class accept the condition which will enable it to decide which class that implements the above interface to return.
here's what I said through code:
public class XmlWay : ISomeInterface
{
public X GetX()
{
//your implementation
}
}
public class NonXmlWay : ISomeInterface
{
public X GetX()
{
// Another implementation
}
}
and finally the factory class
public class MyXFactory
{
public static ISomeInterface GetXImplementation(bool someCondition)
{
if (someCondition)
return new XmlWay();
else
return new NonXmlWay();
}
Now see how elegent your code will look:
ISomeInterface xGen = MyXFactory.GetXImplementation(true);
xGen.GetX();
Hope this helps.

Related

Is there a better alternative to check for collections with members with optional interfaces?

I have a configuration registry class which holds a collection of configuration classes with a certain interface. These classes can also have an optional interface. So these classes may look like this in pseudocode:
class ConfigurationRegistry {
private ModuleConfiguration[];
public function ConfigurationRegistry(ModuleConfiguration[] collection) {
this.collection = collection;
}
public function getCollection() {
return this.collection;
}
}
class ConfigurationClass1 implements ModuleConfiguration, SpecificConfiguration {
public function moduleMethod() {
// do something
}
public function specificMethod() {
// do specific thing
}
}
class ConfigurationClass2 implements ModuleConfiguration {
public function moduleMethod() {
// do something
}
}
public interface ModuleConfiguration {
public function moduleMethod();
}
public interface SpecificConfiguration {
public function specificMethod();
}
In my client code I would like to use these configuration classes. Sometimes I need the whole collection of configuration classes and sometimes I only need to collection of configuration classes which implement the SpecificConfiguration interface.
I could filter the collection method by using instanceof or I could loop through the collection and check whether the class implements the interface. But I've read quite a few articles stating online that using instanceof in this case is not considered a good practice.
My question is: is my implementation a good design? If not, do you have any suggestions how I could redesign or improve this?

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?

C# OO Design: case when only ONE abstract method is needed

I have 2 classes that have the exact same logic/workflow, except in one method.
So, I created a abstract base class where the method that differs is declared as abstract.
Below is some sample code to demonstrate my design; can anyone offer suggestions on a better approach or am I heading in the right direction.
I didn't use an interface because both derived classes B and C literally share most of the logic. Is there a better way to do what I am doing below via dependency injection?
public abstract class A
{
public void StageData()
{
// some logic
DoSomething();
}
public void TransformData();
public abstract DoSomething();
}
public class B : A
{
public override void DoSomething()
{
// Do Something!
}
}
public class C : A
{
public override void DoSomething()
{
// Do Something!
}
}
There is nothing wrong with what you have done. To introduce dependency injection into this design would be messy and overkill - you would have to pass in a delegate:
public class ABC
{
public ABC(Action z)
{
_doSomethingAction = z;
}
public void DoSomething()
{
_doSomthingAction.Invoke();
}
private Action _doSomthingAction;
}
There would be few reasons why you want to use this approach - one would be if you needed to execute a callback. So stick with the pattern you have, don't try to overcomplicate things.

Design pattern to save/load an object in various format

I have an object: X, that can be saved or loaded in various formats: TXT, PDF, HTML, etc..
What is the best way to manage this situation? Add a pair of method to X for each format, create a new Class for each format, or exists (as I trust) a better solution?
I'd choose the strategy pattern. For example:
interface XStartegy {
X load();
void save(X x);
}
class TxtStrategy implements XStartegy {
//...implementation...
}
class PdfStrategy implements XStartegy {
//...implementation...
}
class HtmlStrategy implements XStartegy {
//...implementation...
}
class XContext {
private XStartegy strategy;
public XContext(XStartegy strategy) {
this.strategy = strategy;
}
public X load() {
return strategy.load();
}
public void save(X x) {
strategy.save(x);
}
}
I agree with #DarthVader , though in Java you'd better write
public class XDocument implements IDocument { ...
You could also use an abstract class, if much behavior is common to the documents, and in the common methods of base class call an abstract save(), which is only implemented in the subclasses.
I would go with Factory pattern. It looks like you can use inheritance/polymorphism with generics. You can even do dependency injection if you go with the similar design as follows.
public interface IDocument
{
void Save();
}
public class Document : IDocument
{
}
public class PdfDocument: IDocument
{
public void Save(){//...}
}
public class TxtDocument: IDocument
{
public void Save(){//...}
}
public class HtmlDocument : IDocument
{
public void Save(){//...}
}
then in another class you can do this:
public void SaveDocument(T document) where T : IDocument
{
document.save();
}
It depends on your objects, but it is possible, that visitor pattern (http://en.wikipedia.org/wiki/Visitor_pattern) can be used here.
There are different visitors (PDFVisitor, HHTMLVisitor etc) that knows how to serialize parts of your objects that they visit.
I would instead suggest the Strategy pattern. You're always saving and restoring, the only difference is how you do it (your strategy). So you have save() and restore() methods that defer to various FormatStrategy objects you can plug and play with at run time.

Prevent Ninject from calling Initialize multiple times when binding to several interfaces

We have a concrete singleton service which implements Ninject.IInitializable and 2 interfaces. Problem is that services Initialize-methdod is called 2 times, when only one is desired. We are using .NET 3.5 and Ninject 2.0.0.0.
Is there a pattern in Ninject prevent this from happening. Neither of the interfaces implement Ninject.IInitializable. the service class is:
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public void Initialize()
{
// This is called twice!
}
}
And module looks like this:
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<Iservice1, Iservice2, ConcreteService>();
}
}
where Singleton is an extension method defined like this:
public static void Singleton<K, T>(this NinjectModule module) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>(this NinjectModule module)
where T : K, L
{
Singleton<K, T>(module);
module.Bind<L>().ToMethod(n => n.Kernel.Get<T>());
}
Of course we could add bool initialized-member to ConcreteService and initialize only when it is false, but it seems quite a bit of a hack. And it would require repeating the same logic in every service that implements two or more interfaces.
Thanks for all the answers! I learned something from all of them! (I am having a hard time to decide which one mark correct).
We ended up creating IActivable interface and extending ninject kernel (it also removed nicely code level dependencies to ninject, allthough attributes still remain).
Ninject 3
Ninject 3.0 now supports multiple generic types in the call to bind, what you are trying to do can be easily accomplished in a single chained statement.
kernel.Bind<IService1, IService2>()
.To<ConcreteService>()
.InSingletonScope();
Ninject 2
You are setting up two different bindings K=>T and L=>T. Requesting instances of L will return transient instances of T. Requesting K will return a singleton instance of T.
In Ninject 2.0, an objects scope is per service interface bound to a scope callback.
When you have
Bind<IFoo>...InSingletonScope();
Bind<IBar>...InSingletonScope();
you are creating two different scopes.
You are saying
"Binding to IFoo will resolve to the same object that was returned
when .Get was called."
and
"Binding to IBar will resolve to the same object that was returned
when .Get was called."
you can chain the bindings together, but you will need to remove IInitializable as it will cause duplicate initialization when the instance is activated:
kernel.Bind<IBoo>()
.To<Foo>()
.InSingletonScope();
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>()
.ToMethod( ctx => (IBaz) ctx.Kernel.Get<IBoo>() );
or
kernel.Bind<Foo>().ToSelf().InSingletonScope()
.OnActivation(instance=>instance.Initialize());
kernel.Bind<IBaz>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
kernel.Bind<IBoo>().ToMethod( ctx => ctx.Kernel.Get<Foo>() );
in order to get multiple interfaces to resolve to the same singleton instance. When I see situations like this, I always have to ask, is your object doing too much if you have a singleton with two responsibilities?
Update : Pretty sure using V3's multiple Bind overloads will address this; See this Q/A
Good question.
From looking at the source, the initialize bit happens after each Activate. Your Bind...ToMethod counts as one too. The strategy is pretty uniformly applied - there's no way to opt out in particular cases.
Your workaround options are to use an explicit OnActivation in your Bind which will do it conditionally (but to do that in a general way would require maintaining a Set of initialized objects (havent looked to see if there is a mechanism to stash a flag against an activated object)), or to make your Initialize idempotent through whatever means is cleanest for you.
EDIT:
internal interface IService1
{
}
internal interface IService2
{
}
public class ConcreteService : IService1, IService2, Ninject.IInitializable
{
public int CallCount { get; private set; }
public void Initialize()
{
++CallCount;
}
}
public class ServiceModule : NinjectModule
{
public override void Load()
{
this.Singleton<IService1, IService2, ConcreteService>();
}
}
Given the following helpers:
static class Helpers
{
public static void Singleton<K, T>( this NinjectModule module ) where T : K
{
module.Bind<K>().To<T>().InSingletonScope();
}
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
Singleton<T, T>( module );
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
#Ian Davis et al. The problem is that:
class Problem
{
[Fact]
static void x()
{
var kernel = new StandardKernel( new ServiceModule() );
var v1 = kernel.Get<IService1>();
var v2 = kernel.Get<IService2>();
var service = kernel.Get<ConcreteService>();
Console.WriteLine( service.CallCount ); // 3
Assert.AreEqual( 1, service.CallCount ); // FAILS
}
}
Because each activation (per Bind) initialises each time.
EDIT 2: Same when you use the following slightly more stripped down version:
static class Helpers
{
public static void Singleton<K, L, T>( this NinjectModule module )
where T : K, L
{
module.Bind<T>().ToSelf().InSingletonScope();
module.Bind<K>().ToMethod( n => n.Kernel.Get<T>() );
module.Bind<L>().ToMethod( n => n.Kernel.Get<T>() );
}
}
I think one of the option is, you create the object your self in the module and bind your object the each of the interfaces.
BTW, try not to use any container specific code in your production code. If you have to do that, use some helper and isolate them in the module project.
public class ServiceModule : NinjectModule
{
public override void Load()
{
ConcreteService svc = new ConcreteService();
Bind<IService1>().ToConstant(svc);
Bind<IService2>().ToConstant(svc);
....
}
}