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

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?

Related

Ninject factory method with input parameter to determine which implementation to return

I am trying to find a way to have a factory class / method that would take in an object or some kind of identifier (string or type) then based off the input parameter determine which implementation of the interface to create and return.
how do I setup my factory method and register the dependency for the interface? following is what I have roughly.
public class ISampleFactory
{
public ISample GetSample(Type type)
{
// do something here to return an implementation of ISample
}
}
public class SampleA : ISample
{
public void DoSomething();
}
public class SampleB : ISample
{
public void DoSomething();
}
public interface ISample
{
void DoSomethin();
}
Have a look at ninject Contextual Bindings Documentation:
You can either use Named Bindings:
this.Bind<ISample>().To<SampleA>().Named("A");
this.Bind<ISample>().To<SampleB>().Named("B");
or a conditional binding with any of the already available extensions or write your own:
this.Bind<ISample>().To<SampleA>().When(...);
this.Bind<ISample>().To<SampleB>().When(...);
see https://github.com/ninject/ninject/wiki/Contextual-Binding

design pattern query

i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.

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.

"Dumb" Wrapper class

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.

What's the idiomatic way of inheriting data access functionality as well as object properties?

Suppose the following (slightly pseudo-code for brevity):
class Basic
{
String foo;
}
class SomeExtension extends Basic
{
String bar;
}
class OtherExtension extends Basic
{
String baz;
}
class BasicService
{
Basic getBasic()
{
}
}
class SomeExtensionService extends BasicService
{
SomeExtension getSomeExtension()
{
}
}
class OtherExtensionService extends BasicService
{
OtherExtension getOtherExtension()
{
}
}
What would be the most idiomatic, elegant way to implement the get-() service methods with the most possible code reuse?
Obviously you could do it like this:
class BasicService
{
Basic getBasic()
{
Basic basic = new Basic();
basic.setFoo("some kind of foo");
return basic;
}
}
class SomeExtensionService
{
SomeExtension getSomeExtension()
{
SomeExtension someExtension = new SomeExtension;
Basic basic = getBasic();
someExtension.setFoo(basic.getFoo());
someExtension.setBar("some kind of bar");
return someExtension;
}
}
But this would be ugly if Basic has a lot of properties, and also you only need one object, as SomeExtension already inherits Basic. However, BasicService can obviously not return a SomeExtension object.
You could also have the get methods not create the object themselves, but create it at the outermost level and pass it to the method for filling in the properties, but I find that too imperative.
(Please let me know if the question is confusingly formulated.)
EDIT: Okay, so it was. I'll try to explain it better. Say you have two model classes, A and B. You also have two classes for returning objects of class A and B (from a database for instance, with information scattered all over so any ORM doesn't apply). Now, say A and B contains a lot of overlapping information, so it makes sense to refactor into a superclass C and let A and B extend from it. However, the service classes are still particular to A and B and need to duplicate the code for reading the overlapping information. How could you refactor these into a service class C?
I would add constructor to A and B which accepts C and sets the fields accordingly. The advantage over your suggested solution is that your ExtensionServices don't have to know about basic fields.
It looks like you're setting default values to your Basic (and children) objects. It's probably best to do that in their constructors.
public class Basic
{
protected String foo;
// and other properties
public Basic()
{
foo = "some kind of foo";
// assign defaults to all other properties
}
}
public class SomeExtension extends Basic
{
protected string bar;
public SomeExtension()
{
super(); // set the default properties of the base class
bar = "some kind of bar";
}
}
Remember to call super() in the child constructors so that the inherited properties will also be assigned default values.
public class BasicService
{
public Basic getBasic()
{
return new Basic();
}
}
public class ExtensionService extends BasicService
{
#Override
public Basic getBasic()
{
return new SomeExtension();
}
}
At least with this structure, you eliminate having to instantiate two objects in ExtensionService, and you actually don't set default values in the service classes. Since SomeExtension is a child of Basic, you can return a SomeExtension at the end of a function whose declared return type is Basic.