Scenario
I'm building a system where each item gets reviewed by 2 different people. Whenever the first reviewer saves an item review it's then turn for the second checker to complete their individual review. If I submitted the first review and I open the item again then the item is put into a read only state because you can't review your own work. Also, the first reviewer can put the item into a pending state if more information is required, which the second review can't. Each user is given a specific reviewer roll whenever they select an item from a list.
What I have so far
Each time an item is loaded into the editor the person is given one of 2 roles, InitialReviewer or SecondReviewer.
public class Reviewer
{
public void AddReview(string review) { }
}
public class InitialReviewer : Reviewer, ICanPutIntoPendingState
{
public void PutIntoPendingState(string pendingState) { }
}
public class SecondReviewer : Reviewer
{
// Just use base class to add review
}
public class ReviewerService
{
private readonly Reviewer _reviewer;
public void AddReview(string review)
{
_reviewer.AddReview(review);
}
public void PutIntoPendingState(string pendingState)
{
_reviewer.PutIntoPendingState(pendingState);
}
}
A trimmed down version of my editor.
public class Editor
{
private readonly ReviewerService _reviewerService;
public Editor(ReviewerService reviewerService)
{
_reviewerService = reviewerService;
}
public void SaveCommand()
{
if(user chose a pending state && _reviewerService.Reviewer is ICanPutIntoPendingState) // Pending state is a dropdown.
_reviewerService.PutIntoPendingState("pending state");
else // the user made a complete review
_reviewerService.AddReview("user review");
}
}
Problem
The issue I'm having is that I can't seem to escape from having logic inside Save() from the Editor class that doesn't belong there.
Question
How do I rid myself of the logic inside of the Save() function from the Editor class? It appears to be violating the SRP principle. Checking whether the current reviewer object is of type ICanPutIntoPendingState is the big problem, I think.
Note that I've ommited all logic because there's quite a bit.
Woudn't be enough to give to ReviewerService one Save() method, which internaly call one Save() method of, at this point, abstract class Reviewer, whom abstact Save() method's concrete implementation is made in InitialReviewer and SecondReviewer. So you push decisional logic to classes with concrete implementation.
Hope this helps.
Perhaps you should consider moving business logic from Reviewer class to ReviewerService. Simple implementation would be then something like this:
public abstract class Reviewer
{
public abstract bool CanPutIntoPendingState { get; }
}
public class InitialReviewer : Reviewer
{
public override bool CanPutIntoPendingState
{
get
{
return true;
}
}
}
public class SecondReviewer : Reviewer
{
public override bool CanPutIntoPendingState
{
get
{
return false;
}
}
}
public class ReviewerService
{
private readonly Reviewer _reviewer;
public void AddReview(string review)
{
// do add review logic here
}
public void PutIntoPendingState(string pendingState)
{
if (_reviewer.CanPutIntoPendingState )
{
// do PutIntoPendingState logic here
}
}
}
public class Editor
{
private readonly ReviewerService _reviewerService;
public Editor(ReviewerService reviewerService)
{
_reviewerService = reviewerService;
}
public void SaveCommand()
{
if(user chose a pending state) // Pending state is a dropdown.
_reviewerService.PutIntoPendingState("pending state");
else // the user made a complete review
_reviewerService.AddReview("user review");
}
}
You can also consider to expose only one function on reviewer service, that takes input model. Service is then responsible to validate input and take appropriate action. Something like this:
public class ReviewerService
{
private readonly Reviewer _reviewer;
public void StoreReview(ReviewModel model)
{
// validate input here
// do business logic here
if (model.IsPendingState && _reviewer.CanPutIntoPendingState)
{
this.PutIntoPendingState("pending state");
}
else
{
this.AddReview(model.Review);
}
}
private void AddReview(string review)
{
// do add review logic here
}
private void PutIntoPendingState(string pendingState)
{
// do PutIntoPendingState logic here
}
}
public class ReviewModel
{
public string Review { get; set; }
public bool IsPendingState { get; set; }
}
public class Editor
{
private readonly ReviewerService _reviewerService;
public Editor(ReviewerService reviewerService)
{
_reviewerService = reviewerService;
}
public void SaveCommand()
{
ReviewModel model = new ReviewModel() {Review="user review",IsPendingState=user chose a pending state };
_reviewerService.StoreReview(model);
}
}
Related
I have an existing C# console application that takes arguments and based on the arguments
creates an instance of markets (UK, US, MX..) using dependency injection.
Each market class does a 'string GetData()', 'string ProcessData()' and 'bool ExportData()'.
The application was initially created for one eCommerce vendor's markets. Now I am told to modify it for a different vendor that does a different process. The high-level flow remains the same.
'GetData' to fetch records from DB,
'ProcessData' for any transformation or the likes
'ExportData'.
The difference is Getdata() pulls records from DB and maps to an object. I am planning to use Petapoco. 'ProcessData' might return a similar class. 'Exportdata' currently does an API call but for the new vendor, I have to write to a file.
I was reading up on patterns I am totally confused. At first, I thought I needed abstract factory pattern and now I think the factory method is what I should be using but I am not sure if I am doing it right. Need some guidance/review here. A sample cs file I created from my understanding of factory pattern. This code is based on the headfirst code samples.
using System;
using System.Collections.Generic;
using StatusExport.Models;
namespace factorymethod
{
class Program
{
static void Main(string[] args)
{
ClientFactory factory = null;
Console.WriteLine("Enter client code:");
string clientCode= Console.ReadLine();
switch (clientCode.ToLower())
{
case "costco":
factory = new CostcoFactory("accountname", "taskname");
break;
//NEw vendor might be added
//case "walmart"
//factory = new WalmartFactory("taskname", "type");
//break
default:
break;
}
bool status = factory.ProcessData();
Console.ReadKey();
}
}
abstract class Client
{
public abstract string AccountName { get; }
public abstract string Task { get; set; }
//More properties might be added. Some may not even be used by some of the new vendors. For example, Costco Might need accountname and task. Tomorrow if walmart comes, they might not need these two or may need task and a new property 'type'
public abstract List<T> GetData<T>();
public abstract List<T> ProcessData<T>();
public abstract bool ExportData();
}
class CostcoClient : Client
{
public override string AccountName { get; }
public override string Task { get; set; }
public CostcoClient(string accountName, string task)
{
AccountName = accountName;
Task = task;
}
public override List<DBRecord> GetData<DBRecord>() //DBRecord class is specific to Costco.
{
List<DBRecord> dbresult = new List<DBRecord>();
//dbresult = db return data mapped to an object DBRecord using petapoco. Another vendor might have a different class to which DB records are mapped. So the return type can be generic
return asn;
}
public override List<T> ProcessData<T>()
{
throw new NotImplementedException(); //Any data transformation or business logic. Return type might be DBRecord or a new class altogether
}
public override bool ExportData()
{
throw new NotImplementedException();//Call API or write data to file and if success send true else false
}
}
abstract class ClientFactory
{
public abstract bool ProcessData();
}
class CostcoFactory : ClientFactory
{
public string AccountName { get; }
public string Task { get; set; }
public CostcoFactory(string accountname, string task)
{
AccountName = accountname;
Task = task;
}
public override bool ProcessData()
{
CostcoClient gc = new CostcoClient(AccountName, Task);
var result = gc.GetData<DBRecord>();
return true;
}
}
}
Do you think this is the right design approach?
I also want to keep the console project independent of vendor project. So maybe 'StatusExport.Program' for the console application. DLL projects StatusExport.Common to hold the interface and abstract classes' and 'StatusExport.Client(ex:StatusExport.Costco)' for each vendor stuff.
You can create BaseClient class that will contains a basic group of properties, and if you need to add something new - just inherit it. You did right, but i think it's better to change public modifier to protected in your properties AccountName and Task, to give access to them only from child classes.
Actually, you can create a BaseClientModels (request/response) for each method if you are not sure that returning type List will be always actual.
Example:
public abstract class BaseClient
{
#region Properties : Protected
protected abstract string AccountName { get; }
protected abstract string Task { get; set; }
#endregion
#region Methods : Public
public abstract BaseGetDataResponseModel GetData(BaseGetDataRequestModel model);
public abstract BaseProcessDataResponseModel ProcessData(BaseProcessDataRequestModel model);
public abstract BaseExportDataResponseModel ExportData(BaseExportDataRequestModel model);
#endregion
}
public class BaseGetDataResponseModel { }
public class BaseGetDataRequestModel { }
public class BaseProcessDataResponseModel { }
public class BaseProcessDataRequestModel { }
public class BaseExportDataResponseModel { }
public class BaseExportDataRequestModel { }
Then let's look on your class CostcoClient and how it can looks like:
public class CostcoClient : BaseClient
{
#region Properties : Protected
protected override string AccountName { get; }
protected override string Task { get; set; }
protected virtual IDataReader<BaseGetDataRequestModel, BaseGetDataResponseModel> DataReader { get; }
protected virtual IDataProcessor<CostcoClientProcessDataRequestModel, CostcoClientProcessDataResponseModel> DataProcessor { get; }
protected virtual IExportDataHandler<CostcoClientExportDataRequestModel, CostcoClientExportDataResponseModel> ExportDataHandler { get; }
#endregion
#region Constructors
public CostcoClient(string accountName, string task)
{
//set DataReader, DataProcessor, ExportDataHandler
AccountName = accountName;
Task = task;
}
#endregion
#region Methods : Public
public override BaseGetDataResponseModel GetData(BaseGetDataRequestModel model)
{
if (model is CostcoClientGetDataRequestModel clientGetDataRequestModel)
{
return DataReader.ReadData(clientGetDataRequestModel);
}
return null; //wrong type has passed
}
public override BaseProcessDataResponseModel ProcessData(BaseProcessDataRequestModel model)
{
if (model is CostcoClientProcessDataRequestModel clientProcessDataRequestModel)
{
return DataProcessor.ProcessData(clientProcessDataRequestModel);
}
return null;
}
public override BaseExportDataResponseModel ExportData(BaseExportDataRequestModel model)
{
if (model is CostcoClientExportDataRequestModel clientExportDataRequestModel)
{
return ExportDataHandler.Handle(clientExportDataRequestModel);
}
return null;
}
#endregion
}
public class CostcoClientGetDataRequestModel : BaseGetDataRequestModel { }
public class CostcoClientGetDataResponseModel : BaseGetDataResponseModel { }
public class CostcoClientProcessDataRequestModel : BaseProcessDataRequestModel { }
public class CostcoClientProcessDataResponseModel : BaseProcessDataResponseModel { }
public class CostcoClientExportDataRequestModel : BaseExportDataRequestModel { }
public class CostcoClientExportDataResponseModel : BaseExportDataResponseModel { }
public interface IDataReader<TIn, TOut>
{
public TOut ReadData(TIn model);
}
public interface IDataProcessor<TIn, TOut>
{
public TOut ProcessData(TIn model);
}
public interface IExportDataHandler<TIn, TOut>
{
public TOut Handle(TIn model);
}
public class CostcoClientDataReader : IDataReader<CostcoClientGetDataRequestModel, CostcoClientGetDataResponseModel>
{
public CostcoClientGetDataResponseModel ReadData(CostcoClientGetDataRequestModel model)
{
throw new NotImplementedException();
}
}
//and so on
You have to implement IDataReader, IDataProcessor, IExportDataHandler, make your logic and call it from GetData, ProcessData, ExportData methods, as an example, and get instances via dependency injection.
Then, we can change your factory to this:
public interface IClientFactory
{
BaseClient GetClientService(ClientServicesEnum value);
}
public class BaseClientFactory : IClientFactory
{
#region Propertied : Protected
protected virtual IEnumerable<BaseClient> Services { get; }
protected string AccountName { get; }
protected string Task { get; set; }
#endregion
#region Constructors
public BaseClientFactory(IEnumerable<BaseClient> services, string accountname, string task)
{
Services = services;
AccountName = accountname;
Task = task;
}
#endregion
public BaseClient GetClientService(ClientServicesEnum value)
=> Services.First(x => x.GetType().Equals(GetClientServiceByCode()[value]));
private Dictionary<ClientServicesEnum, Type> GetClientServiceByCode()
=> new Dictionary<ClientServicesEnum, Type>()
{
{ ClientServicesEnum.CostcoClient, typeof(CostcoClient) }
};
}
public enum ClientServicesEnum
{
CostcoClient = 1,
Another2 = 2,
Another3 = 3
}
Where
protected virtual IEnumerable<BaseClient> Services { get; }
you can get via DI too, and then get correct ServiceHandler by enum.
And your main function to call all this:
switch (clientCode)
{
case 1:
baseClient = ClientFactory.GetClientService(ClientServicesEnum.CostcoClient);
break;
case 2:
baseClient = ClientFactory.GetClientService(ClientServicesEnum.Another2);
break;
default:
break;
}
bool status = baseClient.ProcessData(null); //your model
The main thing is - you can use more than one pattern, for example one from Creational patterns, and one from Structural.
If i need some help in code architecture i use this:
https://refactoring.guru/
I think, using this example you can remove properties AccountName and Task, because of request models in methods.
Recently I have started to dig into MVVM to structure a WPF application I am working on. I am struggling to understand how I can keep collections in sync between Model and ViewModel, and in conjunction with that, how to validate information the user will enter.
Suppose I have a (theoretical) class Building, the model, that will store a building layout, during runtime in memory, and otherwise in xml via serialization. Building has a member List, and each entry Floor in that list can have other Lists, like List and List, which could again have members which are Lists (ie. List).
The model:
namespace TestMVVM
{
public class Building
{
public string strName { get; set; }
public List<Floor> floors { get; set; }
}
public class Floor
{
public int iNumber { get; set; }
public List<Room> rooms { get; set; }
}
public class Room
{
public int iSize { get; set; }
public string strName { get; set; }
public List<Door> doors { get; set; }
}
public class Door
{
public bool bIsLocked { get; set; }
}
}
In the View, the List of type Floor will be editable in a DataGrid. The user can enter a new row in the DataGrid to add a Floor to the Building class. In another DataGrid, Rooms could be added to a Floor. This is quite easy when I make all Lists into ObservableCollections, and directly couple them with the View. However, this also means there is no proper separation of concerns, and it gets messy once validation comes into play.
So I wrote a ViewModel class, BuildingViewModel. It will hold a reference to an instance of the model. This is where I run into trouble: the ViewModel will hold an ObservableCollection of type FloorViewModel. But when the user adds an entry, how do I also add an entry to the List in the model? And mostly, keep the data in sync? What if a Room is added to a Floor, or a Door to a Room, how to know where in the Model to update which data? Ie. how to sync nested List member data?
Subsequently I would to make sure no duplicate Floors can be created; ie. if the user adds a floor with a number that is already in the List, the DataGrid must report an error. Same if an existing floor is edited, and same for Room names. I would think that kind of error checking cannot happen within the FloorViewModel class, because it has no access to other instances of itself.
I have searched a lot but found no clear answer to this. It would seem like a rather common situation? Maybe I am simply going in the wrong direction with this?
This is the current ViewModel, where ViewModelBase is a generic class holding implementations of INotifyProretyChanged and INotifyDataErrorInfo.
namespace TestMVVM
{
public class BuildingViewModel : ViewModelBase
{
private Building building;
public string strName
{
get { return building.strName; }
set
{
building.strName = value;
if (value == "") AddError("strName", "Name cannot be empty.");
OnPropertyChanged("strName");
}
}
public ObservableCollection<FloorViewModel> floors
{
// what goes here? how to sync members of floor to the model, and validate data?
}
public BuildingViewModel(Building b)
{
building = b;
}
}
public class FloorViewModel : ViewModelBase
{
public ObservableCollection<Room> rooms
{
// what goes here? how to sync members of room to the right Floor of the model, and validate data?
}
}
// etc
}
There is a problem in the classes, that You provided. Try to apply the law of Demeter, watch this video about how to structure correctly the House object (even same example), than You only call the correct level's addX() method, that will validate.
Look you need to read again MVVM concept.. All the idea is to have one view model per each view. In our situation try this:
namespace TestMVVM
{
public class BuildingViewModel : ViewModelBase
{
private Building building;
private ObservableCollection<Floor> _floors;
public string strName
{
get { return building.strName; }
set
{
//building.strName = value;
if (String.IsNullOrEmpty(value))
{
AddError("strName", "Name cannot be empty.");
return;
}
building.strName = value;
OnPropertyChanged("strName");
}
}
public ObservableCollection<Floor> floors
{
get
{
return _floors;
}
set
{
_floors = value;
}
}
public BuildingViewModel(Building b)
{
building = b;
}
public void AddNewFloor(Floor)
{
// valid your floor
// floors.Add(floor);
}
}
Now I suggest you to add function that will validate your changes in floors and not in the setter of the property.
Or override/create ObservableCollection class and redefine all methods :
public class MyObservableCollection<T> : ICollection<T>, INotifyCollectionChanged, INotifyPropertyChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
public event PropertyChangedEventHandler PropertyChanged;
public int Count { get { return _reference.Count; } }
public bool IsReadOnly { get { return _reference.IsReadOnly; } }
private readonly IList<T> _reference;
public MyObservableCollection(IList<T> reference)
{
_reference = reference;
}
public IEnumerator<T> GetEnumerator()
{
return _reference.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public void Add(T item)
{
_reference.Add(item);
SendNotification();
}
public void Clear()
{
_reference.Clear();
SendNotification();
}
public bool Contains(T item)
{
return _reference.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
_reference.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
var result = _reference.Remove(item);
SendNotification();
return result;
}
private void SendNotification()
{
if (CollectionChanged != null)
{
CollectionChanged(this, new NotifyCollectionChangedEventArgs(new NotifyCollectionChangedAction()));
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("..."));
}
}
}
Why you don't change type (List to ObservableCollection) on Model ?
In this case :
public ObservableCollection<FloorViewModel> floors
{
get{return building.floors;}
}
I was reading an interesting article using of DataFlow + dynamic method invocation to make an Actor model in C#. Here is the completed example verbatim.
using System;
using System.Threading.Tasks.Dataflow;
namespace ConsoleApplication
{
public abstract class Message { }
public abstract class Actor
{
private readonly ActionBlock<Message> _action;
public Actor()
{
_action = new ActionBlock<Message>(message =>
{
dynamic self = this;
dynamic mess = message;
self.Handle(mess);
});
}
public void Send(Message message)
{
_action.Post(message);
}
}
class Program
{
public class Deposit : Message
{
public decimal Amount { get; set; }
}
public class QueryBalance : Message
{
public Actor Receiver { get; set; }
}
public class Balance : Message
{
public decimal Amount { get; set; }
}
public class AccountActor : Actor
{
private decimal _balance;
public void Handle(Deposit message)
{
_balance += message.Amount;
}
public void Handle(QueryBalance message)
{
message.Receiver.Send(new Balance { Amount = _balance });
}
}
public class OutputActor : Actor
{
public void Handle(Balance message)
{
Console.WriteLine("Balance is {0}", message.Amount);
}
}
static void Main(string[] args)
{
var account = new AccountActor();
var output = new OutputActor();
account.Send(new Deposit { Amount = 50 });
account.Send(new QueryBalance { Receiver = output });
Console.WriteLine("Done!");
Console.ReadLine();
}
}
}
This works as intended. Moving Actor & Message classes into a new class library and referencing properly causing an issue. When run it throws a RuntimeBinderException on the dynamic self.Handle(mess); within the Actor constructor saying Actors.Actor does not contain a definition for 'Handle'. Are there limitations to dynamic method calls I can't seem to find in the MSDN or syntax magic I missing to do this from a separate class library?
The original author got back to me.
Hi,
The problem is that you have declared your messages and actors inside
the internal NotWorkingProgram class.
class NotWorkingProgram // no access modifier! Default is 'internal' {
public class Deposit : Message
...
public class AccountActor : Actor
{
public void Handle(Deposit message)
...
} }
When you run the program the runtime tries to find a method named
'Handle' with a parameter of typ 'Deposit'. It can't find anything
because the AccountActor class is not visible from the Actors Project.
It is hidden inside the invisible NotWorkingProgram. If you make the
NotWorkingProgram class public (or move the Deposit and AccountActor
classes outside) it works!
Regards Johan
I'm leaving this here cause the RuntimeBinderException doesn't give much info, let alone any hint of class/method privacy being a possible root
Methods specific for customers:
I try to refactore a code, where are a lot of logic for specifi customer:
public void SendDocumentsToCustomer(List<Case> cases)
{
foreach(var case in cases)
{
if(case.CustomerId==123)
{
if(case.Type==1 || case.Type==2)
{
SendDocumentsToCustomer123(case)
}
else if(case.CustomerId==456)
{
if(case.Type==1 || case.Type==3)
{
SendDocumentsToCustomer456(case);
}
}
else if(case.CustomerId==768)
{
if(case.Type==2)
{
SendDocumentsToCustomer456(case);
}
else
{
SendDocumentsToCustomer(case);
}
}
}
The list of specific customer will grow, and the conditions will be modified as well. I will have a generic solution, but maybe code like this with method DoItForClient123 is not a bad solution and I should leave it like that and goint this way introduce methods like CanDocumentsBeSendToClient123 and so on?
I will be very gratefull for some input
To separate logic for each specific customer I would use such code:
abstract class DocumentSender //Base class for all document sending components
{
public abstract bool CanSend(Case #case); // Check if sender can send the document
public abstract void SendDocument(Case #case); // Send the document
}
class DefaultDocumentSender : DocumentSender
{
public override bool CanSend(Case #case)
{
return true; //Can process all requests
}
public override void SendDocument(Case #case)
{
// Do something
}
}
class Customer123DocumentSender : DocumentSender
{
public override bool CanSend(Case #case)
{
return #case.CustomerId == 123; //Specific case
}
public override void SendDocument(Case #case)
{
if(#case.Type==1 || #case.Type==2)
{
// Do something different
}
}
}
//Separate class for getting the correct sender
class CaseSenderFactory
{
readonly List<DocumentSender> _senders = new List<DocumentSender>();
public DocumentSenderFactory()
{
//Initialize the list of senders from the most specific.
_senders.Add(new Customer123DocumentSender());
// Add more specific cases here
_senders.Add(new DefaultDocumentSender()); //Last item should be the default sender
}
public DocumentSender GetDocumentSender(Case #case)
{
//At least one sender needs to satisfy the condition
return _senders.First(x => x.CanSend(#case));
}
}
You then can use the senders like this:
var factory = new DocumentSenderFactory();
foreach(var #case in cases)
{
var sender = factory.GetDocumentSender(#case);
sender.SendDocument(#case);
}
I think it would be a good ideea to make something like this:
The ideea is if the code is really specific to some of the Customers then you could make a class for them. If the code for specific customers somehow related but combined in a diferent way then you should take a loot at DecoratorPattern(mabye it helps)
class Customer
{
public abstract SendDocumentsTo(Customer c);
}
class SpecificCustomerA
{
public overwrite SendDocumentsTo(Customer c)
{
if (c is SpecificCustomerB)
{
//Logic here
}
}
}
class SpecificCustomerB { ... }
Let's say that I got a simple todolist:
interface ITodoList
{
ITodoItem Create(title);
IEnumerable<ITodoItem> Items {get;}
}
interface ITodoITem
{
void StartTrackTime();
void StopTrackTime();
}
Now I want to enforce so that time is only tracked for one item at a time (per user).
Should I create a domain event like ItemTimeTrackingStarted that StartTrackTime generates. The event would be picked up by a ITodoService which checks if there are any other time tracked items for the current user (and stop them). Or are there a better way?
well if you have dependencies between the items, which in the case is the check, my proposal would be to move the track method into the todo list object, and away from item.
So you request a change from the object that holds all todo items, and there you locate the checks as well.
IMO I'd do it like this, I don't know all the details of the context, but for this specific functionality here it goes
public interface ITrackTime
{
void StartTrackTime();
void StopTrackTime();
}
public interface ITodoItem
{
int Id {get;}
//other stuff
}
public TodoItem:ITodoITem, ITrackTime {}
public class TodoList:ITodoList,ITrackItem
{
ITodoItem Create(title)
{
//create item and add it to collection
}
TodoItem _currentlyTracking;
void StartTrackTime(int itemId)
{
if (_currentlyTracking == null)
{
// getItem and call method for item ..
item.StartTrackTime();
_currentlyTracking=item;
}
else{
//get item and check to see if it is the same id
//throw exception if it is not, ignore it if it is
}
}
}
var list = new TodoList();
ITodoItem item= list.Create("titel");
list.StartTrackingTime(item.Id);
list.StartTrackingTime(otherId); //should throw or whatever handling
Everything is contained within the AR (TodoList). One again, this is a rough draft as I'm not fully aware about the context and the domain.
As stated, the ToDoList should enforce the constraint since the constraint is defined at the ToDoList level. (Unless it is defined at the user level as you indicated in which case the responsibility would shift there). You can leave the method on the item, but it can reference the parent todo list. The code could look like this:
public class ToDoList
{
public IList<ToDoListItem> Items { get; private set; }
// factory method creates items as required by ToDoList
public ToDoListItem Create(string title)
{
var item = new ToDoListItem(this, title);
this.Items.Add(item);
return item;
}
ToDoListItem currentItem;
public void StartTrackTimeFor(ToDoListItem item)
{
if (this.currentItem != null)
throw new Exception();
// could also throw different exception if specified item is current item being tracked
// start time tracking logic.
this.currentItem = item;
}
public void StopTrackTimeFor(ToDoListItem item)
{
if (this.currentItem != item)
throw new Exception();
// stop time tracking logic.
this.currentItem = null;
}
}
public class ToDoListItem
{
public ToDoListItem(ToDoList list, string title)
{
this.ToDoList = list;
this.Title = title;
}
public ToDoList ToDoList { get; private set; }
public string Title { get; private set; }
public void StartTrackTime()
{
this.ToDoList.StartTrackTimeFor(this);
}
public void StopTrackTime()
{
this.ToDoList.StopTrackTimeFor(this);
}
}