I have a container class called PaymentPlan, which holds basic Payment summary info. It also holds a list of ExpectedPayments. Hopefully a fairly basic OOP type question, my brain appears to have gone to sleep - I have a property in the ExpectedPayment class which needs to interrogate a property on the PaymentPlan class to determine the result.
I'm currently storing a reference to the PaymentPlan as a property on the ExpectedPayment class, however, it has a public getter, and following DDD, I feel this is a bit of a code smell. Is there a better way to achieve what I want?
I've removed all but the necessary bits as an example:
public class PaymentPlan
{
private readonly List<ExpectedPayment> _payments;
public PaymentPlan(List<ExpectedPayment> payments)
{
... Other Stuff
//TODO: Fix this smell
_payments = payments;
_payments.ForEach(p => p.Plan = this);
}
... Other Properties
}
And the ExpectedPayment class:
public class ExpectedPayment
{
public ExpectedPayment(... Args removed for example)
{
}
//TODO: Attempting to avoid this public setter as I have no control..
public PaymentPlan Plan { get; set; }
public PaymentState PaymentState
{
get
{
if (Plan.SomePropertyOnPlan == "SomeValue")
{
return PaymentState.SomeState;
}
else
{
... Other logic to determine the payment state of this expected payment.
}
}
}
... Other Properties
}
Any help appreciated! - I would like to know some techniques if possible as know there are multiple ways to achieve what I'm after.
Thanks,
Alex
As if ExpectedPayment shouldn't exist if it hasn't any PaymentPlan, you must force your ExpectedPayment() constructor to provide PaymentPlan to caller and add a "friendly" method for adding new ExpectedPlan on PaymentPlan .
public class ExpectedPayment
{
public ExpectedPayment(PaymentPlan plan, ..... other args)
{
Plan = plan ;
plan.AddExpectedPlan(this) ;
......
}
......
....
public class PaymentPlan
{
.........
internal void AddExpectedPlan(ExpectedPlan expectedPlan)
{
...........
_payments.Add(expectedPlan) ;
}
}
Related
I've made a class with T. It looks like this.
public interface ISendLogic<T> where T : NarcoticsResult
{
ChangeType Change_New();
ChangeType Change_Cancel();
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
public class SendLogic<T> : ISendLogic<T> where T : NarcoticsResult
{
private eReportType _type;
private bool Send_Change()
{
// Send to server by xml file
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public ChangeType Change_New()
{
_type = change_new;
Send_Change();
}
public ChangeType Change_Cancel()
{
_type = change_cancel;
Send_Change();
}
public PurchaseType Purchase_New()
{
_type = purchase_new;
Send_Purchase();
}
public PurchaseType Purchase_Cancel()
{
_type = purchase_cancel;
Send_Purchase();
}
}
There are two types, ChangeType and PurchaseType
and these are inherited from NarcoticsResult.
I thought the person who want to use this class would use it like this.
// this class can only be used when someone wants to use change function
var logic = SendLogic<ChangeType >();
logic.Change_New();
logic.Change_Cancel();
Here is a question.
I want to force this class to be used only as I thought.
I mean, I want to prevent it to be used like this.
var logic = SendLogic<ChangeType>();
logic.Change_New(); // OK
logic.Purchase_New(); // You should make this class like SendLogic<PurchaseType>()
I thought I add some code which check type of T in every function.
How do you think the way I thought. I think there are better way to fix it
Please tell me a better way
thank you.
Personally, I don't think you need a generic class in this case. What you need is either an abstract base class or an interface. I personally love the interface approach as below:
public interface ISendLogic {
void New();
void Cancel();
}
So now you've got a contract that will force the consumer of your code to use New or Cancel methods only.
The next step you can implement that send logic interface for your specific implementation:
public class ChangeSendLogic : ISendLogic {
private eReportType _type;
public ChangeSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Change()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Change();
}
public void Cancel()
{
_type = change_cancel;
Send_Change();
}
}
public class PurchaseSendLogic : ISendLogic {
private eReportType _type;
public PurchaseSendLogic(
/*you can put the necessary parameters in the constructor
and keep it as private fields in the object*/
)
{
}
private bool Send_Purchase()
{
// Send to server by xml file
}
public void New()
{
_type = change_new;
Send_Purchase();
}
public void Cancel()
{
_type = change_cancel;
Send_Purchase();
}
}
From here you can see those two classes handle the implementation for each type nicely. You can think this is as an implementation of single responsibility principle. So if you have one more type, you can just add one more implementation of this interface rather than updating the existing classes.
If you want to hide the creation of those objects, in the next part you can introduce a kind of factory or selector as below:
public enum SendLogicType {
Change,
Purchase
}
public static SendLogicSelector {
public static ISendLogic GetSendLogic(SendLogicType type)
{
switch(type)
{
case SendLogicType.Change:
return new ChangeSendLogic();
case SendLogicType.Purchase:
return new PurchaseSendLogic();
}
}
}
This is how the code will be consumed:
ISendLogic sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Change);
sendLogic.New(); // change new logic executed
sendLogic.Cancel(); // change cancel logic executed
sendLogic = SendLogicSelector.GetSendLogic(SendLogicType.Purchase);
sendLogic.New(); // purchase new logic executed
sendLogic.Cancel(); // purchase cancel logic executed
Hopefully, you can get the idea of my approach. Good luck! :)
Thank you for your comment
I divided it into two parts like below
public class ChangeSendLogic : SendLogic<ChangeType>, IChangeLogic
public class PurchaseSendLogic : SendLogic<PurchaseType>, IPurchaseLogic
And I also divided interface too
public interface IChangeLogic
{
ChangeType Change_New();
ChangeType Change_Cancel();
}
public interface IPurchaseLogic
{
PurchaseType Purchase_New();
PurchaseType Purchase_Cancel();
}
And I made SendLogic<T> class to abstract class.
This is because I want to make the person who wants to use this class to use a class that inherits from this class without directly accessing it.
Thank you for your comment. I got a good idea.
Problem
I have a design issue I can't solve clevely. I'm sure there's an elegent solution, but I can't figure out how achieve it. I still managed to my my code work, but the result is ugly, and I want to learn better designs.
I did my best to provide a minimal implementation with only the bare minimum. Some aspects might therefore look weird. I hope I will get myself clear.
Context
So first, I have these simple classes that both implement the same interface:
public interface Human
{
string getName();
}
public class Adult : Human
{
public Adult(string name, string job)
{
Name = name;
Job = job;
}
public string Name { get; set; }
public string Job { get; set; }
public string getName()
{
return Name;
}
}
public class Child : Human
{
public Child(string name, string toy)
{
Name = name;
Toy = toy;
}
public string Name { get; set; }
public string Toy { get; set; }
public string getName()
{
return Name;
}
}
I use those classes in another, more complex class, that basically have the folloing structure:
class MasterClass
{
public string Name;
public string Job;
public string Toy;
private ObservableCollection<Adult> ListOfAdults;
private ObservableCollection<Child> ListOfChildren;
private ObservableCollection<Human> CurrentList; // Will point to one of the above list
public void InitiateLists()
{
// Populate above lists with data
}
public Human CurrentHuman;
public void ManageAdults()
{
CurrentList = new ObservableCollection<Human>(ListOfAdults);
}
public void ManageChildren()
{
CurrentList = new ObservableCollection<Human>(ListOfChildren);
}
public void setOtherHuman()
{
// Sets CurrentHuman as another adult/child according to currently managed list
}
public void SetManager(string newType)
{
switch (newType)
{
case "adult":
ManageAdults();
break;
case "child":
ManageChildren();
break;
}
}
void UpdateInfo()
{
// Set Name and Toy/Job according to currently managed human
}
void PrintInfo()
{
// Print Name and Toy/Job according to currently managed human
}
}
This is the skeleton of my current implementation, with aspects I can't modify due to other constraints. In this class, I want the methods PrintInfo() and UpdateInfo() to behave differently depending if the CurrentHuman is an Adult or a Child.
So far
I managed to make it work with a swich-case in both methods and some cast. Like this:
void UpdateInfo(string currentType)
{
Name = CurrentHuman.getName();
switch (currentType)
{
case: "adult":
Job = ((Adult) CurrentHuman).Job;
break;
case: "child":
Toy = ((Child) CurrentHuman).Toy;
break;
}
}
This is really not ideal though. In my actual design, I have a lot more types, and other methods that behave differently according to the type of the CurrentItem. So I'm now drowning in switch-cases. This makes my code messy, duplicated and very hard to maintain.
Possible solution with interfaces
Since I just discovered them, I thought I could use interfaces. I did my best, but couldn't get a solution to work.
I imagined a simple interface like so:
public interface IUpdater
{
void UpdateData(); // Takes the values from CurrentHuman and store them in the private members Name and Job/Toy depending on current type.
void Print();
}
I also implement my interface in two different ways:
class AdultUpdater : IUpdater
{
public void Print()
{
// Print Adult stuff only
}
public void UpdateData()
{
// Update Adult data only.
}
}
and a similar class ChildUpdater : IUpdater. They both implement the dedicated code for the Child/Adult.
If I declare a private IUpdater Updater as private member of my MasterClass, this allows me to change my methods ManageAdult()and ManageChildren() like this:
public void ManageAdults()
{
CurrentList = new ObservableCollection<Human>(ListOfAdults); // Same as before
Updater = new AdultUpdater(); // Specify implementation to use
}
(similar for ManageChildren()).
I can then brilliantly implement my UpdateInfo() like this:
void UpdateInfo()
{
Updater.UpdateData();
}
and my PrintInfo() method like this:
void PrintInfo()
{
Updater.Print();
}
Interfaces are truly amazing! Oh but wait...
New problem
This seems very promising. My problem is that I don't know how to implement the code of my class AdultUpdater() and class ChildUpdater(). More precisely, these two classes need to access private members of the MasterClass, namely the members Name, Job and Toy. The UpdateData() need to modify them, and the Print() need to display them. I feel so stupidely stuck at this point, so close to a very elegent solution. Does someone have an idea how to finalize this design?
Thank you for reading... I'm sorry if this issue could have been reduced to a more concise question. I had the feeling some details about my current implementation were necessary to get a suitable answer.
As I see it, you are trying to "manage" your humans. Just let them self do the job.
f.e. Don't Print from the manager/masterclass and decide, what to print, but get the printed data (even if only parts, but the parts that are different) from humans and just put it all together in the masterclass.
Use Polymorphism for you. They (your objects/humans) already know, what to print out or update, so let them do the Job. Try to spread the work, instead of pulling it all into one class.
Here is what I advise,
You have a Human class which corresponds to your IHuman, something like this
public class Human : IHuman
{
public Human(string name, string job)
{
Name = name;
Job = job;
}
public string Name { get; set; }
public string Job { get; set; }
public string getName()
{
return Name;
}
}
Your adult and child class would then Inherit the Human class and pass back the constructor values.
public Adult(string name, string job) : base (name, job)
{
}
When you create an instance of adult, you will pass in the name and job, and you can call getName because it will be inherited from the Human class.
I am currently designing an API and I have run into a design issue I'm not sure how to approach.
I have a customer facing class that depends on another class from within the model. I need to test the Customer Facing class because it contains business logic.
Normally I would use Dependency Injection to handle this case, like this contrived example:
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing(IRunQuery needed)
{
Needed = needed;
}
IRunQuery Needed { get; }
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
I inject a Stub of the IRunQuery interface when unit testing; it is an expensive operation. This has one enormous glaring issue, though. IRunQuery is not to be known about by the customer. They shouldn't need to know about it and the constructor for CustomerFacing should be:
public CustomerFacing() { }
How do I Unit Test CustomerFacing without injecting the dependency in the constructor?
you could have 2 constructors: one for unit tests where you inject the dependency, and one that is for production, that creates the dependency some other way, possibly calling the other ctor. lookup "poor-man's DI":
class MyClass
{
public MyClass(IService service)
{
this.Service = service;
}
public MyClass() : this(new Service())
{
}
}
I used "Property Injection" to solve this issue.
"IRunQuery" has a very reasonable default value. It is only in the testing case that it needs to be modified. I can define it as internal which obscures it from consumer eyes while still allowing tests to modify it before it is accessed.
public interface IRunQuery
{
ResultObject RunQuery();
}
public class CustomerFacing
{
public CustomerFacing()
{
}
private IRunQuery _needed = null;
internal IRunQuery Needed
{
get
{
if (_needed = null)
{
_needed = new StandardQuery();
}
return _needed;
}
set
{
_needed = value;
}
}
public void DoSomethingForCustomer()
{
// Do some stuff.
result = Needed.RunQuery();
// Do some more stuff.
}
}
Thanks for the help everyone.
I am working on a C# project and I need to manage a local cache of data and present it on a GUI.
For example I have:
public class DataFromOtherLibrary
Now I want make a class to help translate the information I need out of it
public class MyDataModel
{
private DataFromOtherLibrary cache;
public MyDataModel ( DataFromOtherLibrary Source)
{
cache = Source;
}
public long Field1 { get { return cache.SomeField; } }
public long Field2 { get { return cache.OtherFiled; } }
}
Now the issue I have is I need to create a MyDataModel for every DataFromOtherLibrary it would be nice to have a single translator class. I'm not sure how to do it and still implement properties (which I need to data-bind to).
Thanks
Matt
You should use a Provider with all your DataModels in it Like:
public class MyDataModelProvider
{
public List<MyDataModel> DataModelList { get; set; }
MyDataModelProvider()
{
loadDataModelList();
}
private void LoadDataModel()
{
foreach (Cachobject c in Cache)
{
this.DataModelList.Add(new MyDataModel(c.valueA,c.valueB));
}
}
}
and for this Provider you also need a Factory Like:
[Singleton(true)]
public class DataModelListProviderFactory
{
private static DataModelListProvider dataListProvider;
public DataModelListProvider getInstance()
{
if (dataListProvider == null)
{
dataListProvider = new DataModelListProvider();
return dataListProvider;
}
else
return dataListProvider;
}
}
Because now you have a single Spot with all your DataModels and you only must recieve them once. You can also easily search the List for a specific Model if you have a case or you show all the Data in a View.
You can read here more about Factory Patterns.
Hope that helps.
I have a main object which has some properties and methods. This object can have multiple parts. These parts are required. The amount of these parts is variable.
Each part has different properties and is referenced to the main object.
To accomplish this in my GUI I have a tabcontrol. The first tab is the main object. The other tabs describes the main object further. These 'other' tabs are the parts I mentioned above.
I am trying to design an architecture, but I can't figure I hope yoy can help me.
As suggested from the answers, the part-tabs inherit from an interface. But how does the main know about it's parts? The parts can't be hardcoded because it is variable. To hardcode the parts is a violation of the OCP principle.
Also, when loading the main object, again, how does it knows about it parts? I have to 'register' them somewhere, but where?
Create interface for your parts, that can have reference to main object. And main object will contain collection of parts as Collection<IPart>
class MainObject
{
Collection<IPart> Parts {get;set;}
}
interface IPart
{
MainObject MainObject {get;set;}
}
class SomePartImpl : IPart
{
//properties of this IPart implementation
}
This classes is entities. Your data service must implement logic for saving and cascade operations.
Sample wcf service(from my project):
[EnableClientAccess]
public class ModelService : LinqToEntitiesDomainService<dpirtEntities>
{
public void InsertZone(Zone zone)
{
if ((zone.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(zone, EntityState.Added);
}
else
{
this.ObjectContext.Zones.AddObject(zone);
}
}
public void UpdateZone(Zone currentZone)
{
Zone originalZone = this.ChangeSet.GetOriginal(currentZone);
if ((currentZone.EntityState == EntityState.Detached))
{
if (originalZone != null)
{
this.ObjectContext.Zones.AttachAsModified(currentZone, originalZone);
}
else
{
this.ObjectContext.Zones.Attach(currentZone);
}
}
foreach (Document doc in this.ChangeSet.GetAssociatedChanges(currentZone, o => o.Documents))
{
ChangeOperation op = this.ChangeSet.GetChangeOperation(doc);
switch (op)
{
case ChangeOperation.Insert:
if ((doc.EntityState != EntityState.Added))
{
if ((doc.EntityState != EntityState.Detached))
{
this.ObjectContext.ObjectStateManager.ChangeObjectState(doc, EntityState.Added);
}
else
{
this.ObjectContext.AddToDocuments(doc);
}
}
break;
case ChangeOperation.Update:
this.ObjectContext.Documents.AttachAsModified(doc, this.ChangeSet.GetOriginal(doc));
break;
case ChangeOperation.Delete:
if (doc.EntityState == EntityState.Detached)
{
this.ObjectContext.Attach(doc);
}
this.ObjectContext.DeleteObject(doc);
break;
case ChangeOperation.None:
break;
default:
break;
}
}
}
public void DeleteZone(Zone zone)
{
if ((zone.EntityState == EntityState.Detached))
{
this.ObjectContext.Zones.Attach(zone);
}
this.ObjectContext.Zones.DeleteObject(zone);
}
}
Have a List or Dictionary in your Main class and store the references to the different objects.
For example:
All the tabs implement an interface called IScreenTab.
class MainTab : IScreenTab
{
// Store a map of scree name to screen object
// You can also just use a List<IScreenTab>
private Dictionary<string, IScreenTab> m_OtherScreens;
// Your implementation goes here
public MainTab(){ }
public MainTab(List<IScreenTab> screenTabList){ }
public AddTab(string screenName, IScreenTab screenTabObj){ }
}
I've done something similar in the past, and I decoupled my GUI from my domain design by using an IoC container. In my code I used StructureMap, which was very easy to adopt.
I had exactly the same setup in which there was an 'editor' which contained a number of 'tabs'. Each tab could either contain some different view of my 'object' or it could show an item from collections stored within the 'object'. So there were a number of static and variable tabs.
So, I needed two things.
1. A way to create an editor, with the correct number of tabs.
2. A way to create the tab, plus all it's controls.
So, I created an interface for each, which looked loosely like this.
public interface IEditorFactory<TObject>
{
Editor CreateEditor(TObject instance);
}
public interface ITabEditorFactory<TObject>
{
void CreateTab(TObject instance, Editor parent);
}
I'll leave Editor up to your imagination. By in my app it was a custom UserControl, with various features and behaviour.
Next, imagine we had a Person, who had personal info, an Address an multiple contracts.
public class Person
{
public string Title { get; set; }
public string Forename { get; set; }
public string Surname { get; set; }
public string EmployeeNumber { get; set; }
public string NationalInsuranceNumber { get; set; }
public Address Address { get; set; }
public IEnumerable<Contract> Contracts { get; }
}
My app wanted to display one 'Personal Details' tab, one 'Employment' tab, one 'Address' tab and multiple 'Contract' tabs.
I implemented the following.
public class PersonalTab : ITabEditorFactory { ... }
public class EmployeeTab : ITabEditorFactory { ... }
public class AddressTab : ITabEditorFactory { ... }
public class ContractTab : ITabEditorFactory { ... }
Notice how #1 and #2 implement the same ITabEditorFactory. That's because they both display different aspects of the Person.
But before I had implemented those I implemented the PersonEditor
public class PersonEditor : IEditorFactory { ... }
It was good that I implemented this first, as it forced de-coupling my editor factory from all the tab factories. I wouldn't accidentally slip in any references to concrete classes. My editor factory just knew how to ask for a ITabEditorFactory<> for the Person, Address and Contract classes.
My final solution was a little more complicated than I outlined above, as it also covered Editor re-use for different instances, how to handle multiple (or no) tab editors for any a single class, and being able to define security on a tab-by-tab basis.
The end result was that I had a GUI model that was decoupled from my domain, and was extensible without requiring me to change a single line of existing code.
Lovely jubbly.