Can I make Rhino Mocks GenerateStub or GenerateMock return a new type every time? - rhino-mocks

I want to create an IList of objects that are all different concrete types, so:
var tasks = new List<ITask>();
foreach (string taskName in taskNames)
{
var task = MockRepository.GenerateStub<ITask>();
task.Stub(t => t.Name).Return(taskName);
tasks.Add(task);
}
return tasks;
The problem is that each stub object is all the same concrete type. Normally this is fine, but I have a case where I want to test each one being a different type. Can I somehow configure Rhino Mocks to do this, in this case?
EDIT:
The "you-must-be-doing-it-wrong-crew" are out in force today. Since you all seem to think I need to justify my use-case before you can take a stab at answering my question, here's what I'm doing:
ITask is in my domain model, so it's part of my business layer.
I have logic in a higher level (presentation) layer that takes an ITask as an argument.
The presentation layer logic normally executes a default Strategy on the ITask, but there can be special cases where we need to use a different Strategy, and the Strategy to use depends entirely upon the concrete type of the ITask object.
The regular Strategy pattern doesn't work here because that requires my concrete ITask objects to know about a layer above them.
Decorators still have to know about the concrete type of the object they decorate, and have to be applied either at construction time (wrong layer for this case) or when used, but then that leaves me with the same problem - applying a decorator based on concrete type.
I decided to use the same pattern used by DataTemplates (and the DataType attribute) in WPF. That is, given an object from a lower layer, see if anyone's registered a Strategy to handle that type, and if so, use it. Otherwise, use a default Strategy.
So, I hope you can see why I need the test logic. So far I've had to write my own Stub factory that generates from a limited pool of concrete ITask types. It works, but I'd rather let Rhino Mocks do it for me.

You could add a ITask.Type property.
The code which is interested in the type behind the interface should then use this property instead of calling GetType(). In your tests, it then becomes trivial to take control of what the Type property returns for any given ITask stub.

Related

Flaw: Constructor does Real Work

I have a class which represents a set of numbers. The constructor takes three arguments: startValue, endValue and stepSize.
The class is responsible for holding a list containing all values between start and end value taking the stepSize into consideration.
Example: startValue: 3, endValue: 1, stepSize = -1, Collection = { 3,2,1 }
I am currently creating the collection and some info strings about the object in the constructor. The public members are read only info strings and the collection.
My constructor does three things at the moment:
Checks the arguments; this could throw an exception from the constructor
Fills values into the collection
Generates the information strings
I can see that my constructor does real work but how can I fix this, or, should I fix this? If I move the "methods" out of the constructor it is like having init function and leaving me with an not fully initialized object. Is the existence of my object doubtful? Or is it not that bad to have some work done in the constructor because it is still possible to test the constructor because no object references are created.
For me it looks wrong but it seems that I just can't find a solution. I also have taken a builder into account but I am not sure if that's right because you can't choose between different types of creations. However single unit tests would have less responsibility.
I am writing my code in C# but I would prefer a general solution, that's why the text contains no code.
EDIT: Thanks for editing my poor text (: I changed the title back because it represents my opinion and the edited title did not. I am not asking if real work is a flaw or not. For me, it is. Take a look at this reference.
http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/
The blog states the problems quite well. Still I can't find a solution.
Concepts that urge you to keep your constructors light weight:
Inversion of control (Dependency Injection)
Single responsibility principle (as applied to the constructor rather than a class)
Lazy initialization
Testing
K.I.S.S.
D.R.Y.
Links to arguments of why:
How much work should be done in a constructor?
What (not) to do in a constructor
Should a C++ constructor do real work?
http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/
If you check the arguments in the constructor that validation code can't be shared if those arguments come in from any other source (setter, constructor, parameter object)
If you fill values into the collection or generate the information strings in the constructor that code can't be shared with other constructors you may need to add later.
In addition to not being able to be shared there is also being delayed until really needed (lazy init). There is also overriding thru inheritance that offers more options with many methods that just do one thing rather then one do everything constructor.
Your constructor only needs to put your class into a usable state. It does NOT have to be fully initialized. But it is perfectly free to use other methods to do the real work. That just doesn't take advantage of the "lazy init" idea. Sometimes you need it, sometimes you don't.
Just keep in mind anything that the constructor does or calls is being shoved down the users / testers throat.
EDIT:
You still haven't accepted an answer and I've had some sleep so I'll take a stab at a design. A good design is flexible so I'm going to assume it's OK that I'm not sure what the information strings are, or whether our object is required to represent a set of numbers by being a collection (and so provides iterators, size(), add(), remove(), etc) or is merely backed by a collection and provides some narrow specialized access to those numbers (such as being immutable).
This little guy is the Parameter Object pattern
/** Throws exception if sign of endValue - startValue != stepSize */
ListDefinition(T startValue, T endValue, T stepSize);
T can be int or long or short or char. Have fun but be consistent.
/** An interface, independent from any one collection implementation */
ListFactory(ListDefinition ld){
/** Make as many as you like */
List<T> build();
}
If we don't need to narrow access to the collection, we're done. If we do, wrap it in a facade before exposing it.
/** Provides read access only. Immutable if List l kept private. */
ImmutableFacade(List l);
Oh wait, requirements change, forgot about 'information strings'. :)
/** Build list of info strings */
InformationStrings(String infoFilePath) {
List<String> read();
}
Have no idea if this is what you had in mind but if you want the power to count line numbers by twos you now have it. :)
/** Assuming information strings have a 1 to 1 relationship with our numbers */
MapFactory(List l, List infoStrings){
/** Make as many as you like */
Map<T, String> build();
}
So, yes I'd use the builder pattern to wire all that together. Or you could try to use one object to do all that. Up to you. But I think you'll find few of these constructors doing much of anything.
EDIT2
I know this answer's already been accepted but I've realized there's room for improvement and I can't resist. The ListDefinition above works by exposing it's contents with getters, ick. There is a "Tell, don't ask" design principle that is being violated here for no good reason.
ListDefinition(T startValue, T endValue, T stepSize) {
List<T> buildList(List<T> l);
}
This let's us build any kind of list implementation and have it initialized according to the definition. Now we don't need ListFactory. buildList is something I call a shunt. It returns the same reference it accepted after having done something with it. It simply allows you to skip giving the new ArrayList a name. Making a list now looks like this:
ListDefinition<int> ld = new ListDefinition<int>(3, 1, -1);
List<int> l = new ImmutableFacade<int>( ld.buildList( new ArrayList<int>() ) );
Which works fine. Bit hard to read. So why not add a static factory method:
List<int> l = ImmutableRangeOfNumbers.over(3, 1, -1);
This doesn't accept dependency injections but it's built on classes that do. It's effectively a dependency injection container. This makes it a nice shorthand for popular combinations and configurations of the underlying classes. You don't have to make one for every combination. The point of doing this with many classes is now you can put together whatever combination you need.
Well, that's my 2 cents. I'm gonna find something else to obsess on. Feedback welcome.
As far as cohesion is concerned, there's no "real work", only work that's in line (or not) with the class/method's responsibility.
A constructor's responsibility is to create an instance of a class. And a valid instance for that matter. I'm a big fan of keeping the validation part as intrinsic as possible, so that you can see the invariants every time you look at the class. In other words, that the class "contains its own definition".
However, there are cases when an object is a complex assemblage of multiple other objects, with conditional logic, non-trivial validation or other creation sub-tasks involved. This is when I'd delegate the object creation to another class (Factory or Builder pattern) and restrain the accessibility scope of the constructor, but I think twice before doing it.
In your case, I see no conditionals (except argument checking), no composition or inspection of complex objects. The work done by your constructor is cohesive with the class because it essentially only populates its internals. While you may (and should) of course extract atomic, well identified construction steps into private methods inside the same class, I don't see the need for a separate builder class.
The constructor is a special member function, in a way that it constructor, but after all - it is a member function. As such, it is allowed to do things.
Consider for example c++ std::fstream. It opens a file in the constructor. Can throw an exception, but doesn't have to.
As long as you can test the class, it is all good.
It's true, a constructur should do minimum of work oriented to a single aim - successful creaation of the valid object. Whatever it takes is ok. But not more.
In your example, creating this collection in the constructor is perfectly valid, as object of your class represent a set of numbers (your words). If an object is set of numbers, you should clearly create it in the constructor! On the contrary - the constructur does not perform what it is made for - a fresh, valid object construction.
These info strings call my attention. What is their purpose? What exactly do you do? This sounds like something periferic, something that can be left for later and exposed through a method, like
String getInfo()
or similar.
If you want to use Microsoft's .NET Framework was an example here, it is perfectly valid both semantically and in terms of common practice, for a constructor to do some real work.
An example of where Microsoft does this is in their implementation of System.IO.FileStream. This class performs string processing on path names, opens new file handles, opens threads, binds all sorts of things, and invokes many system functions. The constructor is actually, in effect, about 1,200 lines of code.
I believe your example, where you are creating a list, is absolutely fine and valid. I would just make sure that you fail as often as possible. Say if you the minimum size higher than the maximum size, you could get stuck in an infinite loop with a poorly written loop condition, thus exhausting all available memory.
The takeaway is "it depends" and you should use your best judgement. If all you wanted was a second opinion, then I say you're fine.
It's not a good practice to do "real work" in the constructor: you can initialize class members, but you shouldn't call other methods or do more "heavy lifting" in the constructor.
If you need to do some initialization which requires a big amount of code running, a good practice will be to do it in an init() method which will be called after the object was constructed.
The reasoning for not doing heavy lifting inside the constructor is: in case something bad happens, and fails silently, you'll end up having a messed up object and it'll be a nightmare to debug and realize where the issues are coming from.
In the case you describe above I would only do the assignments in the constructor and then, in two separate methods, I would implement the validations and generate the string-information.
Implementing it this way also conforms with SRP: "Single Responsibility Principle" which suggests that any method/function should do one thing, and one thing only.

OO principle: c#: design to interface and not concrete classes

I have some questions about the affects of using concrete classes and interfaces.
Say some chunk of code (call it chunkCode) uses concrete class A. Would I have to re-compile chunkCode if:
I add some new public methods to A? If so, isn't that a bit stange? After all I still provide the interface chunkCode relies on. (Or do I have to re-compile because chunkCode may never know otherwise that this is true and I haven't omitted some API)
I add some new private methods to A?
I add a new public field to A?
I add a new private field to A?
Factory Design Pattern:
The main code doesn't care what the concrete type of the object is. It relies only on the API. But what would you do if there are few methods which are relevant to only one concrete type? This type implements the interface but adds some more public methods? Would you use some if (A is type1) statements (or the like) the main code?
Thanks for any clarification
1) Compiling is not an activity in OO. It is a detail of specific OO implementations. If you want an answer for a specific implementation (e.g. Java), then you need to clarify.
In general, some would say that adding to an interface is not considered a breaking change, wheras others say you cannot change an interface once it is published, and you have to create a new interface.
Edit: You specified C#, so check out this question regarding breaking changes in .Net. I don't want to do that answer a disservice, so I won't try to replicate it here.
2) People often hack their designs to do this, but it is a sign that you have a poor design.
Good alternatives:
Create a method in your interface that allows you to invoke the custom behavior, but not be required to know what that behavior is.
Create an additional interface (and a new factory) that supports the new methods. The new interface does not have to inherit the old interface, but it can if it makes sense (if an is-a relationship can be expressed between the interfaces).
If your language supports it, use the Abstract Factory pattern, and take advantage of Covariant Return Types in the concrete factory. If you need a specific derived type, accept a concrete factory instead of an abstract one.
Bad alternatives (anti-patterns):
Adding a method to the interface that does nothing in other derived classed.
Throwing an exception in a method that doesn't make sense for your derived class.
Adding query methods to the interface that tell the user if they can call a certain method.
Unless the method name is generic enough that the user wouldn't expect it to do anything (e.g. DoExtraProcessing), then adding a method that is no-op in most derived classes breaks the contract defined by that interface.
E.g.: Someone invoking bird.Fly() would expect it to actually do something. We know that chickens can't fly. So either a Chicken isn't a Bird, or Birds don't Fly.
Adding query methods is a poor work-around for this. E.g. Adding a boolean CanFly() method or property in your interface. So is throwing an exception. Neither of them get around the fact that the type simply isn't substitutable. Check out the Liskov Substitution Principle (LSP).
For your first question the answer is NO for all your points. If it would be that way then backward compatibility would not make any sense. You have to recompile chunkCode only if you brake the API, that is remove some functionality that chunkCode is using, changing calling conventions, modifying number of parameters, these sort of things == breaking changes.
For the second I usually, but only if I really have to, use dynamic_cast in those situations.
Note my answer is valid in the context of C++;I just saw the question is language agnostic(kind of tired at this hour; I'll remove the answer if it offenses anybody).
Question 1: Depends on what language you are talking about. Its always safer to recompile both languages though. Mostly because chuckCode does not know what actually exists inside A. Recompiling refreshes its memory. But it should work in Java without recompiling.
Question 2: No. The entire point of writing a Factory is to get rid of if(A is type1). These if statements are terrible from maintenance perspective.
Factory is designed to build objects of similar type. If you are having a situation where you are using this statement then that object is either not a similar type to rest of the classes. If you are sure it is of similar type and have similar interfaces. I would write an extra function in all the concrete base classes and implement it only on this one.
Ideally All these concrete classes should have a common abstract base class or a Interface to define what the API is. Nothing other than what is designed in this Interface should be expected to be called anywhere in the code unless you are writing functions that takes this specific class.

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Does ChannelFactory implement a factory pattern?

I’ve started learning WCF and I’m already utterly confused. I did a bit of reading on factory pattern and I can’t figure out how or why does ChannelFactory<> implement it.
Namely, the whole idea of a factory pattern is that factory abstracts the creation and initialization of the product from the client and thus if new type of product is introduced, client code doesn’t need to change and thus can immediately start using the new product.
ChannelFactory<IRequestChannel> factory = new
ChannelFactory<IRequestChannel>(binding, address);
IRequestChannel channel = factory.CreateChannel();
The following is not a valid code, but it’s just used to demonstrate that, as far as I can tell, ChannelFactory doesn’t bring any benefits over directly instantiating specific channel class:
IRequestChannel channel=new RequestChannelClass(binding, address);
a) Only benefit of the first example ( implementing the factory pattern ) is that client code doesn’t need to change in the event that the type of object returned by factory.CreateChannel is changed sometime in the future.
But if that’s the reason for implementing factory pattern, then any method returning an object should implement a factory pattern, just in case the type of returned object ever changes in the future?!
c) Thus, if ChannelFactory<>.CreateChannel really implemented factory pattern, then client code would be able to inform factory.GetFactory (say via parameter) of what type should an object/product returned by factory.CreateFactory be?!
d) Similarly, as far as I can tell, ChannelFactory class also doesn't implement a factory pattern?
thank you
REPLYING TO Justin Niessner:
b) The Factory pattern doesn't
necessarily require you to be able to
specify the concrete type to be
created. It also allows for the
factory to determine the concrete type
based on the parameters passed to it
(in this case, binding and address).
So ChannelFactory.CreateChannel choose a concrete type to return based on binding and address values? I thought it always returns the same concrete type, regardless of address and binding values?!
As I’ve asked the other two posters, would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Kevin Nelson
A) There are 2 benefits. 1)
implementing code doesn't have to
change if you start using a new
implementation of IRequestChannel.
True, but as I’ve mentioned to other posters, if that’s the only requirement for class to be qualified as a class implementing a factory pattern , then any class with a method ( with an interface type as return type ) that creates and returns a concrete instance, implements a factory pattern? As far as I can tell, factory pattern is when factory produces different products based on values somehow supplied by a client code?!
On the other hand, if I correctly understood Steve Ellinger, then based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will choose the concrete type to return based on binding and address values( supplied to constructor ). If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
REPLYING TO Steve Ellinger
IRequestChannel is implemented by the
abstract class RequestChannel. In .Net
4.0 HttpChannelFactory.HttpRequestChannel,
ReliableRequestSessionChannel and
StreamedFramingRequestChannel all
inherit from RequestChannel. So:
a) You say the only benefit, but
actually I think this is a significant
benefit. Keep in mind, this also makes
WCF extensible and more flexible.
But then we could claim that any class with a method ( with an interface type as return type ) that creates and returns a concrete instance implements a factory pattern?
c) The client code does tell the
factory which to return, indirectly by
the passed binding and address.
I thought ChannelFactory.CreateChannel will always return in instance of the same concrete type, regardless of the binding and address passed to constructor of ChannelFactory.But you’re saying that based on binding and address values ( passed to constructor of ChannelFactory), the call to ChannelFactory.CreateChannel will return one of the following types: HttpChannelFactory.HttpRequestChannel ,ReliableRequestSessionChannel and StreamedFramingRequestChannel?
If that is the case, then I can understand why we say ChannelFactory implements factory pattern?!
So would you agree that if ChannelFactory.CreateChannel always returned an instance of the same concrete type, regardless of the binding and address values, then ChannelFactory wouldn’t have a factory pattern implemented?
SECOND REPLY TO Steve Ellinger
a) So depending on the binding and address values, ChannelFactory.CreateChannel returns either HttpRequestChannel ,ReliableRequestSessionChannel or StreamedFramingRequestChannel? Or may it also return some other types also?
b) if client code will always use channel instance of the same type (say HttpRequestChannel ), then there's nothing wrong if instead of using ChannelFactory.CreateChannel we directly instantiate HttpRequestChannel instance:
HttpRequestChannel channel = new HttpRequestChannel( ... )
c) BTW - any idea why msdn doesn't contain any entries describing HttpRequestChannel ,ReliableRequestSessionChannel and `StreamedFramingRequestChannel' classes?
IRequestChannel is implemented by the abstract class RequestChannel. In .Net 4.0 HttpChannelFactory.HttpRequestChannel, ReliableRequestSessionChannel and StreamedFramingRequestChannel all inherit from RequestChannel. So:
a) You say the only benefit, but actually I think this is a significant benefit. Keep in mind, this also makes WCF extensible and more flexible.
c) The client code does tell the factory which to return, indirectly by the passed binding and address. I for one would not want to go through all my code to change a concrete type because Microsoft decided to obsolete the one I was using.
d) Yes, given the structure mentioned at the start, this is a typical Factory pattern implementation.
Edit:
a factory pattern?
But then we could claim that any class
with a method ( with an interface type
as return type ) that creates and
returns a concrete instance implements
a factory pattern?
Not necessarily, to quote the Design Patterns book: the abstract factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Yes
Edit2:
a) It can return other types because it is possible to create custom bindings in WCF
b) & c) HttpChannelFactory.HttpRequestChannel is a protected class, ReliableRequestSessionChannel and StreamedFramingRequestChannel are internal classes; this is why you can't find them on msdn, and also why you can't instantiate these classes directly. I found out about them via Reflector, my point in mentioning them is that ChannelFactory does not necessarily return the same concrete type all the time
The Factory pattern is used to return a Concrete Implementation of a more generic class/interface.
In this case, ChannelFactory is returning a concrete implementation of IRequestChannel. Nowhere in any of your code are you telling the factory which concrete class to return which is what makes this a Factory. As for your points:
a) It is often considered good coding practice to return the least specific type possible. If you can get away with returning an instance of an interface, do it. It will reduce maintenance headaches in the future.
Keep in mind though that returning the least specific type has nothing to do with the Factory pattern. The Factory pattern is specific to the creation of an instance of an object.
b) The Factory pattern doesn't necessarily require you to be able to specify the concrete type to be created. It also allows for the factory to determine the concrete type based on the parameters passed to it (in this case, binding and address).
c) Yes, the ChannelFactory does implement the Factory pattern.
There are others that are probably more efficient with patterns (and explaining them) than I am, but here goes:
A) There are 2 benefits. 1) implementing code doesn't have to change if you start using a new implementation of IRequestChannel. 2) This also enables you to make Mock objects. In your unit test project, you tell your ChannelFactory to instantiate a Mock IRequestChannel. This way, you can focus your unit test onto just the specifics of the method you are testing rather than having to create a behemoth test that instantiates real instances of everything, etc. (If you're unfamiliar, look up Test Driven Development (TDD), Inversion of Control (IoC), and Dependency Injection (basically a subset of IoC).
B) I would say that you generally want to use the factory pattern between layers, not within layers. E.g. your service layer would implement a factory for your repository layer classes. This way, if your ICustomerRepostory changes from an NHibernateCustomerRepository to a CouchDBCustomerRespository...your service layer doesn't have to know anything about this change.
Other poster answered the other issues, I think...so I'll leave C & D alone.
REPLY EDIT:
So would you agree that if
ChannelFactory.CreateChannel always
returned an instance of the same
concrete type, regardless of the
binding and address values, then
ChannelFactory wouldn’t have a factory
pattern implemented?
Sorry, probably over my head as to the semantics of it...but to my understanding, the point isn't so much whether it does return more than one concrete class, but in its ability to return a different concrete class if the need arises. If it's not able to produce different concrete classes, then it wouldn't be a factory...but if it "can" produce different concrete classes if and when the need arises, then it is a factory pattern. Beyond that, I'll have to declare ignorance...and even in that, I'm not saying I can't be wrong.

Is type checking ever OK?

Is type checking considered bad practice even if you are checking against an interface? I understand that you should always program to an interface and not an implementation - is this what it means?
For example, in PHP, is the following OK?
if($class instanceof AnInterface) {
// Do some code
}
Or is there a better way of altering the behaviour of code based on a class type?
Edit: Just to be clear I am talking about checking whether a class implements an interface not just that it is an instance of a certain class.
As long as you follow the LSP, I don't see a problem. Your code must work with any implementation of the interface. It's not a problem that certain implementations cause you to follow different code paths, as long as you can correctly work with any implementation of the interface.
If your code doesn't work with all implementations of the interface, then you shouldn't use the interface in the first place.
If you can avoid type checking you should; however, one scenario where I found it handy, was we had a web service which took a message but the contents of the message could change. We had to persist the message back into a db, in order to get the right component to break the message down to its proper tables we used type checking in a sense.
What I find more common and flexible then if ($class instanceof SomeOtherType) is to define an IProcessing strategy for example and then using factory based on the type $class create the correct class.
So in c# roughly this:
void Process(Message msg)
{
IProcessor processor=ProcessignFactory.GetProcessor(msg.GetType());
processor.Process(msg);
}
However sometimes doing this can be overkill if your only dealing with one variation that won't change implement it using a type check, and when / if you find you were wrong and it requires more checks then refactor it into a more robust solution.
In my practice any checking for type (as well as type casting) has always indicated that something is wrong with the code or with the language.
So I try to avoid it whenever possible.
Run-time type checking is often necessary in situations where an interface provides all the methods necessary to do something, but does not provide enough to do it well. A prime example of such a situation is determining the number of items in an enumerable sequence. It's possible to make such a determination by enumerating through the sequence, but many enumerable objects "know" how many items they contain. If an object knows how many items it contains, it will likely be more efficient to ask it than to enumerate through the collection and count the items individually.
Arguably, IEnumerable should have provided some methods to ask what it knows about the number of items it contains [recognizing the possibility that the object may know that the number is unbounded, or that it's at most 4,591 (but could be a lot less), etc.], but it doesn't. What might be ideal would be if a new version of IEnumerable interface could be produced that included default implementations for any "new" methods it adds, and if such interface could be considered to be implemented by any implementations of the present version. Unfortunately, because no such feature exists, the only way to get the count of an enumerable collection without enumerating it is to check whether it implements any known collection interfaces that include a Count member.