Assuming I have a list of financial transactions, I have a need to execute a list of validation rules against those transactions. An example would be I have a transaction to purchase a product, however first I need to validate that the account in the transaction has enough available funds, that the product is not sold out etc. As a result of these many rules the transaction will be marked as rejected, as well as an error code should be specified.
Naturally I am thinking towards fronting my rules with an interface, allowing the executing code to roll through the rules executing each one until the first one rejects the transaction.
Each rule will require to be configured with parameters (ex. ValidateMinimumBalance will need to know that minimumBalance = 30). The result of a rule executing can be as simple as settings the rejection code on the transaction object, and the error code; or it can be as complicated as automatically modifying multiple other properties of the transaction.
My basic understanding of design patterns points to me either Strategy or Command patterns, but I am not entirely sure which one is better suited for this scenario.
Command Pattern
Each command will implement some sort of IValidate interface
The constructor of the command will take an instance of the transaction as the receiver in order to be able to read/validate the transaction as well as modify aspects of it. The constructor will also take an array of key/value pairs as parameters for the validation logic.
When I try to picture how the Strategy Pattern fits this scenario it looks very similar. In most examples the strategy is a simple object with a single method, however in my case the strategy will need a reference to the transaction as well as validation parameters.
Strategy is more used to swap out algorithms, its not really used for chaining validations. If you are going to have a pattern where you have one validation per type then you could use the strategy, if you are finding your having to use multiple validators, or the need to reuse validators. I think you are going to have to either find a new way to do it (aka COR) or within your strategy use the COR.
I actually would answer other. I think a combination chain of responsibility pattern and the composite pattern, or decorator for validators is much more suited for your needs.
Typing up an example implementation now.. but at a high level
Chain of Responsiblity
The design would revolve around something like:
abstract class Handler
{
protected Handler next;
public Handler(Handler h){
this.next = h;
}
public abstract bool Validate(Request request);
public abstract void Handle(Request request);
}
class CoreLogic: Handler
{
public CoreLogic(Handler handle) : base(handle){
}
public override void Validate(Request request){
return True
}
public override void Handle(Request request){
if(this.Validate(request)){
if(next!= null){
next.Handle(request);
}
}
}
}
class ValidBalance: Handler
{
public ValidBalance(Handler handle) : base(handle){
}
public override void Validate(Request request){
return True
}
public override void Handle(Request request){
if(this.Validate(request)){
if(next!= null){
next.Handle(request);
}
}
}
}
class MainApp
{
static void Main(){
Handler h = new ValidateBalance( new CoreLogic(null));
h.Handle(new Request());
}
}
Other useful links:
Chain of Responsiblity wikipedia
A Strategy would be something use to 'parameterize' a Command (telling it how parts of the operation should be executed).
When I try to picture how the Strategy Pattern fits this scenario it looks very similar.
Similar? It should look identical.
The distinction is one of how the context and delegation works. In principle a Command is the "active" agent. A Strategy is injected into some active agent. That distinction is pretty subtle.
It barely changes the design. What does change is the expectation.
Command objects (more-or-less) stand alone. They're built to do their work, and then they can vanish. No one cares about them any more. Perhaps they also use the Memento pattern, and have some future life, but perhaps not.
Strategy objects (more-or-less) live with the object into which they're injected. A Strategy would be part of some larger object, and could be replaced by a different implementation without breaking or changing anything else.
But the essential interface is largely the same.
In most examples the strategy is a simple object with a single method,
Those are poor examples.
however in my case the strategy will need a reference to the transaction as well as validation parameters.
Not unusual. Nothing wrong with it.
but I am not entirely sure which one
is better suited for this scenario
Neither :)
I strongly recommend to look at Interpreter. Actually your validator rules are just predicates formulated for your transactions. It's quite possible that soon you will need to combine these rules with AND, OR, NOT, etc.
Related
I am designing a client that will call methods based on certain inputs. I will be sending in a billing system enum and calling an endpoint to determine which billing system is appropriate for an existing patient. Once I get the billing system, I have to check to see what type of operation I need to perform and make an API call based on the billing system.
For example, if I need to update a patient record and the patient is in BillingSystemA, I need to call a PUT-based method of the API for BillingSystemA.
I need to have CRUD methods for each billing system.
Selecting between the two billing systems and allowing for future growth made me think that the strategy pattern was a good fit. Strategy seems to work for the billing system, but what about the CRUD operations?
I have a BillingStrategy abstract class that has Create, Update, Get and Delete methods, but I need those methods to work against a variety of types. Can I just make the methods generic, like T Create<T> or bool Update<T> or do I need a strategy within a strategy to manage this? I've analyzed myself into a corner and could use some advice.
Here's a rough illustration. I invented a lot of the specifics, and the names aren't so great. I tend to revisit names as I refactor. The main point is to illustrate how we can break up the problem into pieces.
This assumes that there are classes for Patientand Treatment and an enum for InsuranceType. The goal is to bill a patient for a treatment, and determine where to send the bill based on the patient's insurance.
Here's a class:
public class PatientBilling
{
private readonly IBillingHandlerByInsuranceSelector _billingHandlerSelector;
private readonly IBillingHandler _directPatientBilling;
public PatientBilling(
IBillingHandlerByInsuranceSelector billingHandlerSelector,
IBillingHandler directPatientBilling)
{
_billingHandlerSelector = billingHandlerSelector;
_directPatientBilling = directPatientBilling;
}
public void BillPatientForTreatment(Patient patient, Treatment treatment)
{
var billingHandler = _billingHandlerSelector.GetBillingHandler(patient.Insurance);
var result = billingHandler.BillSomeone(patient, treatment);
if (!result.Accepted)
{
_directPatientBilling.BillSomeone(patient, treatment);
}
}
}
and a few interfaces:
public interface IBillingHandler
{
BillSomeoneResult BillSomeone(Patient patient, Treatment treatment);
}
public interface IBillingHandlerByInsuranceSelector
{
IBillingHandler GetBillingHandler(InsuranceType insurance);
}
As you can see this will rely heavily on dependency injection. This class is simple because it doesn't know anything at all about the different insurance types.
All it does is
Select a billing handler based on the insurance type
try to submit the bill to the insurance
if it's rejected, bill the patient
It doesn't know or care how any of that billing is implemented. It could be a database call, an API call, or anything else. That makes this class very easy to read and test. We've deferred whatever isn't related to this class. That's going to make it easier to solve future problems one at a time.
The implementation of IBillingHandlerByInsuranceSelector can be an abstract factory that will create and return the correct implementation of IBillingHandler according to the patient's insurance. (I'm glossing over that but there's plenty of information on how to create abstract factories with dependency injection containers.)
In a sense we could say that the first part of this problem is solved (although we're likely to refactor some more.) The reason why is that we can write unit tests for it, and any of the work specific to one insurance type or another will be in different classes.
Next we can write those insurance-specific implementations. Suppose one of the insurance types is WhyCo, and now we need to create an IBillingHandler for them. We're essentially going to repeat the same process.
For the sake of illustration, let's say that submitting a bill to WhyCo is done in two steps. First we have to make a request to check eligibility, and then we have to submit the bill. Maybe other insurance APIs do this in one step. That's okay, because no two implementations have to have anything in common with each other. They just implement the interface.
At this point we're dealing with the specifics of one particular insurance company, so somewhere in here we'll need to convert our Patient and Treatment information into whatever data they expect to receive.
public class WhyCoBillingHandler : IBillingHandler
{
private readonly IWhyCoService _whyCoService;
public WhyCoBillingHandler(IWhyCoService whyCoService)
{
_whyCoService = whyCoService;
}
public BillSomeoneResult BillSomeone(Patient patient, Treatment treatment)
{
// populate this from the patient and treatment
WhyCoEligibilityRequest eligibilityRequest = ...;
var elibility = _whyCoService.CheckEligibility(eligibilityRequest);
if(!elibility.IsEligible)
return new BillSomeoneResult(false, elibility.Reason);
// create the bill
WhyCoBillSubmission bill = ...;
_whyCoService.SubmitBill(bill);
return new BillSomeoneResult(true);
}
}
public interface IWhyCoService
{
WhyCoEligibilityResponse CheckEligibility(WhyCoEligibilityRequest request);
void SubmitBill(WhyCoBillSubmission bill);
}
At this point we still haven't written any code that talks to the WhyCo API. That makes WhyCoBillingHandler easy to unit test. Now we can write an implementation of IWhyCoService that calls the actual API. We can write unit tests for WhyCoBillingHandler and integration tests for the implementation of IWhyCoService.
(Perhaps it would have been better if translating our Patient and Treatment data into what they expect happened even closer to the concrete implementation.)
At each step we're writing pieces of the code, testing them, and deferring parts for later. The API class might be the last step in implementing WhyCo billing. Then we can move on to the next insurance company.
At each step we also decide how much should go into each class. Suppose we have to write a private method, and that method ends up being so complicated that it's bigger than the public method that calls it and it's hard to test. That might be where we replace that private method with another dependency (abstraction) that we inject into the class.
Or we might realize up front that some new functionality should be separated into its own class, and we can just start off with that.
The reason why I illustrated it this way is this:
I've analyzed myself into a corner
It's easy to become paralyzed when our code has to do so many things. This helps to avoid paralysis because it continually gives us a path forward. We write part of it to depend on abstractions, and then that part is done (sort of.) Then we implement those abstractions. The implementations require more abstractions, and we repeat (writing unit tests all the way in between.)
This doesn't enforce best practices and principles, but it gently guides us toward them. We're writing small, single-responsibility classes. They depend on abstractions. We're defining those abstractions (interfaces, in this case) from the perspective of the classes that need them, which leads to interface segregation. And each class is easy to unit test.
Some will point out that it's easy to get carried away with all the abstractions and create too many interfaces and too many layers of abstraction, and they are correct. But that's okay. At every single step we're likely to go a little off balance one way or the other.
As you can see, the problems that occur when we have to deal with the difference between billing systems becomes simpler. We just create every implementation differently.
Strategy seems to work for the billing system, but what about the CRUD operations?
The fact that they all have different CRUD operations is fine. We've made components similar where they need to be similar (the interfaces through which we interact with them) but the internal implementations can be as different as they need to be.
We've also sidestepped the question of which design patterns to use, except that IBillingHandlerByInsuranceSelector is an abstract factory. That's okay too, because we don't want to start off too focused on a design pattern. If this was a real application, I'd assume that a lot of what I'm doing will need to be refactored. Because the classes are small, unit tested, and depend on abstractions, it's easier to introduce design patterns when their use becomes obvious. When that happens we can likely isolate them to the classes that need them. Or, if we've just realized that we've gone in the wrong direction, it's still easier to refactor. Unless we can see the future that's certain to happen.
It's worth taking some time up front to understand the various implementation details to make sure that the way you have to work with them lines up with the code you're writing. (In other words, we still need to spend some time on design.) For example, if your billing providers don't give you immediate responses - you have to wait hours or days - then code that models it as an immediate response wouldn't make sense.
One more benefit is that this helps you to work in parallel with other developers. If you've determined that a given abstraction is a good start for your insurance companies and maybe you've written a few, then it's easy to hand off other ones to other developers. They don't have to think about the whole system. They can just write an implementation of an interface, creating whatever dependencies they need to.
I'm trying to explain to my team why this is bad practice, and am looking for an anti-pattern reference to help in my explanation. This is a very large enterprise app, so here's a simple example to illustrate what was implemented:
public void ControlStuff()
{
var listOfThings = LoadThings();
var listOfThingsThatSupportX = new string[] {"ThingA","ThingB", "ThingC"};
foreach (var thing in listOfThings)
{
if(listOfThingsThatSupportX.Contains(thing.Name))
{
DoSomething();
}
}
}
I'm suggesting that we add a property to the 'Things' base class to tell us if it supports X, since the Thing subclass will need to implement the functionality in question. Something like this:
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
if (thing.SupportsX)
{
DoSomething();
}
}
}
class ThingBase
{
public virtual bool SupportsX { get { return false; } }
}
class ThingA : ThingBase
{
public override bool SupportsX { get { return true; } }
}
class ThingB : ThingBase
{
}
So, it's pretty obvious why the first approach is bad practice, but what's this called? Also, is there a pattern better suited to this problem than the one I'm suggesting?
Normally a better approach (IMHO) would be to use interfaces instead of inheritance
then it is just a matter of checking whether the object has implemented the interface or not.
I think the anti-pattern name is hard-coding :)
Whether there should be a ThingBase.supportsX depends at least somewhat on what X is. In rare cases that knowledge might be in ControlStuff() only.
More usually though, X might be one of set of things in which case ThingBase might need to expose its capabilities using ThingBase.supports(ThingBaseProperty) or some such.
IMO the fundamental design principle at play here is encapsulation. In your proposed solution you have encapsulated the logic inside of the Thing class, where as in the original code the logic leaks out into the callers.
It also violates the Open-Closed principle, since if you want to add new subclasses that support X you now need to go and modify anywhere that contains that hard-coded list. With your solution you just add the new class, override the method and you're done.
Don't know about a name (doubt such exists) but think of each "Thing" as a car - some cars have Cruise Control system and others do not have.
Now you have fleet of cars you manage and want to know which have cruise control.
Using the first approach is like finding list of all car models which have cruise control, then go car by car and search for each in that list - if there it means the car has cruise control, otherwise it doesn't have. Cumbersome, right?
Using the second approach means that each car that has cruise control come with a sticker saying "I has cruise control" and you just have to look for that sticker, without relying on external source to bring you information.
Not very technical explanation, but simple and to the point.
There is a perfectly reasonable situation where this coding practice makes sense. It might not be an issue of which things actually support X (where of course an interface on each thing would be better), but rather which things that support X are ones that you want to enable. The label for what you see is then simply configuration, presently hard-coded, and the improvement on this is to move it eventually to a configuration file or otherwise. Before you persuade your team to change it I would check this is not the intention of the code you have paraphrased.
The Writing Too Much Code Anti-Pattern. It makes it harder to read and understand.
As has been pointed out already it would be better to use an interface.
Basically the programmers are not taking advantage of Object-Oriented Principles and instead doing things using procedural code. Every time we reach for the 'if' statement we should ask ourselves if we shouldn't be using an OO concept instead of writing more procedural code.
It is just a bad code, it does not have a name for it (it doesn't even have an OO design). But the argument could be that the first code does not fallow Open Close Principle. What happens when list of supported things change? You have to rewrite the method you're using.
But the same thing happens when you use the second code snippet. Lets say the supporting rule changes, you'd have to go to the each of the methods and rewrite them. I'd suggest you to have an abstract Support Class and pass different support rules when they change.
I don't think it has a name but maybe check the master list at http://en.wikipedia.org/wiki/Anti-pattern knows? http://en.wikipedia.org/wiki/Hard_code probably looks the closer.
I think that your example probably doesn't have a name - whereas your proposed solution does it is called Composite.
http://www.dofactory.com/Patterns/PatternComposite.aspx
Since you don't show what the code really is for it's hard to give you a robust sulotion. Here is one that doesn't use any if clauses at all.
// invoked to map different kinds of items to different features
public void BootStrap
{
featureService.Register(typeof(MyItem), new CustomFeature());
}
// your code without any ifs.
public void ControlStuff()
{
var listOfThings = LoadThings();
foreach (var thing in listOfThings)
{
thing.InvokeFeatures();
}
}
// your object
interface IItem
{
public ICollection<IFeature> Features {get;set;}
public void InvokeFeatues()
{
foreach (var feature in Features)
feature.Invoke(this);
}
}
// a feature that can be invoked on an item
interface IFeature
{
void Invoke(IItem container);
}
// the "glue"
public class FeatureService
{
void Register(Type itemType, IFeature feature)
{
_features.Add(itemType, feature);
}
void ApplyFeatures<T>(T item) where T : IItem
{
item.Features = _features.FindFor(typof(T));
}
}
I would call it a Failure to Encapsulate. It's a made up term, but it is real and seen quite often
A lot of people forget that encasulation is not just the hiding of data withing an object, it is also the hiding of behavior within that object, or more specifically, the hiding of how the behavior of an object is implemented.
By having an external DoSomething(), which is required for the correct program operation, you create a lot of issues. You cannot reasonably use inheritence in your list of things. If you change the signature of the "thing", in this case the string, the behavior doesn't follow. You need to modify this external class to add it's behaviour (invoking DoSomething() back to the derived thing.
I would offer the "improved" solution, which is to have a list of Thing objects, with a method that implements DoSomething(), which acts as a NOOP for the things that do nothing. This localizes the behavior of the thing within itself, and the maintenance of a special matching list becomes unnecessary.
If it were one string, I might call it a "magic string". In this case, I would consider "magic string array".
I don't know if there is a 'pattern' for writing code that is not maintainable or reusable. Why can't you just give them the reason?
In order to me the best is to explain that in term of computational complexity. Draw two chart showing the number of operation required in term of count(listOfThingsThatSupportX ) and count(listOfThings ) and compare with the solution you propose.
Instead of using interfaces, you could use attributes. They would probably describe that the object should be 'tagged' as this sort of object, even if tagging it as such doesn't introduce any additional functionality. I.e. an object being described as 'Thing A' doesn't mean that all 'Thing A's have a specific interface, it's just important that they are a 'Thing A'. That seems like the job of attributes more than interfaces.
Recently I've found my self to implement code following a pattern like:
public class SomeClass()
{
private T Execute<T>(Func<T> function)
{
// Do some common stuff for every function like logging and try-catch
function();
}
public Type1 Command1()
{
Execute<Type1>(() => funcForCommand1);
}
public Type2 Command2()
{
Execute<Type2>(() => funcForCommand2);
}
}
Is this just a functional approach on the CommandPattern? Depending on the situation I've different version of this? You could probably achieve exactly the same thing by letting funcForCommandX inherit from somekind of ICommand that defines the Execute function, but I like my way in many situations better since most of the time the commands are only used in one location in the code and not needs to be exposed to the rest of the code. Of course you should implement the real command pattern if it is used in more locations in the code.
It is up to your needs. That is all I can say.
But I would like to state that this is not a Command Pattern but may be a method delegation.
Command Pattern focuses mainly on execution of a method/task. Following are standard behaviors that can be expected from a Command in this pattern:
Undo/Redo
Transactions
Composite Command Execution
Macros
When you wrap a method/task implementation in a Command, you can provide implementations on what to do to reverse/undo what has been done. Provide default implementation on attaching current execution to transactions, macro recording, thread-safe execution, etc.
With your approach you don't have that. And it's not easily doable until you wrap each task/method in a Command wrapper and provide above mentioned behaviors.
Take a look at Wikipedia article for further details on a Command Pattern.
I am trying to create a web-based tool for my company that, in essence, uses geographic input to produce tabular results. Currently, three different business areas use my tool and receive three different kinds of output. Luckily, all of the outputs are based on the same idea of Master Table - Child Table, and they even share a common Master Table.
Unfortunately, in each case the related rows of the Child Table contain vastly different data. Because this is the only point of contention I extracted a FetchChildData method into a separate class called DetailFinder. As a result, my code looks like this:
DetailFinder DetailHandler;
if (ReportType == "Planning")
DetailHandler = new PlanningFinder();
else if (ReportType == "Operations")
DetailHandler = new OperationsFinder();
else if (ReportType == "Maintenance")
DetailHandler = new MaintenanceFinder();
DataTable ChildTable = DetailHandler.FetchChildData(Master);
Where PlanningFinder, OperationsFinder, and MaintenanceFinder are all subclasses of DetailFinder.
I have just been asked to add support for another business area and would hate to continue this if block trend. What I would prefer is to have a parse method that would look like this:
DetailFinder DetailHandler = DetailFinder.Parse(ReportType);
However, I am at a loss as to how to have DetailFinder know what subclass handles each string, or even what subclasses exist without just shifting the if block to the Parse method. Is there a way for subclasses to register themselves with the abstract DetailFinder?
You could use an IoC container, many of them allows you to register multiple services with different names or policies.
For instance, with a hypothetical IoC container you could do this:
IoC.Register<DetailHandler, PlanningFinder>("Planning");
IoC.Register<DetailHandler, OperationsFinder>("Operations");
...
and then:
DetailHandler handler = IoC.Resolve<DetailHandler>("Planning");
some variations on this theme.
You can look at the following IoC implementations:
AutoFac
Unity
Castle Windsor
You might want to use a map of types to creational methods:
public class DetailFinder
{
private static Dictionary<string,Func<DetailFinder>> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Func<DetailFinder>>();
Creators.Add( "Planning", CreatePlanningFinder );
Creators.Add( "Operations", CreateOperationsFinder );
...
}
public static DetailFinder Create( string type )
{
return Creators[type].Invoke();
}
private static DetailFinder CreatePlanningFinder()
{
return new PlanningFinder();
}
private static DetailFinder CreateOperationsFinder()
{
return new OperationsFinder();
}
...
}
Used as:
DetailFinder detailHandler = DetailFinder.Create( ReportType );
I'm not sure this is much better than your if statement, but it does make it trivially easy to both read and extend. Simply add a creational method and an entry in the Creators map.
Another alternative would be to store a map of report types and finder types, then use Activator.CreateInstance on the type if you are always simply going to invoke the constructor. The factory method detail above would probably be more appropriate if there were more complexity in the creation of the object.
public class DetailFinder
{
private static Dictionary<string,Type> Creators;
static DetailFinder()
{
Creators = new Dictionary<string,Type>();
Creators.Add( "Planning", typeof(PlanningFinder) );
...
}
public static DetailFinder Create( string type )
{
Type t = Creators[type];
return Activator.CreateInstance(t) as DetailFinder;
}
}
As long as the big if block or switch statement or whatever it is appears in only one place, it isn't bad for maintainability, so don't worry about it for that reason.
However, when it comes to extensibility, things are different. If you truly want new DetailFinders to be able to register themselves, you may want to take a look at the Managed Extensibility Framework which essentially allows you to drop new assemblies into an 'add-ins' folder or similar, and the core application will then automatically pick up the new DetailFinders.
However, I'm not sure that this is the amount of extensibility you really need.
To avoid an ever growing if..else block you could switch it round so the individal finders register which type they handle with the factory class.
The factory class on initialisation will need to discover all the possible finders and store them in a hashmap (dictionary). This could be done by reflection and/or using the managed extensibility framework as Mark Seemann suggests.
However - be wary of making this overly complex. Prefer to do the simplest thing that could possibly work now with a view to refectoring when you need it. Don't go and build a complex self-configuring framework if you'll only ever need one more finder type ;)
You can use the reflection.
There is a sample code for Parse method of DetailFinder (remember to add error checking to that code):
public DetailFinder Parse(ReportType reportType)
{
string detailFinderClassName = GetDetailFinderClassNameByReportType(reportType);
return Activator.CreateInstance(Type.GetType(detailFinderClassName)) as DetailFinder;
}
Method GetDetailFinderClassNameByReportType can get a class name from a database, from a configuration file etc.
I think information about "Plugin" pattern will be useful in your case: P of EAA: Plugin
Like Mark said, a big if/switch block isn't bad since it will all be in one place (all of computer science is basically about getting similarity in some kind of space).
That said, I would probably just use polymorphism (thus making the type system work for me). Have each report implement a FindDetails method (I'd have them inherit from a Report abstract class) since you're going to end with several kinds of detail finders anyway. This also simulates pattern matching and algebraic datatypes from functional languages.
I have been using factory method creation pattern for awhile now. I was just recently told that this:
public static class ScheduleTypeFactory
{
public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
{
IScheduleItem scheduleItem = null;
switch (scheduleType)
{
case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.BroadbandScheduleTypeID:
{
scheduleItem = new VODScheduleItem();
break;
}
case ScheduleTypeEnum.LinearCableScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
case ScheduleTypeEnum.MobileLinearScheduleTypeID:
{
scheduleItem = new LinearScheduleItem();
break;
}
}
return scheduleItem;
}
}
is not a factory method creation pattern by my "Tech" lead without telling me why or giving me her interpretation. I kindly asked for an explanation and she told me she didn't have time. I was told to just rename it. If I am wrong, then I will no doubt accept that I have implemented this incorrectly for years. Is this how YOU would implement the factory method creation pattern? Thanks in advance.
I would agree to call the method a "Factory Method", though the design is not strictly a "Factory Method Pattern".
Here is a key point (from Wikipedia):
...The Factory method lets a class defer instantiation to subclasses."
Since your class is static and method static (hence non-virtual), there is no "deferring" possible.
Conceptually, notice also, that this implementation, though provides encapsulation, does not decouple/delay any decision.
Having said that, same Wikipedia article does present this schema as a variant of the "Factory Method Pattern".
Summary of the Summary: In my opinion this snippet is not a proper implementation of the "Factory Method OO Design Pattern", since it does not satisfy "a class defer instantiation to subclasses." Though, personally I would freely refer to this solution as "factory method".
To make it real factory method pattern, you need to allow the method to be overridden by subclasses. I.e. factory class (ScheduleTypeFactory) needs to be extensible (i.e. non-static), and GetScheduleItem needs to be virtual.
Sure looks like the factory pattern to me. I don't see anything wrong with your implementation.
From Factory method pattern:
The essence of the Factory Pattern is
to "Define an interface for creating
an object, but let the subclasses
decide which class to instantiate. The
Factory method lets a class defer
instantiation to subclasses."
This is exactly what you are doing.
As a side note: a good rule of thumb is that whenever someone tells you something and is unable or unwilling to provide a rationale for their statement, there is a good chance they are unqualified to make the statement at all.
Yes this is a factory pattern. My only comment would be that you fail silently for enum values that you don't specifically handle. That may be expected but I like to add the following to the end of statements like that
default:
throw new InvalidOperationException("Invalid Enum Value");
Your code fragment is what in Head First Design Patterns is called "The Simple Factory" (p. 117).
The main difference to the Factory Method Pattern is the ConcreteCreator (compare the diagram in the upper right corner), which is a simple class in your case. In the "real pattern" the factory class is abstract with an abstract factory class. So, there is one more abstraction level. However, for many use cases, your Simple Factory is enough.
Simple Factory
Simple Factory http://yuml.me/7221a4c9
Factory Method Pattern
Factory Method Pattern http://yuml.me/3d22eb4e
I think it is traditionally called the simple factory pattern to distinguish it from the 'real' Abstract Factory pattern. It might be that you are not adhering to some sort of internal naming practice. She really ought to explain herself though.
Your lead is right (sorry for the formatting, but this answer need some of it in order to be seen between the main line that is stating the lead is a moron): neither by the GOF book nor Head First this a factory method.
GoF :
“Define an interface for creating an
object, but let the subclasses decide
which class to instantiate. Factory
Method lets a class defer
instantiation to subclasses.”
In your example, it's not a subclass that is deciding.
Have you implemented it incorrectly all these years? No, you just haven't implemented the factory pattern, but what is sometimes referred to as the 'Simple Factory Pattern', which probably has done the job just fine.
Looks like a (basic) factory to me... in many factories the implementation is more complex (perhaps involving types resolved at runtime), but that is not (AFAIK) a requirement. The only other critique I'd have added is to combine the cases, and do something more dramatic if you don't recognise the type...
I'm surprised so many saying that this is the factory pattern.
(So chances are that I'm thinking of this wrong, so please let me know.)
It looks to me like what you have there is only a part of the design. If you call it from your client, it's referred to as a "simple" factory, but it's not really considered a design pattern. (Don't get me wrong, I do this all the time).
The factory design pattern would state that your factory inherits/implements an abstract factory/factory interface.
Then, in your class which needs to use the factory (the client), you set the type of the factory to the abstract/interface, creating a concrete factory:
i.e. --> IFactory factory = new ConcreteFactory();
The concrete factory would then create your IScheduleItem (leaving it to the factory to actually create the concrete type).
In the end I think the whole point is about loose coupling. While a "simple" factory loosely couples the construction of the product from the client, it does not decouple the factory. The factory pattern also decouples the factory.
Then again, it's early, I haven't had coffee, and I have a nasty habit of posting absolutely horrible responses that miss the entire point of the question.
Well, Wikipedia says it is a factory method:
public class ImageReaderFactory
{
public static ImageReader getImageReader( InputStream is )
{
int imageType = figureOutImageType( is );
switch( imageType )
{
case ImageReaderFactory.GIF:
return new GifReader( is );
case ImageReaderFactory.JPEG:
return new JpegReader( is );
// etc.
}
}
}
Looks like a factory pattern to me. Tell your tech lead you don't have time to explain why she is wrong.
That is the Factory pattern, but it's not necessarily the most maintainable variant. A more maintainable variant would maintain some sort of global map between ScheduleTypeEnum values and actual concrete subtypes of IScheduleItem -- that way, you could replace the switch statement with a lookup of the map.
Why is it more maintainable? Because subclass authors can add pairs to the map at the site where they derive the class, rather than in the GetScheduleItem() factory function itself. Hence the latter never needs updating; it is constantly up-to-date.
In C++ you can do this using a global std::map -- for each concrete subclass, the author of the subclass adds a dummy global variable which actually just registers the class (by adding to the map) in its constructor, which runs at program startup time. I'm certain that there's a convenient way to do the same thing in C#.
(C++ guru Herb Sutter has an entertaining description here, but it's fairly C++-heavy.)
It is indeed a "factory" in that you have a method that returns a specific instance of the IScheduleItem based on some sort of logic; however, it probably isn't the best implementation or the most maintainable given that you are using a switch statement.
Yup, that's the factory pattern alright. Your Tech lead is wrong.
Looks like a basic factory pattern to me. I'm curious to hear why your tech lead doesn't think this is a pattern.
I'm also dissapointed she wouldn't take the time to explain things. Having been a tech lead before on a team, it is curcial to take the time to explain your decisions.
It is the factory method pattern, at least according to Wikipedia:
http://en.wikipedia.org/wiki/Factory_method_pattern
What the tech lead is likely thinking is that the Factory pattern is to replace a constructor in the same object, not to return subclasses, or perhaps only return subclasses from a superclass, not from an unrelated object. It's wrong, but that is probably the thinking.
The fact that Wikipedia lists your pattern as an example shows that it is correctly a factory pattern. The patterns were defined to provide a common language for common solutions, so clearly if Wikipedia is showing this as an example, it is part of the common language. An academic debate about what the "Factory Pattern" is in some abstract sense misses the point of patterns.
Take back the power right now! Just drop 'Type' from the wording. ScheduleFactory FTW. Wait, is this a factory for 'Schedules' or 'ScheduleItems'? If it's scheduleitems then the factory should be called 'ScheduleItemFactory'. Be expressive!!!
The simplest explanation of the factory pattern, which I learned from a patterns and practice class, was that if you rely on another class to create the instances of your class, then you're using the factory pattern.
Of course, often times you want to add a layer of indirection by making your class abstract or an interface.
This is very simplified view of it, but either way, you are using the factory pattern.
Your Tech is right on renaming the method:
public static IScheduleItem GetScheduleItem(ScheduleTypeEnum scheduleType)
The action of the method is not to get something, is to create something.
How do you decide which scheduleType should be created? Seems that logic should
be encapsulated not the switch of the type.
Also why the static on the class? Where are you using it from?
public class ScheduleTypeFactory
{
public static IScheduleItem createScheduleFrom(ScheduleTypeEnum scheduleType)
{
switch (scheduleType)
{
case ScheduleTypeEnum.CableOnDemandScheduleTypeID:
case ScheduleTypeEnum.BroadbandScheduleTypeID:
return new VODScheduleItem();
case ScheduleTypeEnum.LinearCableScheduleTypeID:
case ScheduleTypeEnum.MobileLinearScheduleTypeID:
return new LinearScheduleItem();
}
raise InvalidSchedule;
}
}
Thats a textbook Factory Pattern.
Some texts call it a Simple Factory Patteren, but I've never seen any criteria for what "Simple" means.
In my practice, a Factory Pattern is any intelligent creation of a concrete class coresponding to a desired interface.
But why fight your tech lead over naming a method. Rename it, move on with your life.