I have an array of different object types (about 15 different types) , they are coming from 3rd party system.
For every type I need to make different transformation.
My original thought is to make some interface with transform function and for every type make a class and run it's own implementation.
But like this I will need to make a really big if statement that checks the object type and make the mapping.
I am trying to learn something new here, so my question is there other ways to deal with this situation?
Have you considered the possibility of using a Visitor?
If you combine the visitor pattern with the use of dynamic, you could get a pretty simple implementation without any if or switch statements, or having to manually create a Type Dictionary with delegates, or similar alternatives.
Using dynamic you can avoid implementing the "accept" part of the design pattern, which I assume is useful to you since these are external types you have no control over.
Meaning, you create something like this:
public interface IVisitor
{
void Visit(OneType element);
void Visit(AnotherType element);
....
}
You implement that visitor, and can later call the implementation using:
visitor.Visit((dynamic)objectToTransform);
You would probably have to handle for exceptions regarding not having an appropriate overload for the Type.
That would solve the part of the problem related to executing a separate method for each type.
Now, depending on what you specifically need to do with each one, if you need automatic property mapping then AutoMapper could be very useful.
You can create a lookup of type and transformation, similar to Java Front Controller pattern.
I'm not sure if this is what you want, but have a look at AutoMapper (or aother mappers). It allows you to easily define rules to map types to other types.
Related
I have an existing base type and I would like to cast it to a derived type base upon the name of the type as a string, so something like this:
public void DoStuffInDerivedType(string derivedName) {
(base as Type.GetType(derivedName)).DoThisThing();
}
I'm pretty sure this can't be done but would be good to know for sure. Thanks
EDIT: I understand that I could construct the object using reflection from the type name but I want use an existing object. And also I know this is generally a bad idea. However I wanted to use this for a SpecFlow BDD Feature.
I'll repeat the advice that you probably don't need to do this, but because I have done this operation before:
Convert.ChangeType(ItemToCast, Type.GetType(stringNameOfType)))
Should work for you.
I don't think you need to cast it to the derived type. You should be able to cast it to the base type and use the shared interface (be it a base class or literal Interface) to perform whatever you want done.
If not, consider adding the behavior as an interface requirement so you can do it that way.
Finally: the one possibility where you'd need to do it this way is if you're overriding the casts...in which case I'm almost certain you can't do this without some heavy duty reflection.
in my application I've got three interfaces ICapture<T>, IDecoder<T, K>, and IBroadcaster<K>.
Now I implement for example a VideoCapture class inheriting from Capture<IntPtr> (IntPtr is the raw data produced by the class). When data is generated by an object of VideoCapture, I firstly want to decode it from T to K, and then broadcast it.
What I want to know is: how would you chain this ? Simply by writing a method like
var data = videoCapture.GetData();
var decoded = decoder.Decode(data);
broadcaster.Broadcast(decoded);
Or are there any design patterns, that I could use? I know of the chain of responsibility pattern. I could imagine writing classes like CaptureHandler, DecoderHandler, and BroadcastHandler inheriting from HandlerBase. HandlerBase would provide mechanisms to hand over objects to the next handler.
var handler1 = new CaptureHandler();
var handler2 = new DecodeHandler();
handler1.SetNext(handler2);
handler1.Handle(object);
But I dunno if this is the best approach for my situation.
Why would you want to avoid the method? It's simple, and I see no disadvantage for your application.
If the GetData => Decode => Broadcast pattern is useful for other captures, you can make the method generic.
You could an instance of each object into the constructor of the next. If for example, every decoder instance needs a video capture instance to work, then you can have a constructor as follows ...
Decoder(VideoCapture<T> captureDevice)
{
}
And do the same thing for the Broadcaster, i.e have a constructor that will take in a decoder instance as a parameter.
In fact, I am not even sure you would need generics. You might do, depending on your application. We can only see a small part in this question after all. Not sure what Types you will be passing into each of these classes either and how the Type parameter will be used inside them.
But if I was to hazard a guess, I think just normal OO hierarchy would be the best, simplest way to go.
So, have a Capture base class, which has the virtual method GetData(). You will then create sub classes for different kinds of Capturing you do. "CapturePal", "CaptureSecam", "CaptureMeSecam" etc. Again, I am guess that sub classing would be enough for you rather than a generic Type parameter (would Capture<float>() as well as Capture<StringBuilder>() be meaningful in your application?)
So once you have a base class and subclasses for your capture functionality, do the same for your Decoder and Broadcaster classes. Base class Decoder, sub class "DivxDecoder", "MpegDecoder". Base class Broadcaster with subclass "TVBroadcaster", "IPBroadcaster", "TCPBroadcaster" etc.
Now, the constructors for each of the base classes will take the other base class as a parameter and call the appropriate methods.
This will allow you to chain them as follows
var myProcessingChain = new TVBroadcaster(new DivxDecoder (new CaptureSecam(inputData))));
assuming that all the capture classes take the same input type.
The other option is to use Interfaces. If your application has some classes that can act as both a capturer and a decoder for example.
Think a bit more about whether you really need Generics. Generics are helpful when you want to reuse algorithms and want to be agnostic to the Type, while enforcing Type safety. Being agnostic to Type is different from being able to accept a set of Types that share a commonality. In this case you can get the commonality among the Types by using inheritance.
I have a set of objects that I want to conform to an interface, say ISpecialObject.
However a part of my implementation I want to encapsulate the instantiation trigger of these specialobjects within the implementation of each ISpecialObject.
So say for instance I have as list of class types that implement ISpecialObject, I then want to go through each one and call a static method like CanCreate(some data) which tells me whether or not to create an instance of one of these.
However, .net doesn't seem to let me specify this static CanCreate as part of the ISpecialObject interface.
Can anyone suggest a way to get around this, or alternatively a better approach to solving the problem of encapsulation of the instantiation of these objects? I may just be thinking about this all wrong.
Thanks.
Edit: I may have phrased some parts of this poorly. I don't want to provide the implementation in the interface, but rather specify that there will be one, and that it will be static. Essentially I want the objects to be self defining by allowing a higher level object to query when to create them at runtime.
From what I understand, your main issue is the instantiation of a set of objects that conform to the same interface. If that is so, you may want to look at the Factory Design Pattern which is the standard way to encapsulate such logic.
.NET does not allow static method declarations on interfaces. They don't really make sense since interfaces are all about the contract and avoid implementation entirely. Static methods are specifically about implementation. Additionally, interface methods are virtual function calls depending on the type of the instance, whereas static methods are independent of an instance or even a class (they could be put on any concrete type).
If you have many implementations of ISpecialObject, you could use a factory pattern. In order to do this, you would define define an interface called ISpecialObjectFactory alongside ISpecialObject:
class ISpecialObjectFactory
{
ISpecialObject CreateInstance(...);
bool CanCreate(...);
}
Each class that implements ISpecialObject should have a corresponding ISpecialObjectFactory (e.g. UserObject would have also have a UserObjectFactory). This would require a bit more code, but it's a common pattern and I believe it solves your problem.
I dont see the issue. The typename is just a prefix when dealing with static methods. It will make no difference what so ever if the static method lives somewhere else.
That said, look at extension methods, which may do want you really want it to :)
Edit: Another option might be using attributes.
We just discussed something very similiar to this on another thread. Extension methods are definitely a way to solve this problem. They can provide an implementation for an interface, and the methods can be treated as static or used as a method on an instance of an object which is being extended.
It is not exactly a duplicate in the way that you've phrased the question, but it is duplicate in nature so check out the link below.
StackOverflow - subclass-needs-to-implement-interface-property-as-static
Maybe you can use an abstract class as super class for your purpose. So the static methods go in the abstract class and all derived classes have that as well. However, I agree to the the posts above that may be using the factory pattern is a better approach here.
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was.
But, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this mechanism to provide statically type checking.
So, dynamic ( OO ) programming languages do use interfaces, even thought they don't statically check them. Just like other data types, for instance in Ruby:
#i = 1;
You don't have to declare i of type FixNum you just use it. Same goes for interfaces, they just flow. The trade-off is, you can't have a static check on that and failures are only show at runtime.
In the other hand Structural type ( or static duck type as I call it :P ) used by languages as Go or Scala, gives the best of both worlds.
1. See Daniel Earwicker comment about CORBA interface keyword
We don't require them, but we do support them. Check out Zope Interfaces (which can be and are used outside of Zope).
It's worth noting that, contrary to what many people will say as a first response, interfaces can be used to do more than document "what methods a class supports". Grzenio touches on this with his wording on "implement the same behaviour". As a specific example of this, look at the Java interface Serializable. It doesn't implement any methods; rather it's used as a "marker" to indicate that the class can be serialized safely.
When considered this way, it could be reasonable to have a dynamic language that uses interfaces. That being said, something akin to annotations might be a more reasonable approach.
Interfaces are used in statically typed languages to describe that two otherwise independent objects "implement the same behaviour". In dynamically typed languages one implicitly assumes that when two objects have a method with the same name/params it does the same thing, so interfaces are of no use.
One key thing about at least some dynamic languages that makes explicit interfaces more than a little awkward is that dynamic languages can often respond to messages (err, “method calls”) that they don't know about beforehand, even doing things like creating methods on the fly. The only real way to know whether an object will respond to a message correctly is by sending it the message. That's OK, because dynamic languages consider it better to be able to support that sort of thing rather than static type checking; an object is considered to be usable in a particular protocol because it is “known” to be able to participate in that protocol (e.g., by virtue of being given by another message).
Interface constructs are used in statically typed languages to teach the type system which objects are substitutable for each other in a particular method-calling context. If two objects implement the same method but aren't related through inheritance from a common base class or implementation of a common interface, the type system will raise an error at compile time if you substitute one for the other.
Dynamic languages use "duck typing", which means the method is simply looked up at runtime and if it exists with the right signature, it's used; otherwise a runtime error results. If two objects both "quack like a duck" by implementing the same method, they are substitutable. Thus, there's no explicit need for the language to relate them via base class or interface.
That being said, interfaces as a concept are still very important in the dynamic world, but they're often just defined in documentation and not enforced by the language. Occasionally, I see programmers actually make a base class that sketches out the interface for this purpose as well; this helps formalize the documentation, and is of particular use if part of the interface can be implemented in terms of the rest of the interface.
Perl has Roles (or traits ), It is more than interfaces unlike java perl roles we can have a implementation check out these links for more on perl roles
http://en.wikipedia.org/wiki/Perl_6#Roles
http://use.perl.org/~Ovid/journal/38649
In C# and Java, interfaces are just abstract classes with all abstract methods. They exist to allow pseudo multiple-inheritance without actually supporting full-blown multiple inheritance and the ambiguity multiple inheritance creates.
Python supports multiple inheritance and has its own way of determining which parent's method should be called when a method exists in multiple parents.
Dynamic languages are Duck Typed
If it walks like a duck and quacks
like a duck, it must be a duck
http://en.wikipedia.org/wiki/Duck_typing
In other words, If you exect an object to suport the Delete() method, than you can just use the
obj.Delete()
method but if the object doesn't support Delete() you get a Runtime error. Statically typed languages wouldn't allow that and throw a compile time error. So you basically trade type safty against faster developement time and flexibility.
Without interfaces you can do something like that in static languages:
void Save(MyBaseClass item)
{
if (item.HasChanges)
item.Save()
}
but that would require every object that you pass to this method to inherit from MyBaseClass. Since Java or C# don't support muliinheritance that isn't very flexible because if your class already inherits another class it cannot inherit from MyBaseClass, too. So the better choise would be to create a ISavable interface and accept that as a input parameter to ensure that item can be saved. Then you have best of both: type safety and flexibility.
public interface ISavable
{
bool HasChanges {get;set;}
void Save();
}
void Save(ISavable item)
{
if (item.HasChanges)
item.Save()
}
The last backdoor is to use object as a parameter if you cannot expect every item that will use your save method to implement the interface.
void Save(object item)
{
if (item.HasChanges)
item.Save()
}
But than again, you don't have compile time checking and probably get a runtime error if someone uses your method with an incompatible class.
I have a warehouse. Sometimes I want to lookup a box location by a name, sometimes by a description, sometimes by a UPC, maybe something else, etc. Each of these lookup methods call the same various private methods to find information to help locate the data.
For example, upc calls a private method to find a rowid, so does name, so does X. So I need to have that method for all of them. I might use that rowid for some way to find a shelf location (it's just an example.)
But my question is should I have an abstract class (or something else) because I am looking up my box in different ways.
In other words, say my code for lookups is very similar for UPC and for location. Each method may call something with (select * from xxxx where location =, or select * from xxxx where upc =). I could just create two different methods in the same class
LocateByUPC(string upc)...
LocateByLocation(string location)...
LocateByDescription(string description)
... again, this would be in one big class
Would there be any reason that I would want a super class that would hold
abstract class MySuper
{
properties...
LocateBox(string mycriteria)...
}
and then inherit that and create a second class that overrides the LocateBox method for whichever version I need?
I don't know why I'd want to do this other than it looks OOD, which really means I'd like to do this if I have a good reason. But, I know of no advantage. I just find that my class gets bigger and bigger and I just slightly change the name of the methods and a little bit of code and it makes me think that inheritance might be better.
Using C# if that matters.
Edit - Would I do this if I only gave someone a .dll with no source but the class definition? The class def. would tell my properties, etc. and what methods to override.
Neither
neither using an abstract class nor an interface will simplify the protocol, i.e. you will still end up with a bunch of LocateXXX methods
I would recommend having a generic Locate(string criteria) method as the basis, and only defining specialized method signatures for the ones you know you will use frequently; the generic can be a catch-all for future expansion in case you need it (and relying on the generic simplifies coding and testing)
It sounds like you might want to implement the design pattern called Template Method. Basically you would define the outline of the lookup algorithm in a base class as final methods, placing common code in those methods. For the methods that require different behavior depending on the type, simply have the base class' final methods call protected methods in the children, and have each child type implement that behavior.
You can take a look online at some resources, just do a google search for Template Method design pattern. Hopefully it will shed some light on your question.
Abstraction helps when you have multiple implementations. And for future-proofing (hoping that a newer implementation will crop up). An interface acts as a contract between the client and the implementer. This is an invariant. Implementations are free to add any number of methods they wish to. Do you have any such needs?
Does that help answer your question?
What you are proposing is (basically) the Strategy pattern. I don't like to link to wikipedia, but its a good place to start at least. Take a look at the pros and cons and see if it would be beneficial to you.
I don't think there's really a need for you to do it this way. You can simply make the LocateBox method public and have it call private helpers based on which search you want to do. It's generally a bad idea to overly complicate your class structure just for the sake of using some OO design principles. Wait until you find a need for them, and then refactor appropriately. This will help point out what is really necessary and what is a waste of your time.
Edit: Another approach that I was thinking of would be to create a data class that has properties based on the various things you could search by. Ie. a BoxSearchData class that has properties such as UPC, etc, and then pass that to LocateBox() and construct the query as necessary based on the properties that are null. This would help you construct searches on multiple criteria later down the line.
It wouldn't seem necessary in my opinion. Just have a single repository that has the different search functions. Then just use the functions you need when they're needed.
However, the interface portion would only become useful if you have tools that are queueing up different types of searches. Then you could have a factory creating different types of Search classes that all implement an Interface. At which point you could enumerate through your queued Search classes, cast to the interface, and execute the function which would be virtual and point to the correct search type. Example: ReturnDataObject GetItem(object param);
On a side note, there are other uses for interfaces when pulling data. That is just the first example that comes to mind.
When in this example you look closely, you see that only the property, used for lookup, changes. When representing this in an OO way, you end up with a class I would call "Lookup" (representing a search, maybe in SQL, maybe in another query language: an object that can return a rowId based on some property and searched-for value of that property.
The real behavioral change would be in the query language. So if you are to create an abstract class or an interface, it should serve that purpose. The concern of variation in property and value can be separated by adding a "property" argument to the query call.
An abstract class is useful when you need a substantial amount of
functionality to be identical across the subclasses, for example in a
shopping cart with multiple methods of payment available, you could
have an abstract class which defines a generic payment method, and
have subclasses inherit from the superclass for each actual payment
method you want to support (paypal, credit card, account, etc). The
mechanics of how a payment is authorized would be different for each
subclass, but they all perform essentially the same function - they
validate that a user can prove that they can pay for the goods or
services in question.
An example of where an interface is useful is where you have unrelated
items that need to provide some similar functionality in a uniform
way. For example, you might have a CMS where articles are stored in a
database, but where the system caches them to disc as well as HTML
pages until the article in the database is modified, at which point
the physical file is deleted until the next time someone access the
copy in the database. Your CMS might also support the ability for
users to upload images, PDFs, etc to be stored for access on the disc,
but you definitely don't want these files to be deleted as the copy on
the disc represents the file itself and not a cached version. In this
case, you could create a Cacheable interface that says what methods a
class which is cached to disc needs to implement, while leaving it up
to the class itself to implement them. This makes more sense as
classes that represent different kinds of data almost certainly need
to implement their caching scheme (if any) differently.
Every class that allows caching would be defined as Class
implements Cacheable, which is something you can then check for in
your code. Less experienced coders might test the class of an object
they are working with by getting the class and processing the result
with a big switch statement. This isn't the correct approach because
it means that you're assuming that certain classes objects implement
certain functionality, and if you add a new class to the system you
need to modify every switch statement in your software to take it into
account. If yo uimplement an interface you can test if an object
implements that interface with the instanceof keyword.
if ($thisObject instanceof Cacheable)
{
// Manage item's cache
}
This approach is better because it eliminates the switch statement and
thus makes your software easier to maintain. If you add a new class
to the system that also implements its own caching scheme then you
just need to declare that it implements Cacheable. As the interface
requires all classes to implement it to declare the methods specified
in the interface you can be sure that any class that implements
Cacheable will provide certain methods for you to use. Your code
doesn't need to know how the class implements these methods, just that
it does implement them.
These concepts are somewhat trickier to explain than to actually learn
to use I'm afraid, hopefully I've got the basic ideas across well
enough for you to figure them out for yourself.
Obviously the entity that is polymorphic here is the constraint. Using string is the quick and dirty way of achieving the same but your type system is completely out of the loop and garbage string values will be just as valid for input as meaningful constraint specs.
So,
LocateBy (Constraint constraint);
and
abstract class Constraint {
String toString ();
}
class LocationConstraint extends Constraint { /* ... */}
etc.