The central object of a system I'm developing is getting a bit too unwieldy. The problem is that it can be acted upon in so many different ways. You can:
Cancel it
Deny it
Discard it
Sell it
Split it
Expire it
... and plenty more.
I'm considering factorizing those event-like methods away from the class and make it a bit more generic, like a Command pattern. But most of the methods have different parameters, so using a solution like Run() or Execute() could be a problem perhaps?
Any ideas how to structure this, to make it flexible and simple to add new commands, or actions or what you would like to call them? (I wouldn't call them real events since there are no listeners.)
Can you pass the required parameters for your commands in their constructor ? That way, you can have a parameter-less command.
class SellItCommand : ICommand {
private decimal price;
SellItCommand(decimal price) {
this.price = price;
}
void Execute() {
// Do whatever needs to be done with in the sell command using this.price
}
}
Encapsulate the parameters, as a single parameter:
public class SellCommand: Command {
Product OwnerProduct;
ProductCommand (AOwnerProduct)
{
this.OwnerProduct = AOwnerProduct;
}
public override void Execute(KeyValueArray Parameters)
{
double Price = (double)Parameters.ValueofKey("price");
// do something else
}
}
public class BuyCommand: Command {
Product OwnerProduct;
ProductCommand (AOwnerProduct)
{
this.OwnerProduct = AOwnerProduct;
}
public override void Execute(KeyValueArray Parameters)
{
double Cost = (double)Parameters.ValueofKey("cost");
// do something else
}
}
public class Product {
public void AnyMethod()
{
KeyValueArray Parameters = new KeyValueArray Parameters();
KeyValueArray.Add("price", "12.5");
}
}
Its sort of pseudocode, you may like to use the collection libraries that match your programming framework.
Related
I am creating a very simple web api that allows me to search for things:
public IEnumerable<Thing> GetAllThings()
{
// get all the things!
}
My application has to be able to retrieve a single Thing:
public Thing GetThing(string id)
{
// get a single thing
}
I need more details when retrieving a single Thing than I do when I retrieve all Things. Should I have a separate controller that returns a ThingWithDetails instead of having separate models on GetAllThings and GetThing?
No. You do not have to make a separate controller for ThingsWithDetails. Just have a different overload method. All the below methods will be called based on the request
The below method will be called when you are using url: api/{controller}
public IEnumerable<Thing> GetAllThings()
{
// get all the things!
}
The below method will be called when you are using url: api/{controller}/1
public Thing GetThing(string id)
{
// get a single thing
}
The below method will be called when you are using url: api/{controller}?id=1&name=xyz
public Thing GetThing(string id, string name)
{
// get a single thing
}
As a best practice, you should have a Thing entity with all the possible properties, so you keep the code consistent, and by default you load all of them (assuming that they come from DB).
If you then want to "hide" some properties, you can set them to null just before returning them, using an extension method.
public class Thing
{
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
// extension methods
public static class ThingExtensionMethods
{
public static void ToBasicDetails(this Thing thing)
{
// hide properties
thing.PropertyB = null;
thing.PropertyC = null;
}
}
public IEnumerable<Thing> GetAllThings()
{
var things = _db.Things.ToList();
foreach(var item in things)
{
item.ToBasicDetails();
}
return things;
}
public Thing GetThing(string id)
{
var thing = _db.Things.Find(id);
return thing;
}
Defining separate "Thing" and "ThingWithDetails" models makes sense, because you are returning different resource types to the client. The return type defines the response body, so use different models for different response formats.
You don't need to put those methods into separate controllers - it's valid to have an action that returns a ThingWithDetails and another action that returns IEnumerable. It comes down to preference. (I'd probably leave them in the same controller, because they are dealing with the same DB entity.)
This tutorial shows an example.
Does anyone know if it's possible to use Ninject to resolve any unresolved abstract dependencies outside of the instantiation process? I've just been looking into constructor injection vs property/method/field injection, but it looks to me as though Ninject is still expecting to be the creator of the type using the IKernel.Get<>() method.
Basically, we're using MVC3 to build our product, and we've come up against a situation where we want the default ModelBinder to map form values to an instance of the object, and then be able to call a method on the submitted ViewModel that is dependent on an abstract interface e.g.
public class InviteFriend {
[Required]
public string EmailAddress { get; set; }
public void Execute() {
var user = IUserRepository.GetUser(this.EmailAddress);
if (user == null) {
IUserRepository.SaveInvite(this.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
SmtpClient.Send(toSend);
}
}
where the controller action would receive InviteFriend as the method argument. We want Ninject to be able to resolve that IUserRepository dependency, but I can't quite work out how to since the object itself is instantiated by the MVC ModelBinder rather than Ninject IKernel.Get<>().
Maybe the solution is a Ninject-based ModelBinder, or does that seem a really bad idea?
EDIT TO ADD: After the comments below, I realise that my hastily mocked-up code sample doesn't really reflect what we're facing. I've updated the code sample to reflect that the logic for InviteFriend.Execute() is more complex than just calling a method on one repository. Potentially, this is logic representing a discrete task that could co-ordinate interactions between multiple different domain objects and multiple repositories. The repositories are defined abstractly, and ideally would be resolved by Ninject.
I think what you are looking for is somewhat the following scenario:
public class InviteFriend {
[Required]
public string EmailAddress { get; set; }
// More information
}
public interface ICommand {
void Execute();
}
public class InviteFriendCommand : ICommand
{
public InviteFriend(InviteFriend info, IUserRepository userRepo, IMailSender mailSender) {
this.inviteFriend = info;
this.userRepo = userRepo;
this.mailSender = mailSender;
}
public void Execute() {
var user = this.userRepo.GetUser(this.inviteFriend.EmailAddress);
if (user == null) {
this.userRepo.SaveInvite(this.inviteFriend.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
this.mailSender.Send(toSend);
}
}
public interface ICommandFactory {
ICommand CreateInviteFriendCommand(InviteFriend info);
}
public class CommandFactory {
public CommandFactory(IResolutionRoot resolutionRoot) {
this.resolutionRoot = resolutionRoot;
}
ICommand CreateInviteFriendCommand(InviteFriend info) {
this.resolutionRoot.Get<InviteFriendCommand>(new ConstructorArgument("info", info));
}
}
public class YourController {
// Somewhere
var command = this.commandFactory.CreateInviteFriendCommand(info);
command.Execute();
}
public class YourModule : NinjectModule {
override Load() {
Bind<IUserRepository>().To<UserRepo>().InRequestScope();
Bind<ICommandFactory>().To<CommandFactory>().InRequestScope();
Bind<InviteFriendCommand>().ToSelf().InRequestScope();
}
}
Forgive me when you need to tweak it a bit. I hacked it together with my out of brain compiler ;)
Thank you for all your comments, but I've subsequently found the information I was looking for.
The answer is that it is possible to inject dependencies post-instantiation with Ninject. The solution is as follows:
public class InviteFriend {
[Inject]
public IUserRepository UserRepo { get; set; }
[Required]
public string EmailAddress { get; set; }
public void Execute() {
var user = UserRepo.GetUser(this.EmailAddress);
if (user == null) {
UserRepo.SaveInvite(this.EmailAddress);
}
MailMessage toSend = new MailMessage(); // Obviously some logic to prepare the body, subject and other mail properties
SmtpClient.Send(toSend);
}
}
With client code then using the Ninject kernel as follows:
IKernel container = new StandardKernel(new ModuleWithMyBindings());
container.Inject(instanceOfInviteFriend);
The code itself is a bit more sophisticated than that i.e. I'm not instantiating a new IKernel each time I need it.
I realise that this is architecturally less pure than some of the suggestions put forward in comments, but in the spirit of YAGNI, this is good enough for now and we can always refactor later on with some of the good suggestions in Daniel's answer. However, this was a question about the capabilities of Ninject rather than an architectural review question, and this is what I consider the answer to my own question :)
New to the world of TDD and I have soon find out that mocking at times is not as easy.
We are using MOQ at work so I need to learn how to do this using moq
I have some code using the command pattern and works a treat.However If were to test drive it I would not know how to do it implementing the code below.
I have done the following
Created BaseToolStripMenuItem:ToolStripMenuItem and added a Command Property (see below)
Created a windows form and added a menuStrip with 2 item Open and Exit
In the form I just add to map the command to a button and all works a treat.
I would like to change the code so that I can UnitTest using Moq but cannot see how???
Can you help?
Any suggestions?
Thanks a lot!!
public interface ICommand
{
void Execute()
}
public abstract class BaseCmd :ICommand
{
protected ProcessMenuCommand ProcessCommand;
protected MenuCommandFactory Factory;
protected BaseCmd(ProcessMenuCommand processMenuCommand, MenuCommandFactory cmdfactory)
{
ProcessCommand = processMenuCommand;
Factory = cmdfactory;
}
abstract public void Execute();
}
public class BaseToolStripMenuItem : ToolStripMenuItem
{
public BaseToolStripMenuItem()
{
Click += MenuItemClick;
Command = null;
}
public BaseCmd Command { get; set; }
private void MenuItemClick(object sender, EventArgs args)
{
if (Command != null) Command.Execute();
}
}
public class MenuCommandFactory
{
private readonly ProcessMenuCommand _processMenuCommand;
public MenuCommandFactory(ProcessMenuCommand processMenuCommand)
{
_processMenuCommand = processMenuCommand;
}
public OpenFileCmd OpenFile()
{
return new OpenFileCmd(_processMenuCommand,this);
}
public ExitCmd Exit()
{
return new ExitCmd(_processMenuCommand, this);
}
}
public class OpenFileCmd:BaseCmd
{
public OpenFileCmd(ProcessMenuCommand processMenu,MenuCommandFactory menuCommandFactory)
:base(processMenu,menuCommandFactory)
{
}
public override void Execute()
{
ProcessCommand.OpenFile();
}
}
public class ProcessMenuCommand
{
public void OpenFile()
{
MessageBox.Show("Open a file");
}
public void Exit()
{
MessageBox.Show("Exiting");
}
}
public class ExitCmd:BaseCmd
{
public ExitCmd(ProcessMenuCommand processMenu, MenuCommandFactory menuCommandFactory)
:base(processMenu,menuCommandFactory)
{
}
public override void Execute()
{
ProcessCommand.Exit();
}
}
//In the form
public partial class Form1 : Form
{
private ProcessMenuCommand menuCommandProcessor;
private MenuCommandFactory factory;
public Form1()
{
InitializeComponent();
// Created editor and factory.
menuCommandProcessor = new ProcessMenuCommand();
factory = new MenuCommandFactory(menuCommandProcessor);
// Get concrete command objects from factory and assign to corresponding menu items and tool strip buttons.
tsOpen.Command = factory.OpenFile();
tsExit.Command = factory.Exit();
}
}
However If were to test drive it I would not know how to do it implementing the code below
The idea about TDD is that it drives you towards an implementation. There are many implementations you could never arrive at using TDD, so your question doesn't really make much sense.
Try to write some tests that drive you towards your goal without having a preconceived image of the solution at which you wish to arrive. It will often turn out that you end up at an entirely different (and better) place than what you originally thought.
A simple Novice Rule: no abstract classes. Try designing again with only interfaces and concrete classes. You'll notice it's easier to test-drive the result.
As for "how to TDD a Command object", a Command is just a class that provides a single action. Test-drive it the same way you would test-drive any method, except you name the method Execute().
Say you have 5 or 6 variables in the model which a certain View is interested in, do you write different functions for each, such as
int a;
int b;
int c;
void setA( newA ) {
a = newA;
notifyAObservers();
}
void setB( newB ) {
b = newB;
notifyBObservers();
}
void setC( newC ) {
b = newC;
notifyCObservers();
}
Or do you just have one notify method and waste a little bit of CPU time
i.e. instead of notifyAObservers and notifyBObservers, you just have notifyObservers
I believe the traditional approach is to notify all observers, and let them handle it. This is because you don't know which observers are observing which variable(s) - you just know that they want to be notified when something changes. However, if you do know what observers are observing which variables, and performance is critical, then you might be able to do something like what you have.
In the traditional Observer pattern, the Observers implement an update() method that is called by the controller when a change happens. The Observables (the data model) would have a notifyObservers() method that iterates over the Observers and calls their update() method. Then, the Observers get whatever they need and the view updates.
Any time I have implemented the Observer pattern, however, I simply keep a list of observers and notify them all. That way, I only have one list of observers and the rest of the class as well as the different observers can all change without me making any changes to the observable class notification.
EDIT: I wrote my answer a few years ago. After reading it just now, I felt I needed to update it.
I believe the best approach is to notify all observers and let the views decide if they need to update themselves..
Each view will be able to verify the state of the model and act accordingly.
Additionally, the "args" could be used as a flag to indicate what has changed (the view may not wish to update itself for every little change).
That way, the model REALLY does not know how and what the view is displaying, they are decoupled.
A first implementation would look like this:
public class MyModelV1 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
notifyObservers();
}
public int getValue() {
return value;
}
}
public class MyViewV1 implements Observer {
public void update(Observable o, Object arg) {
if (o instanceof MyModelV1) {
System.out.println(((MyModelV1) o).getValue());
}
}
}
The view simply checks the type of the observable received.
However, if the model has many attributes and triggers the view for many different scenarios, this simple check may refresh the view too often.
Another approach would be the following:
public class MyModelV2 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
notifyObservers("value");
}
public int getValue() {
return value;
}
}
public class MyViewV2 implements Observer {
public void update(Observable o, Object arg) {
if (o instanceof MyModelV2 && "value".equals(arg)) {
System.out.println(((MyModelV2) o).getValue());
}
}
}
Here, the notification passes a qualifier, which lets the view decide more precisely when to refresh itself.
The view still needs to check and cast the Model, because there is no garantee that the arg "value" isn't notified by another model (and the cast would fail at runtime).
My personal favorite is something along those lines:
public class MyModelV3 extends Observable {
private int value;
public void setValue(int value) {
this.value = value;
setChanged();
Notification.MY_MODEL_VALUE_UPDATED.notifyObserver(this);
}
public int getValue() {
return value;
}
}
public class MyViewV3 implements Observer {
public void update(Observable o, Object arg) {
if (Notification.MY_MODEL_VALUE_UPDATED.equals(arg)) {
MyModelV3 model = Notification.MY_MODEL_VALUE_UPDATED.getModel(o);
System.out.println(model.getValue());
}
}
}
public class Notification<T extends Observable> {
public static final Notification<MyModelV3> MY_MODEL_VALUE_UPDATED = new Notification<MyModelV3>();
private Notification() {
}
public T getModel(Observable o) {
return (T) o;
}
public void notifyObserver(T observable){
observable.notifyObservers(this);
}
}
Here, the notification sends a strongly typed qualifier, which is bound to the Model.
The view is able to use the notification to retrieve a strongly typed model (instead of casting).
This is somewhere between an observer and an event bus..
How do you deal with validation on complex aggregates in a domain driven design? Are you consolidating your business rules/validation logic?
I understand argument validation and I understand property validation which can be attached to the models themselves and do things like check that an email address or zipcode is valid or that a first name has a minimum and maximum length.
But what about complex validation that involves multiple models? Where do you typically place these rules & methods within your architecture? And what patterns if any do you use to implement them?
Instead of relying on IsValid(xx) calls all over your application, consider taking some advice from Greg Young:
Don't ever let your entities get into
an invalid state.
What this basically means is that you transition from thinking of entities as pure data containers and more about objects with behaviors.
Consider the example of a person's address:
person.Address = "123 my street";
person.City = "Houston";
person.State = "TX";
person.Zip = 12345;
Between any of those calls your entity is invalid (because you would have properties that don't agree with each other. Now consider this:
person.ChangeAddress(.......);
all of the calls relating to the behavior of changing an address are now an atomic unit. Your entity is never invalid here.
If you take this idea of modeling behaviors rather than state, then you can reach a model that doesn't allow invalid entities.
For a good discussion on this, check out this infoq interview: http://www.infoq.com/interviews/greg-young-ddd
I like Jimmy Bogard's solution to this problem. He has a post on his blog titled "Entity validation with visitors and extension methods" in which he presents a very elegant approach to entity validation that suggest the implementation of a separate class to store validation code.
public interface IValidator<T>
{
bool IsValid(T entity);
IEnumerable<string> BrokenRules(T entity);
}
public class OrderPersistenceValidator : IValidator<Order>
{
public bool IsValid(Order entity)
{
return BrokenRules(entity).Count() == 0;
}
public IEnumerable<string> BrokenRules(Order entity)
{
if (entity.Id < 0)
yield return "Id cannot be less than 0.";
if (string.IsNullOrEmpty(entity.Customer))
yield return "Must include a customer.";
yield break;
}
}
I usualy use a specification class,
it provides a method (this is C# but you can translate it in any language) :
bool IsVerifiedBy(TEntity candidate)
This method performs a complete check of the candidate and its relations.
You can use arguments in the specification class to make it parametrized, like a check level...
You can also add a method to know why the candidate did not verify the specification :
IEnumerable<string> BrokenRules(TEntity canditate)
You can simply decide to implement the first method like this :
bool IsVerifiedBy(TEntity candidate)
{
return BrokenRules(candidate).IsEmpty();
}
For broken rules, I usualy write an iterator :
IEnumerable<string> BrokenRules(TEntity candidate)
{
if (someComplexCondition)
yield return "Message describing cleary what is wrong...";
if (someOtherCondition)
yield return
string.Format("The amount should not be {0} when the state is {1}",
amount, state);
}
For localization, you should use resources, and why not pass a culture to the BrokenRules method.
I place this classes in the model namespace with names that suggest their use.
Multiple model validation should be going through your aggregate root. If you have to validate across aggregate roots, you probably have a design flaw.
The way I do validation for aggregates is to return a response interface that tells me if validation pass/fail and any messages about why it failed.
You can validate all the sub-models on the aggregate root so they remain consistent.
// Command Response class to return from public methods that change your model
public interface ICommandResponse
{
CommandResult Result { get; }
IEnumerable<string> Messages { get; }
}
// The result options
public enum CommandResult
{
Success = 0,
Fail = 1
}
// My default implementation
public class CommandResponse : ICommandResponse
{
public CommandResponse(CommandResult result)
{
Result = result;
}
public CommandResponse(CommandResult result, params string[] messages) : this(result)
{
Messages = messages;
}
public CommandResponse(CommandResult result, IEnumerable<string> messages) : this(result)
{
Messages = messages;
}
public CommandResult Result { get; private set; }
public IEnumerable<string> Messages { get; private set; }
}
// usage
public class SomeAggregateRoot
{
public string SomeProperty { get; private set; }
public ICommandResponse ChangeSomeProperty(string newProperty)
{
if(newProperty == null)
{
return new CommandResponse(CommandResult.Fail, "Some property cannot be changed to null");
}
SomeProperty = newProperty;
return new CommandResponse(CommandResult.Success);
}
}
This questions a bit old now but in case anyone is interested here's how I implement validation in my service classes.
I have a private Validate method in each of my service classes that takes an entity instance and action being performed, if validation fails a custom exception is thrown with the details of the broken rules.
Example DocumentService with built in validation
public class DocumentService : IDocumentService
{
private IRepository<Document> _documentRepository;
public DocumentService(IRepository<Document> documentRepository)
{
_documentRepository = documentRepository;
}
public void Create(Document document)
{
Validate(document, Action.Create);
document.CreatedDate = DateTime.Now;
_documentRepository.Create(document);
}
public void Update(Document document)
{
Validate(document, Action.Update);
_documentRepository.Update(document);
}
public void Delete(int id)
{
Validate(_documentRepository.GetById(id), Action.Delete);
_documentRepository.Delete(id);
}
public IList<Document> GetAll()
{
return _documentRepository
.GetAll()
.OrderByDescending(x => x.PublishDate)
.ToList();
}
public int GetAllCount()
{
return _documentRepository
.GetAll()
.Count();
}
public Document GetById(int id)
{
return _documentRepository.GetById(id);
}
// validation
private void Validate(Document document, Action action)
{
var brokenRules = new List<string>();
if (action == Action.Create || action == Action.Update)
{
if (string.IsNullOrWhiteSpace(document.Title))
brokenRules.Add("Title is required");
if (document.PublishDate == null)
brokenRules.Add("Publish Date is required");
}
if (brokenRules.Any())
throw new EntityException(string.Join("\r\n", brokenRules));
}
private enum Action
{
Create,
Update,
Delete
}
}
I like this approach because it allows me to put all my core validation logic in one place which keeps things simple.