OOD - How to desing and structure the projects to avoid redeploying the main Application (factory pattern?) - factory-pattern

I would like to check if my understanding in using and implementing factory pattern.
Say I am designing an Application to play several Games (chess, poker).
The games are loaded from one of the following sources: CSV, XML
but I want the ability to add new sources (say DB) without recompiling/redeploying the Application.I just want to deploy the factory logic and the new loader
This suggests a factory pattern for the game loader, something like the following which however causes circular dependencies because the concrete loaders returns a List.
Application.prj has reference to AbstractFactory.prj
-----------------------
main ()
List<Game> games = LoadGameFactory.Create(src).Load(src)
foreach(game in games) game.play();
abstract class Game { .. abstract void Play(); ..}
class Chess : Game { .. void Play() ..}
class Poker : Game { .. void Play() ..}
Factory.prj has reference to Application.prj
------------------------
class LoadGameFactory {
GameLoader Create(string src)
{
if(src == csv) return new LoadCSVGames().Load(src)
else return new LoadXMLGames().Load(src)
}
}
class GameLoader{ List<Game> Load(src) }
class CSVLoader : GameLoader
{
List<Game> Load(src){ ... logic to create Chess() and Poker() from CSV file}
}
class XMLLoader : GameLoader
{
List<Game> Load(src) { ... logic to create Chess() and Poker() from XML file}
}
The solution I found is to create a new project, Application.Model, where I move the Game, Chess, and Poker, ecc
That way, Application.prj and Factory.prj will need to reference just Application.Model. And adding DB source requires only factory.prj recompilation and deployment.
Is this the way to go? or is there a way to implement the factory pattern to get the same result. I don't want reflection.

It sounds like you want a plugin-based design. I'm assuming this is C#. What you want to do is design a strict set of Interfaces, that define the games, game loader, etc. Then you use Assembly.LoadFrom() to load all the DLLs, and use reflection to get the exported classes that inherit from those interfaces, from those assemblies, and instantiate new objects.

Related

Avoiding cyclic dependencies between entities in two modules

I’m currently wondering what’s a good way to keep ZF2 modules copyable from one project to another, if I have doctrine2 entities that reference each other.
My current situation is something like this: I have an entity User from which I want to be able to access all languages this user speaks.
Of course, Language is not a component of the Authentication module, because I might want to use it for other purposes, too.
namespace Authentication\Entity;
class User {
public function getSpokenLanguages();
}
And:
namespace Application\Entity;
class Language {
public function getUsersWhoSpeakThisLanguage();
}
The problem is, I want my Authentication module to be totally independent from the project-specific module Application.
Is there a good way to keep these relations out of my entities or possibly inject them from the Application module? Maybe also a UserService (in Application module) giving me the languages Language[] for a specific User would be a good idea? I could call it like this:
$userService->getUsersLanguages($user);
I think, especially injection might be a ZF2-solution, but I have no idea, how one could extend Doctrine2 entities like that from another module.
I think you're speaking to more of semantic issue than one specific to ZF2. Reading your question, I think your language becomes more of a managed layer that you can easily facilitate with factories and DI - luckily ZF2 has all the right tools. Consider something like this as a potential draft for a solution:
Create a LanguageAbstractFactory:
namespace Your\Namespace;
use Zend\ServiceManager\AbstractFactoryInterface,
Zend\ServiceManager\ServiceLocatorInterface;
class LanguageAbstractFactory implements AbstractFactoryInterface
{
/**
* Determine if we can create a service with name
*
* #param ServiceLocatorInterface $serviceLocator
* #param $name
* #param $requestedName
* #return bool
*/
public function canCreateServiceWithName( ServiceLocatorInterface $serviceLocator, $name, $requestedName )
{
return stristr( $requestedName, 'Namespace\Language' ) !== false;
}
public function createServiceWithName(ServiceLocatorInterface $locator, $name, $requestedName)
{
$filter = new $requestedName();
$filter->setServiceLocator( $locator );
return $filter;
}
}
Then, create your languages in that same namespace, as subclasses of Language, that implement ServiceLocatorAwareInterface (to give you database access down the road and such). The code in the factory above injects the service locator (and that's where you tweak it to inject other goodness to satisfy your language architecture):
namespace Your\Namespace;
use Zend\ServiceManager\ServiceLocatorAwareInterface,
Zend\ServiceManager\ServiceLocatorInterface;
class Language implements ServiceLocatorAwareInterface
{
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator()
{
return $this->serviceLocator;
}
// ... other things your factory knows, that this class may not go here
}
A Language implementation might then look like:
namespace Your\Namespace\Language;
class English extends \Your\Namespace\Language
{
public function getUsersWhoSpeakThisLanguage()
{
$sm = $this->getServiceManager();
// get your entities or w/e using the SM
}
}
Connect the factory by tweaking your module's Module.php at getServiceConfig:
public function getServiceConfig() {
return array(
'abstract_factories' => array(
// this one generates all of the mass email filters
'Your\Namespace\LanguageAbstractFactory',
),
);
}
This gives you the ability to use the service manager to get a service-aware language very easily. e.g., from a service-aware class:
$sm->getServiceManager()->get( '\Your\Namespace\Language\English' );
Because of the config, and that the Factory can meet the request, your factory will auto-configure the English instance with whatever logic you build into it in a very portable fashion.
Where this is kind of a primer on Factories - if you rig an interface class that the service can use to speak to your user classes, you can invert control to the Language service from the User. Making your User implement LanguageAware (for example) which contains classes that the Language service can use should be a few steps away.
Hope this helps. There's probably 15 ways to skin this cat; this approach is one I have used to solve similar problems, e.g., that of "Filtering" data. A filter, can filter information, and information can be filtered by a filter.
Good Luck!

Getting rid of 'new' operators for subcomponents objects

I've been reading Misko Hevery's classic articles about Dependency injection, and basically 'separating the object graph creation code from the code logic'.
The main idea seems to be "get rid of the 'new' operators", put them in dedicated objects ('Factories') and inject everything you depend on."
Now, I can't seem to wrap my head about how to make this works with objects that are composed of several other components, and whose job is to isolate those components to the outerworld.
Lame example
A View class to represent a combination of a few fields, and a button. All the components depend on a graphical ui context, but you want to hide it behind the interfaces of each sub-component.
So something like (in pseudo-code, language does not really matter I guess):
class CustomView() {
public CustomView(UIContext ui) {
this.ui = ui
}
public void start() {
this.field = new Field(this.ui);
this.button = new Button(this.ui, "ClickMe");
this.button.addEventListener(function () {
if (field.getText().isEmtpy()) {
alert("Field should not be empty");
} else {
this.fireValueEntered(this.field.getText());
}
});
}
// The interface of this component is that callers
// subscribe to "addValueEnteredListener"..)
public void addValueEnteredListener(Callback ...) {
}
public void fireValueEnteredListener(text) {
// Would call each listeners in turn
}
}
The callers would do something like :
// Assuming a UIContext comes from somewhere...
ui = // Wherever you get UI Context from ?
v = new CustomView(ui);
v.addValueEnteredListener(function (text) {
// whatever...
});
Now, this code has three 'new' operators, and I'm not sure which one Misko (and other DI proponents) are advocating to rid off, or how.
Getting rid of new Field() and new Button()
Just Inject it
I don't think the idea here is to actually inject the instances of Field and Button , which could be done this way :
class CustomView() {
public CustomView(Field field, Button button) {
this.field = field;
this.button = button;
}
public void start() {
this.button.addEventListener(function () {
if (field.getText().isEmtpy()) {
alert("Field should not be empty");
} else {
this.fireValueEntered(this.field.getText());
}
});
}
// ... etc ...
This makes the code of the component lighter, surely, and it actually hides the notion of UI, so the MetaForm component has clearly been improved in terms of readability and testability.
However, the burden is now on the client to create those things :
// Assuming a UIContext comes from somewhere...
ui = // wherever ui gets injected from
form = new Form(ui);
button = new Button(ui);
v = new CustomView(form, button);
v.addValueEnteredListener(function (text) {
// whatever...
});
That sounds really troubling to me, espacially since the client know has to all the inners of the class, which sounds silly.
Mama knows, inject her instead
What the articles seems to advocate is instead injecting a Factory to create the components elements.
class CustomView() {
public CustomView(Factory factory) {
this.factory = factory;
}
public void start() {
this.field = factory.createField();
this.button = factory.createButton();
this.button.addEventListener(function () {
if (field.getText().isEmtpy()) {
alert("Field should not be empty");
} else {
this.fireValueEntered(this.field.getText());
}
});
}
// ... etc ...
And then everything gets nice for the caller, because its just has to get the factory from somewhere (and this factory will be the only to know about the UI context, so hurray for decoupling.)
// Assuming a UIContext comes from somewhere...
factory = // wherever factory gets injected from
v = new CustomView(factory);
v.addValueEnteredListener(function (text) {
// whatever...
});
A possible drawback is that when testing the MetaForm, you will typically have to use a 'Mock' Factory that ... create Mocks version of the Field & Button classes. But obviously there is another drawback ...
Yo' Factory so fat!!
How big will the Factory get ? If you follow the pattern rigorously, then every single frigging component you ever want to create in you application at runtime (wich is typically the case for UI, right) will have to get its own createXXXXX methods in at least one factory.
Because now you need :
Factory.createField to create the field
Factory.createButton to create the button
Factory.createMetaForm to create the field, the button and the MetaForm when a client (say the MetaEditPage wants to use one)
And obviously a Factory.createMetaEditPage for the client..
... and its turtles all the way.
I can see some strategies to simplify this :
As much as possible, separate the parts of the graph that are created at "startup" time from the parts that are created at runtime (using an DI framework like Spring for the former, and factories for the latter)
Layer the factories, or collocate related objects in the same factories (a UIWidgetFactory would make sense for Field and Button, but where would you put the other ones ? In a Factory linked to the Application ? To some other logical level ?)
I can almost hear all the jokes from C guys that no Java app can do anything without calling a ApplicationProcessFactoryCreator.createFactory().createProcess().startApplication() chain of nonsense...
So my questions are :
I am completely missing a point here ?
If not, which strategy would you suggest to make the things bearable ?
Addendum : why I'm not sure dependency injection would help
Assume I decide to use dependency injection, with a guice-like framework. I would end up writing code like this :
class CustomView
#Inject
private Field fiedl;
#Inject
private Button button;
public void start() {
this.button.addEventListener(....
// etc...
And then what ?
How would my "Composition Root" make use of that ? I can certainely not configure a "singleton" (with a lowercase 's', as in 'the single instance of a class) for the Field and the Button (since I want to create as many instances of them as instances of MetaForm ?
It would not make sense to use a Provider, since my problem is not which instance of buttons I want to create, but just that I want to create it lately, with some configuration (for example its text) that only makes sense for this form.
To me DI is not going to help because I am new-ing parts of my component rather than Dependencies. And I suppose I could turn any subcomponent into a dependency, and let a framework inject them. It's just that injecting subcomponents looks really artificial and couter-intuitive to me, in this case... so again, I must be missing something ;)
Edit
In particular, my issue is that I can't seem to understand how you would test the following scenario :
"when I click on the button, if the Field is empty, there should be an error".
This is doable if I inject the button, so that I can call its "fireClicked" event manually - but it feels a bit silly.
The alternative is to just do view.getButton().fireClicked() , but that looks a bit ugly...
Well, you can use some DI Framework (Spring or Guice) and get rid of factory method completely. Just put some annotation on the field/constructor/set method and DI Framework will do the work. At unit-test use mock framework.
How about not being overly obsessed with the "no new" dogma ?
My take is that DI works well for - well you know, Dependencies, or Delegates. Your example is about composition and IMHO it absolutely makes sense that the owning entity (your CustomView) creates explicitly its components. After all, the clients of the composite do not even have to know that these components exist, how they are initialized or how you use them.

Unit Testing DbContext

I've researched some information about techniques I could use to unit test a DbContext. I would like to add some in-memory data to the context so that my tests could run against it. I'm using Database-First approach.
The two articles I've found most usefull were this and this.
That approach relies on creating an IContext interface that both MyContext and FakeContext will implement, allowing to Mock the context.
However, I'm trying to avoid using repositories to abstract EF, as pointed by some people, since EF 4.1 already implements repository and unit of work patterns through DbSet and DbContext, and I really would like to preserve all the features implemented by the EF Team without having to maintain them myself with a generic repository, as I already did in other project (and it was kind of painful).
Working with an IContext will lead me to the same path (or won't it?).
I thought about creating a FakeContext that inherits from main MyContext and thus take advantage of the DbContext underneath it to run my tests without hitting the database.
I couldn't find similar implementations, so I'm hoping someone can help me on this.
Am I doing something wrong, or could this lead me to some problems that I'm not anticipating?
Ask yourself a single question: What are you going to test?
You mentioned FakeContext and Mocking the context - why to use both? Those are just different ways to do the same - provide test only implementation of the context.
There is one more bigger problem - faking or mocking context or set has only one result: You are not testing your real code any more.
Simple example:
public interface IContext : IDisposable
{
IDbSet<MyEntity> MyEntities { get; }
}
public class MyEntity
{
public int Id { get; set; }
public string Path { get; set; }
}
public class MyService
{
private bool MyVerySpecialNetMethod(e)
{
return File.Exists(e.Path);
}
public IEnumerable<MyEntity> GetMyEntities()
{
using (IContext context = CreateContext())
{
return context.MyEntities
.Where(e => MyVerySpecialNetMethod(e))
.Select(e)
.ToList();
}
}
}
Now imagine that you have this in your SUT (system under test - in case of unit test it is an unit = usually a method). In the test code you provide FakeContext and FakeSet and it will work - you will have a green test. Now in the production code you will provide a another derived DbContext and DbSet and you will get exception at runtime.
Why? Because by using FakeContext you have also changed LINQ provider and instead of LINQ to Entities you are running LINQ to Objects so calling local .NET methods which cannot be converted to SQL works as well as many other LINQ features which are not available in LINQ to Entities! There are other issues you can find with data modification as well - referential integrity, cascade deletes, etc. That is the reason why I believe that code dealing with context / LINQ to Entities should be covered with integration tests and executed against the real database.
I am developing an open-source library to solve this problem.
http://effort.codeplex.com
A little teaser:
You don't have to add any boilerplate code, just simply call the appropriate API of the library, for example:
var context = Effort.ObjectContextFactory.CreateTransient<MyContext>();
At first this might seem to be magic, but the created ObjectContext object will communicate with an in-memory database and will not talk to the original real database at all. The term "transient" refers to the lifecycle of this database, it only lives during the presence of the created ObjectContext object. Concurrently created ObjectContext objects communicate with dedicated database instances, the data is not shared accross them. This enables to write automated tests easily.
The library provides various features to customize the creation: share data across instances, set initial data of the database, create fake database on different data layers... check out the project site for more info.
As of EF 4.3, you can unit test your code by injecting a fake DefaultConnectionFactory before creating the context.
Entity Framework 4.1 is close to being able to be mocked up in tests but requires a little extra effort. The T4 template provides you with a DbContext derived class that contains DbSet properties. The two things that I think you need to mock are the DbSet objects that these properties return and properites and methods you're using on the DbContext derived class. Both can be achieved by modifying the T4 template.
Brent McKendrick has shown the types of modifications that need to be made in this post, but not the T4 template modifications that can achieve this. Roughly, these are:
Convert the DbSet properties on the DbContext derived class into IDbSet properties.
Add a section that generates an interface for the DbContext derived class containing the IDbSet properties and any other methods (such as SaveChanges) that you'll need to mock.
Implement the new interface in the DbContext derived class.

fake directories for .net unit testing

I'm trying to create a unit test for a code similar to this:
foreach (string domainName in Directory.GetDirectories(server.Path))
{
HandleDomainDirectory(session, server, domainName);
}
The problem is that I'm using the System.IO.Directory class in my code.
How can I create a testing method that won't be dependent on any folder I have on my hard disk.
In other words, How can I fake the response of "Directory.GetDirectories(server.Path)"?
(Please note, I do control the "server" object in my class, therefore i can give any path i want)
Thanks.
Rather than calling Directory.GetDirectories(server.Path) directly, you could create an interface like IDirectoryResolver with a single method that takes a path string and returns the list of directories. The class containing your code above would then need a property or field of type IDirectoryResolver, which can be injected through the constructor or a setter.
For your production code, you would then create a new class that implements the IDirectoryResolver interface. This class could use the Directory.GetDirectories method in its implementation of the interface method.
For unit testing, you could create a MockDirectoryResolver class which implements IDirectoryResolver (or use a mocking library to create a mock instance for the interface). The mock implementation can do whatever you need it to do.
You would inject a wrapper class.
public class DirectoryFetcher
{
public virtual List<string> GetDirectoriesIn(string directory)
{
return Directory.GetDirectories(directory);
}
}
And then inject that:
foreach(string directory in _directoryFetcher.GetDirectoriesIn(server.Path))
{
// Whatever
}
You can then Mock that guy at the injection point (this example uses Moq, and constructor injection):
Mock<DirectoryFetcher> mockFetcher = new Mock<DirectoryFetcher>();
mockFetcher.Setup(x => x.GetDirectoriesIn("SomeDirectory")).Returns(new List<string>
{
"SampleDirectory1",
"SampleDirectory2"
});
MyObjectToTest testObj = new MyObjectToTest(mockFetcher.Object);
// Do Test
When communicating with the outside world, such as file system, databases, web services etc. , you should always consider using wrapper classes like the others before me suggested. Testability is one major argument, but an even bigger one is: The out side world changes, and you have no control over it. Folders move, user rights changes, new disk drives appears and old ones are removed. You only want to care about stuff like that in one place. Hence, the wrapper -- let's call it DirectoryResolver like Andy White suggested ealier.
So, wrap your file system calls, extract an interface, and inject that interface where you need to communicate with the file system.
The best solution I've found was to use Moles. The code is very specific, and must do very specific thing. Wrapping it with wrapper class will be redundant. The only reason I needed wrapper class is in order to write tests. Moles allows me to write the tests without any wrapper class :)

How to unit test instance creation?

I have a Carpenter class that does it's work using a Lathe and a Wood object.
class Carpenter
{
function Work()
{
$tool = new Lathe();
$material = new Wood();
$tool->Apply($material);
}
}
Lathe depends on an interface called Material, so I can easily unit test Lathe by giving it a fake Material in my unit test. Wood doesn't depend on anything, so it can also be easily tested.
interface Material {
// Various methods...
}
interface Tool {
function Apply(Material $m);
}
class Wood implements Material {
// Implementations of Material methods
}
class Lathe {
function Apply(Material $m) {
// Do processing
}
}
However, Carpenter depends on the concrete classes Lathe and Wood because it has to create instances of them. That means that as it currently stands, I cannot unit test the Work() method without inadvertantly bringing Lathe and Wood under test.
How should I change my design to unit test Carpenter?
There's a couple of different directions you can take here:
Use Constructor Injection and simply inject the tool and the material instances into the carpenter.
If injecting instances doesn't work for some reason (perhaps because you need to create new instances for every invocation of the Work method), you can inject Abstract Factories instead.
You can also use the Factory Method approach described by ctford, but that requires you to also create test-specific overrides to be able to unit test, and while that's a completely valid thing to do, it's just more work and in many cases the other alternatives are better and more flexible.
The key is to seperate object creation from object use in Carpenter.
class Carpenter
{
function getTool() {
return new Lathe();
}
function getMaterial() {
return new Wood();
}
function Work()
{
$tool = getTool();
$material = getMaterial();
$tool->Apply($material);
}
}
That way you can override the getTool() and getMaterial() methods in a TestCarpenter class and inject your own Material and Tool fakes.
The getTool() and getMaterial() methods can also be unit tested seperately.
Michael Feathers would call the getTool() and getMaterial() methods "seams", because they are points where fakes can be inserted without changing the surrounding code.