Design Pattern for late binding class (without switch case for class assignment) - oop

I have a base class where all common functions are written. I many classes which override this functions by virtual keyword. Like,
public class Base
{
public virtual void sample()
{
..............
}
}
public class a : Base
{
public override sample()
{
}
}
public class implement
{
public void ToSample()
{
Base baseclass = new Base();
Switch(test)
{
case a: baseclass = a();
break;
case b: baseclass = b();
break;
}
baseclass.sample();
}
}
This perfect code for current situation but now I have more class to be assign in switch case. It is not good practice for adding huge amount of cases so I want something that automatically assign child class.
Is anybody know something to be implement ?

As stated in the comment, you can decouple the implementation by using dependency injection. Note however, that in some cases you have no choice but doing that kind of switch (e.g. when you need to create a class based on a text received in a socket). In such cases the important thing is to always keep the switch statement encapsulated in one method and make your objects rely on it (or, in other words, don't copy-and-paste it everywhere :)). The idea here is too keep your system isolated from a potentially harmful code. Of course that if you add a new class you will have to go and modify that method, however you will only have to do it in one time and in one specific place.
Another approach that I have seen (and sometimes used) is to build a mapping between values an classes. So, if your class-creation switch depends on an integer code, you basically create a mapping between codes and classes. What you are doing here is turning a "static" switch into a dynamic behavior, since you can change the mappings contents at any time and thus alter the way your program behaves. A typical implementation would be something like (sorry for the pseudocode, I'm not familiar with C#):
public class implement
{
public void ToSample()
{
class = this.mapping.valueForKey(test);
Base baseclass = new class();
baseclass.sample();
}
}
Note however that for this example to work you need reflection support, which varies according to the language you are using (again, sorry but I don't know the C# specifics).
Finally, you can also check the creational family of patterns for inspiration regarding object creation issues and some well known forms of solving them.
HTH

Related

Implementing multiple overloaded functions vs doing inside checking/validation for enforcing business logic

This is a general issue, but i will demonstrate it using the following problem:
I want to model airCrafts. now, for every aircraft there is one capability that is loaded with: attackCapability, IntelligenceCapability and BdaCapability. Not all aircraft can be loaded with all capabilities - every airCraft has its own potential capabilities that is supports and can be loaded with.
I want to implement this business logic with composition:
every aircraft object will hold a private member of type Capability (every capability will be implemented by a class that inherits from this abstract class/interface).
Now - I want to design a code that will enforce the business logic - i.e. will not allow any programmer to load an aircraft with an ability it doesn't support.
I have two options for doing this:
implement several overloaded version of the SetCapability() function - each one with the type of capability i want to support. For example:
public void SetCapability(AttackCapability capability);
public void SetCapability(BdaCapability capability);
That way the user can't load the aircraft with forbidden capability - and if he/she will try doing so, there will be a compilation erorr - i.e. that IDE will show some error message.
implement one function: public void SetCapability(Capability capability)
and doing some checking inside it. something like this:
public void SetCapability(Capability capability){
if(capability.getType() != typeOf(AttackCapability) || capability.getType() != typeOf(BdaCapability){
throw new InvalidOperationException();
}
_capability = capability;
}
the disdvantage here is that misuse of the user will be identified only at runtime instead at compiletime (much harder to identify and more bug prone), but as opposed to the previous option - it doesn't make you write several overloaded function which may cause the class to look heavy, strange and less readable for the inexperienced programmer.
(code reusability is not a big issues, because we always can implement private function like: private void SetCapabiltiy(Capability capability); which do the setting logic and every public overloaded SetCapability function will call it).
I feel that both option have their advantages and disadvantages as i described above.
I tend to prefer the first one, because it is more safe and hermeric - but it frequently causes my code to look "ugly" and some programmers may interprete it as duplicated code and don't understand the point...
I would like to hear your opinion for this issues, and maybe you have some better designs for this problem.
I couldn't understand your #1 option, but I think in any option you said you need to check permitted capabilities statically. This would result to change the code in future and would break the OCP. Instead of this I thought that maybe we can take advantage of dynamic dispatch here and let it to check types.
IMHO you can create final concrete classes and set required access modifiers to private in the concretes and then use factories(actually the abstract factory pattern looks suitable here) to hide object creation from clients to enforce business logic and the use the technique(which is my term) that referencing the same type used in Decorator or Chain of Responsibility patterns to keep capabilities in a chain by which you may have extra possibilities to dynamically check the capabilities to apply the behavior they require instead of just in a list( which could be used with Command pattern also)
As a note, the section where you mention as your second option limits the extensibility and generally manual type check is considered as bad practice in a dynamically dispatched or duck typed OOP language runtime. I know the fact that you are checking the field not a type but this is also a manual control and capability as the name implies is a behavior not state.
Finally since the aircrafts don't have same functionalities, but varying behaviors Visitor pattern could be used to design functionalities by which you create method classes instead of classes containing methods.
In addition, a Map<Aircraft, List<Capability>> could be used by keeping in a config object chek the features when creating objects by using DI.
//Capability types
interface Capable {
do();
}
class Attacker implements Capable {
private Capable capability;
public Attacker(Capable capability) { //to keep track of next/linked capability
this.capability = capability;
}
public do(String request) {
this.attack();
this.capability.do();//or instead of this decorator you could use chain of responsibility with next() and handle() below.
}
//to select features in some functionality.
public handle(String request) {
if ("attack".equals(request)) { //just to show what you can by keeping a reference to same type
this.attack();
} else {
this.capability.do();
}
}
public next(Capable capability) {
this.capability = capability;
}
}
class Intelligent implements Capable {
//similar to above.
}
//Aircraft types
class F111 implements Aircraft {
private Capable capability;
//or store capabilities in a list and check with config mapper object(maps aircrafts with its capabilities in a Map<Aircraft.TYPE, List<Capable> capabilities)
//private List<Capable> capabilities;
//other state
Aircraft(Capable capability) { //or create a factory
this.capability = capability;
}
//behaviors
doSth() {
this.capability.do();
}
}
class F222 implements Aircraft {
//...
}
//To hide creation of requested aircraft with only its required capabilities from the client
static class AircraftFactory { //dont permit to directly access to Aircraft concretes
static Aircraft getAircraft(String type) {//could be used abstract factory instead of this.
if("f111".equals(type)) {
return new F111(new Attacker(new Intelligent()));
}
else if(...) { new F222(new Intelligent(new Bda())}
else if(...) { new F001(new Default()) }
}
}
class Client {
main() {
//instead of this
//Aircraft f9999 = new Aircraft(new Attacker);
//f9999.doSth();
//enforce client to use factory.
Aircraft aircraft = AircraftFactory.getAircraft("f222");
aircraft.doSth();
}
}

OO Design Principle - Open Closed Principle

I have a Layout Manager Class and this class designed for setting datagrid layout.
Code:
class LayoutManager
{
private object _target;
public LayoutManager(object aDataGrid)
{
_target = aDataGrid;
}
public void SaveLayout(string strProfileID)
{
}
public void LoadLayout(string strProfileID)
{
}
//in future I might add below function
public void ResetLayout()//OtherFunction0
{
}
public void OtherFunction1()
{
}
public void OtherFunction2()
{
}
}
According to OCP "a Class should be open for extension, but closed for modification". If I add the new function in LayoutManager Class, is this action violate the OCP? If yes, what is the proper way to design the class?
I don't think that adding methods to a class in general violates the OCP prinicple,
as this in fact extends the class's behviour.
The problem is if you change existing behaviours.
So that if the code on your added methods might change the behaviour of the existing methods
(because it changes the object's state) that would be a violation.
The correct way to follow the SOLID principals, is to make an interface:
ILayoutManager with the interfaces you want , with documented behaviours.
The class LayoutManager would implement this interface.
Other new methods might be added in a new interface, say ILayoutFoo or added to the existing interface, as long as they won't break the contract of the documented behaviour in the existing methods.
It's not possible to directly answer this without some concrete code.
Generally speaking though, the upshot of the OCP is that when classes derive from your base class and then override methods, the internal invariants shouldn't break because that's modification. There shouldn't be any way for the derived class to change those parts of the class' behaviour. The derived classes can change behaviour or add new functionality by using the parts exposed by the base class.
Whenever we speak about Open-Closed Principle, one important issue comes into play, which is called Strategic Closure.
It should be clear that no significant program can be 100% closed. In general, no matter how “closed” a module is, there will always be some kind of change against which it is not closed. Since closure cannot be complete, it must be strategic. That is, the designer must choose the kinds of changes against which to close his design. This takes a certain amount of prescience derived from experience. The experienced designer knows the users and the industry well enough to judge the probability of different kinds of changes. He then makes sure that the open-closed principle is invoked for the most probable changes.
For example in famous sample of Shape class you just grantee that your program (in side of Client and Shape)just is closed for modification about adding new shape.
public class Shape {
public draw() {
}
}
public class Circle extends Shape {
#Override
public void draw() {
// implementation special to Circle
}
}
public class Client {
...
public drawMyShape(Shape shape) {
shape.draw();
}
...
}
According to this Strategy, when you are designing your program, you should make a decision about the sections that you want to be closed to changes. Therefore, in your example, when you were designing your program, if you decided that your entity (in this case it is GraphCalculator class) should be closed for modification and open to extension regarding to adding new functionality, adding new function in this example violates Open-Closed Principle, due to the fact that it changes implementation in side of client and GraphCalculator class. And solution can be using abstraction, which is mentioned in previous answers.

How do you implement type-specific functionality when using polymorphism does NOT make sense?

A common red flag that an OOP language is not being leveraged properly looks like this:
if (typeof(x) == T1)
{
DoSomethingWithT1(x);
}
else if (typeof(x) == T2)
{
DoSomethingWithT2(x);
}
The standard "fix" for such design issues is to make T1 and T2 both share an interface, either through inheritance of a base type or implementation of a common interface (in languages that support it); for example, in C# a solution might be:
public interface IT
{
void DoSomething();
}
However, sometimes you want to implement functionality that differs based on the type of an object but that functionality does not belong within that object's type; thus polymorphism seems the wrong way to go.
For example, consider the case of a UI that provides a view of a given clump of data. Supposing this view is capable of rendering various layouts and controls depending on the type of data being presented, how would you implement this type-specific rendering without a bunch of if/else statements?
For reasons that I hope are obvious, putting the rendering logic in the type itself strikes me as a very bad decision in this case. On the other hand, without coupling the type of data object to its visual presentation I have a hard time seeing how the if/else scenario is avoided.
Here's a concrete example: I work on a trading application which utilizes many different pricing models for various market products. These different models are represented by types inheriting from a common PricingModel base; and each type is associated with a completely different set of parameters. When the user wants to view the parameters for a particular pricing model (for a particular product), currently these are displayed by a form which detects the type of the model and displays an appropriate set of controls. My question is how this could be implemented more elegantly than it is currently (with a big if/else block).
I realize this probably seems like a very basic question; it's just one of those gaps in my knowledge (of solid OOP principles? design patterns? common sense?) that I figured it's about time to fix.
We are injecting (Spring.Net) such functionality into dictionaries by type.
IDictionary<Type, IBlahImplementor> blahImplementors;
blahImplementors[thingy.GetType()].Do(thingy);
This dictionary could be managed by a kind of repository which provides the functionality.
As an implementation detail, the implementor usually knows the type it depends on an can provide it itself:
interface IBlahImplementor
{
Type ForType { get; }
void Do(object thingy);
}
Then it is added to the dictionary like this:
IEnumerably<IBlahImplementor> blahImplementors;
foreach (var implementor in blahImplementors)
{
blahImplementors.Add(implementor.ForType, implementor);
}
Remark: IMHO, it is very important to understand that some things do NOT belong into a class, even if providing subtype-specific implementations would make life much easier.
Edit: Finally understood your concrete example.
It is actually about instancing the right UI control to show the pricing models parameters. It should be possible with the pattern I described above. If you don't have a single UI control for a pricing model, you either create it or you write a UI configurer or something like this which sets up the required controls.
interface IPricingModelUiConfigurer
{
Type PricingModelType { get; }
void SetupUi(Control parent, IPricingModel model);
}
you can use common interface approach as you describe and Command pattern to trigger methods with "functionality does not belong within that object's type". I think this won't break solid OOP principles.
What you described is pretty much exactly the use case for the Visitor Pattern.
EDIT: For your concrete example, you could apply the visitor pattern like this:
// interface used to add external functionality to pricing models
public interface PricingModelVisitor {
void visitPricingModel1(PricingModel1 m);
void visitPricingModel2(PricingModel2 m);
...
}
// your existing base-class, with added abstract accept() method to accept a visitor
public abstract class PricingModelBase {
public abstract void accept(PricingModelVisitor v);
...
}
// concrete implementations of the PricingModelBase implement accept() by calling the
// appropriate method on the visitor, passing themselves as the argument
public class PricingModel1 : PricingModelBase {
public void accept(PricingModelVisitor v) { v.visitPricingModel1(this); }
...
}
public class PricingModel2 : PricingModel {
public void accept(PricingModelVisitor v) { v.visitPricingModel2(this); }
...
}
// concrete implementation of the visitor interface, in this case with the new
// functionality of adding the appropriate controls to a parent control
public class ParameterGuiVisitor : PricingModelVisitor {
private Control _parent;
public ParameterGuiVisitor(Control parent) { _parent = parent; }
visitPricingModel1(PricingModel1 m) {
// add controls to _parent for PricingModel1
}
visitPricingModel2(PricingModel2 m) {
// add controls to _parent for PricingModel1
}
}
now, instead of using a big if-else block when you need to display the edit-controls for the parameters of a specific subtype of PricingModelVisitor, you can simply call
somePricingModel.accept(new ParameterGuiVisitor(parentControl))
and it will populate the appropriate GUI for you.

When is an "interface" useful?

OOP interfaces.
In my own experience I find interfaces very useful when it comes to design and implement multiple inter-operating modules with multiple developers. For example, if there are two developers, one working on backend and other on frontend (UI) then they can start working in parallel once they have interfaces finalized. Thus, if everyone follows the defined contract then the integration later becomes painless. And thats what interfaces precisely do - define the contract!
Basically it avoids this situation :
Interfaces are very useful when you need a class to operate on generic methods implemented by subclasses.
public class Person
{
public void Eat(IFruit fruit)
{
Console.WriteLine("The {0} is delicious!",fruit.Name);
}
}
public interface IFruit
{
string Name { get; }
}
public class Apple : IFruit
{
public string Name
{
get { return "Apple"; }
}
}
public class Strawberry : IFruit
{
public string Name
{
get { return "Strawberry"; }
}
}
Interfaces are very useful, in case of multiple inheritance.
An Interface totally abstracts away the implementation knowledge from the client.
It allows us to change their behavior dynamically. This means how it will act depends on dynamic specialization (or substitution).
It prevents the client from being broken if the developer made some changes
to implementation or added new specialization/implementation.
It gives an open way to extend an implementation.
Programming language (C#, java )
These languages do not support multiple inheritance from classes, however, they do support multiple inheritance from interfaces; this is yet another advantage of an interface.
Basically Interfaces allow a Program to change the Implementation without having to tell all clients that they now need a "Bar" Object instead of a "Foo" Object. It tells the users of this class what it does, not what it is.
Example:
A Method you wrote wants to loop through the values given to it. Now there are several things you can iterate over, like Lists, Arrays and Collections.
Without Interfaces you would have to write:
public class Foo<T>
{
public void DoSomething(T items[])
{
}
public void DoSomething(List<T> items)
{
}
public void DoSomething(SomeCollectionType<T> items)
{
}
}
And for every new iteratable type you'd have to add another method or the user of your class would have to cast his data. For example with this solution if he has a Collection of FooCollectionType he has to cast it to an Array, List or SomeOtherCollectionType.
With interfaces you only need:
public class Foo<T>
{
public void DoSomething(IEnumerable<T> items)
{
}
}
This means your class only has to know that, whatever the user passes to it can be iterated over. If the user changes his SomeCollectionType to AnotherCollectionType he neither has to cast nor change your class.
Take note that abstract base classes allow for the same sort of abstraction but have some slight differences in usage.

Where to put methods used by multiple classes?

To show an example what is this question about:
I have currently a dilemma in PHP project I'm working on. I have in mind a method that will be used by multiple classes (UIs in this case - MVC model), but I'm not sure how to represent such methods in OO design. The first thing that came into my mind was to create a class with static functions that I'd call whenever I need them. However I'm not sure if it's the right thing to do.
To be more precise, I want to work, for example, with time. So I'll need several methods that handle time. I was thinking about creating a Time class where I'd be functions that check whether the time is in correct format etc.
Some might say that I shouldn't use class for this at all, since in PHP I can still use procedural code. But I'm more interested in answer that would enlighten me how to approach such situations in OOP / OOD.
So the actual questions are: How to represent such methods? Is static function approach good enough or should I reconsider anything else?
I would recommend creating a normal class the contains this behavior, and then let that class implement an interface extracted from the class' members.
Whenever you need to call those methods, you inject the interface (not the concrete class) into the consumer. This lets you vary the two independently of each other.
This may sound like more work, but is simply the Strategy design pattern applied.
This will also make it much easier to unit test the code, because the code is more loosely coupled.
Here's an example in C#.
Interface:
public interface ITimeMachine
{
IStopwatch CreateStopwatch();
DateTimeOffset GetNow();
}
Production implementation:
public class RealTimeMachine : ITimeMachine
{
#region ITimeMachine Members
public IStopwatch CreateStopwatch()
{
return new StopwatchAdapter();
}
public DateTimeOffset GetNow()
{
return DateTimeOffset.Now;
}
#endregion
}
and here's a consumer of the interface:
public abstract class PerformanceRecordingSession : IDisposable
{
private readonly IStopwatch watch;
protected PerformanceRecordingSession(ITimeMachine timeMachine)
{
if (timeMachine == null)
{
throw new ArgumentNullException("timeMachine");
}
this.watch = timeMachine.CreateStopwatch();
this.watch.Start();
}
public abstract void Record(long elapsedTicks);
public virtual void StopRecording()
{
this.watch.Stop();
this.Record(this.watch.ElapsedTicks);
}
}
Although you say you want a structure for arbitrary, unrelated functions, you have given an example of a Time class, which has many related functions. So from an OO point of view you would create a Time class and have a static function getCurrentTime(), for example, which returns an instance of this class. Or you could define that the constuctors default behaviour is to return the current time, whichever you like more. Or both.
class DateTime {
public static function getNow() {
return new self();
}
public function __construct() {
$this->setDateTime('now');
}
public function setDateTime($value) {
#...
}
}
But apart from that, there is already a builtin DateTime class in PHP.
Use a class as a namespace. So yes, have a static class.
class Time {
public static function getCurrentTime() {
return time() + 42;
}
}
I don't do PHP, but from an OO point of view, placing these sorts of utility methods as static methods is fine. If they are completely reusable in nature, consider placing them in a utils class.