I have the following problem:
I would like to have the following objects:
Several DTOs, e. g. for employees, customers etc.
Several user controls, one (or more) for each DTO which displays the DTO content and provides modifications the user might have made back to the DTO.
The base class of these user controls provides some default functionality.
A standard button panel with CRUD operations that should work with all my user controls.
What I did so far is:
I have an abstract base class for DTOs and several special DTO classes.
I have standard functionality in my default button event handlers. As an example: The save button asks the user control for the current data (via DTO), passes data to some checking class, and if all checks passed, the data are stored in the database. To retrieve the data, there is a reference to the client object setted via constructor.
I have a base class for my user controls. This is not abstract because I would like to have designer support. Therefore, this class provides access to/from its controls via virtual methods, based on the abstract base class for DTOs.
I have a generic interface based on specific DTO types which defines data access with identical method names.
Now I create a new user control, inheriting from my user control base class and implementing the generic interface for the suited DTO class. Therefore, the BaseDTO GetData() is overridden with the new SpecialDTO GetData() method.
And here is my problem:
Within my event handler, the Client control is of my desired type, e. g. CustomerClientControl. But the invoked method is not new CustomerDTO CustomerClientControl.GetData() but the base default implementation BaseDTO BaseClientControl.GetData().
How can I get out of this? Thanks for any help or suggestions to make the whole construct a little more handsome.
Edit: Here is some code.
// in my "standard functionality"
BaseClient Client { get; } // or IClientDataAccess<BaseDTO>
void ButtonSave()
{
var data = this.Client.GetData(); // in runtime, this.Client is CustomerClient
// the following works, don't worry. :-)
if (this.CheckLogic.CheckData(data))
{
this.DataAccess.SaveData(data);
}
}
public interface IClientDataAccess<T> where T : BaseDTO
{ T GetData(); }
public BaseClient : UserControl, IClientDataAccess<BaseDTO>
{
public virtual BaseDTO GetData()
{
return new BaseDTO(); // some stupid default
}
}
public CustomerClient : BaseClient, IClientDataAccess<CustomerDTO>
{
public new CustomerDTO GetData()
{
// CustomerDTO : BaseDTO
return new CustomerDTO(this.CustomerNameTextbox);
}
}
You can't change function signature when overriding.
It means you cannot have this transform public BaseDTO GetData() -> public CustomerDTO GetData().
So you need to change CustomerClient to
public CustomerClient : BaseClient
{
public override BaseDTO GetData()
{
// CustomerDTO : BaseDTO
return new CustomerDTO(this.CustomerNameTextbox);
}
}
or to look for another class design.
Related
I have a business requirement to consolidate CRUD operations into a single base class, regardless of the type of object. I am not able to modify the calling code, which could be anything ... so if there are a bunch of callers that look like this:
var state = new State("New York");
state.Save();
var city = new City("New York", state);
city.Save();
var stadium = new Stadium("Yankee Stadium", city);
stadium.Save();
All of these Save methods would need to be handle in one, single common base class.
The path I've lead myself down is to create a single generic abstract base class which these classes implement, such as the following ...
public abstract class PersistableObject<T> where T : class {
public string Id { get; set; }
public static T Find(string id) {}
public void Save() { }
public void Delete() { }
}
I then have the above objects inherit from this class:
public class City: PersistableObject<City> { }
I stripped out the CRUD methods tied to the concrete implementations and after having these various objects inherit from the abstract base class, the solution compiles without error.
And now I'm stuck. The backing store is a local XML document (decision out of my hands). I am guessing I can serialize these to XML using the normal XML serializers in .Net, but is there a better way to do this? Should I be using some sort of a repository pattern?
Thanks.
I have a BaseClass, which implements a method to populate itself form a different data structure. SubClasses will add their properties to the base ones. I want all sub-classes and sub-sub...classes to implement their own version of the method and call their parent class to do the same. So this is not just overriding, I want to force the implementation, but each implementation of the method has to be called, not just overridden.
Sort of like:
class BaseClass
{
int id;
virtual void fromDictionary(Dictionary data)
{
id = data["id"];
}
}
class Derived1 : BaseClass
{
string name;
override void fromDictionary(Dictionary data)
{
name = data["name"];
base.fromDictionary(data);
}
}
class Derived2 : Derived1
{
float size;
override void fromDictionary(Dictionary data)
{
size = data["size"];
base.fromDictionary(data);
}
}
Then doing this:
Derived2 object = new Derived2();
object.fromDictionary(dictionary);
Populates all of the object's properties.
I can make the first one virtual and override in the derived ones, but that doesn't force the implementation. And making an abstract base above this base or using an interface wouldn't force ALL levels of inheritance to implement.
The ideal case would be forcing all derived classes to implement their version AND call their parent's version (or even better, have some sort of extension/overriding that automatically calls ALL implementations of the method from the instantiated object's class upwards).
How close to that can I get ?
Seeing why you need this kind of overriding I strongly believe that you should try to move this logic to a constructor because as it looks now:
Derived2 object = new Derived2();
object.fromDictionary(dictionary);
Your object will only be valid if it has a dictionary. So instead of constructing it from a dictionary using a method, you should provide a constructor which receives a dictionary as a parameter:
Derived2 object = new Derived2(dictionary);
Now you have a valid object from the beggining. There are more reasons why you should do this instead of using a method which composes your object, one as you observed is that each subclass will need to call the base method, and having this kind of constructor (assuming that you will not provide a parameterless one) will force the inheritors to call the base one.
Another advantage in using this kind of approach is that you will have a valid object form the beginning instead of making it possible for users of that classes to make invalid objects by forgetting to call the fromDictionary() method.
Thanks for the suggestions everyone, the closest I could get is:
public abstract class DAO
{
public long id { get; set; }
public void fromDictionary(Dictionary<string, object> obj)
{
//Does own part in the method
id = (long)obj["id"];
//Calls most derived implementation
fromDictionaryOperation(obj);
}
//Forces child to implement its part
protected abstract void fromDictionaryOperation(Dictionary<string, object> obj);
}
//Is forced to implement its part, and the base implementation will be executed always
public class Area : DAO
{
public string name { get; set; }
protected override void fromDictionaryOperation(Dictionary<string, object> obj)
{
name = (string)obj["name"];
}
}
//Is NOT forced to implement method, and MUST call base.fromDictionary() for all this to work properly, but is NOT FORCED TO.
public class CircularArea : Area
{
public float radius { get; set; }
protected override void fromDictionaryOperation(Dictionary<string, object> obj)
{
radius = (float)obj["radius"];
base.fromDictionary(obj);
}
}
So all 2nd generation classes will be fine, but subsequent sub-classes wont be forced to implement its part or call the parent implementation. Which means that if in an implementation of a sub-sub-class, the base.fromDictionary() method is not called, then all parent classes implementation, except the first/base class, will be skipped without any compiling warning or error.
To force implementation at all levels, I guess I could put the abstract method in an Interface and make all classes implement the interface, which can't be forced itself, but is as close as I can think of.
If anyone knows a way to completely force ALL of them to implement the same method, that would be top notch.
I have the following class:
class Base<T> where T : Base<T>
{
protected static string Source;
public static List<T> Read()
{
return GetResource(Source);
}
}
I want this class as baseclass for its functionality but every derived class has to have a different Source. My problem is that I can't assure the Source is set before Read is called. I know I could ask if the Source is set before GetResource is called but that's not the point. I need it to be set before any static member of my class is called.
Generic parameters can't have static Members so I can't take it from there.
I tried setting the Source in the derived class's static constructor but that will only be called when I call a member that is in the derived class and not in the Base.
I tried using a overridable method inside of the static Base constructor but such a method has to be static as well and static methods can't be overwritten.
When I set the Source manually, there is a chance that the Read-Function has already been called, so I have to set the Source before it can be called.
I know I could give Source as a parameter in Read but I want Read to be used without parameters.
Is there any way I can assure that the Source is Set before any other Member of my class is called, so that any dependent code is inside the derived class and doesn't have to be called by anyone using a derived class?
I basically want it to work like this:
class Derived : Base<Derived>
{
// somehow set Source
Source = "This is my source";
}
class User
{
private List<Derived> MyResources;
public User()
{
MyResources = Derived.Read();
}
}
Note: the Source is basically a SQL statement so an Attribute or something like that wont be sufficient I think.
Ok, I found an answer. It is not as pretty as I hoped it would be but its the best I could come up with.
I will use an interface to force an Instance of T to have a certain method that provides my source.
interface ISource
{
string GetSource();
}
I then implement that into my base class as such:
class Base<T> where T : Base<T>, ISource, new()
{
public static List<T> Read()
{
// here I create an Instance to be able to call the Methods of T
string source = (new T()).GetSource();
return GetResource(source);
}
}
The derived class:
class Derived : Base<Derived>, ISource
{
public string GetSource()
{
return "This specific source";
}
}
Usage as such:
class User
{
public User()
{
List<Derived> myResources = Derived.Read();
}
}
This of course will lead to every instance of Derived having the GetSource-method but for my scenario thats not a big deal.
Also, since it creates an instance in the Read-method, this could be time consuming depending on the constructor of Derived. In my scenario it only has the standard constructor.
So use with caution.
Well, I've had to rewrite this as I've been down voted five times for giving too much detail... Go figure!
class BaseModel
{
public T[] Get<T>()
{
// return array of T's
}
public T Find<T>(object param)
{
// return T based on param
}
public T New<T>()
{
// return a new instance of T
}
}
class BaseRow
{
private BaseModel _model;
public BaseRow(SqlDataReader rdr, BaseModel model)
{
// populate properties of inheriting type using rdr column values
}
public void Save()
{
// calls _model.Save(this);
}
}
I currently have a number of classes that inherit the BaseModel class. Each of the methods exposed by BaseModel will return an instance, or an array of instances of a type that inherits the BaseRow class.
At the moment, when calling the exposed methods on the BaseModel via an inheriting class, i.e.
using(DeviceModel model = new DeviceModel())
{
DeviceRow row = model.Find<DeviceRow>(1);
DeviceRow[] rows = model.Get<DeviceRow>();
DeviceRow newRow = model.New<DeviceRow>();
}
I have to specify the type (a class that inherits the BaseRow class), as the methods in BaseModel/BaseRow do not know/care what type they are, other than they inherit from BaseRow.
What I would like to do is find a way to remove the need to specify the without having to replicate code in every class that inherits BaseModel, i.e.
class DeviceModel : BaseModel
{
public DeviceRow Find(object param)
{
return this.Find<DeviceRow>(param);
}
}
Note: Unfortunately I am unable to implement or use any third party solutions. That said, I have tried using Castle Active Record/nHibernate and to be honest, they are very big and heavy for what should be a very simple system.
Hopefully I haven't provided "too much" detail. If I have, please let me know.
Thanks
If I were you, I'd suggest making BaseModel a generic class. In a situation of "can't win either way", the code you've removed to make others happy might have told me more about what you're doing (not a criticism by any stretch - I appreciate your position).
class BaseModel<T>
{
public virtual T[] Get()
{
// return array of T's
}
public virtual T Find(object param)
{
// return T based on param
}
public virtual T New()
{
// return a new instance of T
}
}
That's your base, and then you have inheritors like:
class DeviceModel : BaseModel<Device>
{
public override Device New()
{
return new Device();
}
}
Now, any generic operations you define in DeviceModel will default to returning or using strongly typed Device. Notice the virtual methods in the BaseModel class. In the base class methods, you might provide some basic operations predicated upon using T's or something. In sub-classes, you can define more specific, strongly typed behavior.
I'd also comment that you might want to pull back a little and consider the relationship of BaseModel and BaseRow. It appears that you're defining a parallel inheritance hierarchy, which can tend to be a code smell (this is where more of your code might have come in handy -- I could be wrong about how you're using this). If your ongoing development prospects are that you're going to need to add a FooRow every time you add a FooModel, that's often a bad sign.
I have been reading a lot on MVC/MVP patterns.... I have a simple question....If you have a view with loads of controls....say 10 texboxes and 10 checkboxes....etc etc... Am I expected to specify the properties and events each one of them in my IView interface?....
Definitely not that way.
Your IView Interface will define set of contracts/ methods (it includes properties) that can be accessed by your business layer.
It is totally wrong to exposed your control in interface like this:
public interface IView
{
TextBox UserNameTextBox{get;set;}
}
You should not have interfaces defined in this way. This is really a bad programming.
You should rather expose some contracts that your UI layer will implement.
E.g.
public interface IView
{
public void SetUserName(string Text);
}
You can implement this interface on winform as well as webform.
Similarly, you are also not supposed to expose knowlede of UI in interface(Contract).
Lets assume a scenario where you have to display information of Employee object on UI.
You should pass Employee object to UI through this interface and UI will take care of way of representing this Employee object.
Your BL should never bother about n number of TextBoxes and checkboxes.
public class Employee
{
//first name
//last name
//is manager
//is teamleader
//address
}
public interface IEmployeeView
{
void SetEmployee(Employee employee);
}
public partial class EmployeeForm:WinForm,IEmployeeView
{
public void SetEmployee(Employee employee)
{
ENameTextBox.Text = employee.FirstName+" "+employee.LastName;
}
}