Starting with the use case.
Let's consider the base for this questions is a big framework and implementations of business objects of some software.
This software hast to be customized quite regularly, so it would be preferred that most of the C# objects are extendable and logic can be overriden. Even "model data".
The goal would be to be able to write code, create objects with input parameters - that may create more objects etc - and you don't have to think about whether those objects have derived implementations in any way. The derived classes will be used automatically.
For ease of uses a typesafe way to create the objects would be preferred as well.
A quick example:
public class OrderModel
{
public int Id { get; set; }
public string Status { get; set; }
}
public class CustomOrderModel : OrderModel
{
public string AdditionalData { get; set; }
}
public class StockFinder
{
public Article Article { get; }
public StockFinder(Article article)
{
Article = article;
}
public virtual double GetInternalStock() { /*...*/ }
public virtual double GetFreeStock() { /*...*/ }
}
public class CustomStockFinder : StockFinder
{
public bool UsePremiumAvailability { get; }
public CustomStockFinder(Article article, bool usePremiumAvailability)
: base(article)
{
UsePremiumAvailability = usePremiumAvailability;
}
protected CustomStockFinder(Article article) : this(article, false) { } // For compatibility (?)
public override double GetFreeStock() { /*...*/ }
}
In both cases I wanna do stuff like this
var resp = Factory.Create<OrderModel>(); // Creates a CustomOrderModel internally
// Generic
var finderGeneric = Factory.Create<StockFinder>(someArticle);
// Typesafe?
var finderTypesafe1 = Factory.StockFinder.Create(someArticle); // GetFreeStock() uses the new implementation
var finderTypesafe2 = Factory.StockFinder.Create(someArticle, true); // Returns the custom class already
Automatically generating and compiling C# code on build is not a big issue and could be done.
Usage of Reflection to call constructors is okay, if need be.
It's less about how complicating some code generation logic, written code analyzers, internal factories, builders etc are, and more about how "easy" and understandable the framework solution will be on a daily basis, to write classes and create those objects.
I thought about tagging the relevant classes with Attributes and then generating a typesafe factory class automatically on build step. Not so sure about naming conflicts, or references that might be needed to compile, as the constructor parameters could be anything.
Also, custom classes could have different constructors, so they should be compatible at each place in default code where they might be constructed already, but still create the custom object. In the custom code then you should be able to use the full custom constructor.
I am currently considering several different cases and possibilities, and can't seem to find a good solution. Maybe I am missing some kind of design pattern, or am not able to look outside of my bubble.
What would be the best design pattern or coding be to implement use cases like this?
Related
I'm currently looking for a nice and clean way to manage/store application configuration. I've seen many approaches and frameworks, yet I'm not really satisfied because most I've seen follow a simple idea:
* Store 'some' data
* Retrieve 'some' data
Which might look like this (pseudo) for a simple key value store:
public T Get<T>(string key);
public void Save<T>(string key, T value);
The .NET configuration framework living inside System.Configuration that has been around for a while tackles this nicely because it allows strongly typed configuration objects by providing a set of base classes which one can derives from to describe the configuration scheme. However this requires a lot of work and boilerplate code to get things running.
What I got in mind is something like this:
public IConfiguration<TSet> : TSet {
void Commit();
void Refresh();
}
public class MyConfigurationSet {
public string Value1 { get; set; }
public int Value2 { get; set; }
}
// usage
var config = new JsonConfiguration<MyConfigurationSet>(MYPATH);
config.Value1 = "Hello";
config.Commit();
Is there any way to make such a thing possible? In order to do this, I would need to a) derive from a generic type and b) "observe" an instance of that generic type for changes in order to track changes etc., and I'm not aware of a way those things are possible (for now, e.g. for the first part, I can't see any reason why it isn't possible other than it's currently not). Anyone got an idea?
Deriving from a generic type is no problem:
public class JsonConfiguration<T> : IConfiguration<T>
{
}
Is perfectly permissible.
As far as observing it goes, I would put a generic type constraint on the type implementing INotifyPropertyChanged so that you can register for the PropertyChanged event. You can't just "trap" a random variable assignment, the client code has to notify you.
public class JsonConfiguration<T> : IConfiguration<T> where T:INotifyPropertyChanged
{
}
After reading this question How to avoid Dependency Injection constructor madness? I still have some concerns about my application design. Suppose I have a class which takes few parameters in its constructor:
public class SampleViewModel
{
public SampleViewModel(IReader1 reader1, IReader2 reader2, IReader3 reader3)
{
// ...
}
}
IReaderX is an interface for retrieving data from different sources and looks like this:
public interface IReader1
{
int Value1 { get; }
string Value2 { get; }
}
Now, if I wanted to aggregate this interfaces into one, I would have to create another class, say ReaderManager, which would act as a wrapper for underlying classes properties. Lot of plumbing code. Not good, if you ask me.
I tried using Composition and having all readers as properties in ReaderManager class, but then I would violate Law of Demeter if I attempted to use these readers outside.
So the question is: how should I decrease number of constructor dependencies which do not communicate with each other and only expose properties, not internal logic?
Look at it from a couple of different perspectives: the consumer, and a higher-level design.
From the perspective of `SampleViewModel`
Does it not like having so many collaborators? Maybe if it had its druthers, it would only have a single collaborator. How would that collaborator look? Create an interface to represent the role for it.
For example:
public interface ISampleViewModelReader
{
int Value1 { get; }
string Value2 { get; }
double Value3 { get; }
string Value4 { get; }
}
public class AggregatedSampleViewModelReader : ISampleViewModelReader
{
public AggregatedSampleViewModelReader(IReader1 reader1, IReader2 reader2, IReader3 reader3)
{
// ...
}
// ...
double Value3 { get { return reader2.Value3; } }
// ...
}
public class SampleViewModel
{
public SampleViewModel(ISampleViewModelReader reader)
{
// ...
}
}
You indicated that you have a concern about this approach, since it would involve a "lot of plumbing code". But consider that this plumbing code is going to exist with or without a wrapper class. By defining a wrapper class, at least you're identifying an object whose sole responsibility is to handle this plumbing, rather than mixing it into the other responsibilities of the SampleViewModel.
From a higher-level design perspective
How do other objects use the IReaderX objects? Are IReader1, IReader2, and IReader3 often used together? How about IReader1 and IReader3?
The point of asking this question is to identify "hidden" abstractions so that they can be made more explicit. If certain objects are often used in tandem, it's usually representative of a broader design concept.
But sometimes a rose is a rose is a rose. Maybe SampleViewModel is the only thing that uses the IReaderX objects. Perhaps SampleViewModel's sole responsibility is to aggregate the individual readers. In these types of cases, there's nothing wrong with having several collaborators.
If another collaborator is added later on (e.g., IReader4), then all of this evaluation should take place again. Sometimes design just happens to jump out at you.
Could someone, please, explain why an answer in this question advocates usage of extension methods while defining base interfaces.
- Why not including the the SteerLeft() and Stop() methods in their respective interfaces? - Is it to illustrate adding behaviors that should not/could not be anticipated/forced by the "base"?
- Isn't it better to "force" something as basic as "steering" behavior when you're requiring a steering wheel?
Below, I've extracted relevant code. The answering person states:
you could use the Extension Methods feature added to C# 3.0 to
further simplify calling methods on those implied properties
public interface ISteerable { SteeringWheel wheel { get; set; } }
public interface IBrakable { BrakePedal brake { get; set; } }
public class Vehicle : ISteerable, IBrakable
{
public SteeringWheel wheel { get; set; }
public BrakePedal brake { get; set; }
public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }
}
public static class SteeringExtensions
{
public static void SteerLeft(this ISteerable vehicle)
{
vehicle.wheel.SteerLeft();
}
}
public static class BrakeExtensions
{
public static void Stop(this IBrakable vehicle)
{
vehicle.brake.ApplyUntilStop();
}
}
public class Main
{
Vehicle myCar = new Vehicle();
public void main()
{
myCar.SteerLeft();
myCar.Stop();
}
}
The point of using extension method is that you can add method to an existing .Net class even if you do not have the Source code or it reside within different assembly.
And extension method helps to
These methods can be added later (than type authoring time) after type has already been published.
Extension methods can target interfaces.
Different people can extend the same type differently as per their needs.
Take LINQ for example it provides Methods that work on any IEnumerable type!
EM are not some substitute of multiple inheritance and is not an inheritance mechanism. It's just a tool, like name suggests, to extend functionality of some type by your means.
In this concrete code there is no much sense of using EM. As you noted, you can easily extend functionality of the class, just by adding a new method inside its body.
EM are extremely useful in cases when you can not change original source of a class or not allowed to do so.
thanks in advance for reading this. I don’t fully understand how/when to use abstracts so I am trying to think about it each project I work on to see if it will all click some day Smile | :)
Also, the mix of accessibility levels (private, protected, internal) with keywords static, abstract, and override tend to leave me a little confused. How do I define this method/property/class....
It's not all a big mystery to me but some projects have me coding in circles when dealing with these topics.
With that said,
I have an application that reads an XML document and outputs text and image files. I’m also storing all of the information in a database. I have it working nicely.
The XML has a standard implementation with required fields and is used by multiple organizations to submit data to my app. All organizations should use (at least) the required nodes/elements that are outlined in the XML implementation guide.
So, I want to have a default data object type to be able to derive a specific organization’s data type for required elements. (If this object is going to be used, these are the fields that must be implemented).
If the org. just uses the default requirements, I can use the default object. If they use additional (optional) fields, I’ll have to create a new type inheriting the default type.
My first thought was to use and abstract class that had protected properties for my bare minimum requirements:
public abstract partial class AbstractDataObject
{
protected string DataObjectName;
protected DateTime? DataObjectDate;
etc...
}
Then, if the organization just uses the required elements of the node and no optional elements, I can use a “default” object.
internal partial class DefaultDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
}
But, if an organization uses optional fields of the required node, I can use a derived organization data object.
internal sealed partial class OranizationDataObject : AbstractDataObject
{
public new string DataObjectName { get; set; }
public new DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
Do I need the abstract class? It seems to me I can just have a DefaultDataObject (something like):
internal partial class DefaultDataObject
{
public virtual string DataObjectName { get; set; }
public virtual DateTime? DataObjectDate { get; set; }
etc...
}
And then:
internal sealed partial class OranizationDataObject : DefaultDataObject
{
public override string DataObjectName { get; set; }
public override DateTime? DataObjectDate { get; set; }
etc...
//Optional fields used by this organization
public string DataObjectCode { get; set; }
etc...
}
I’m just really trying to understand how to define these objects so I can reuse them per organization. Both ways seem to work, but I am hoping to understand how to define them properly.
Getting the XML into above objects:
public DefaultDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new DefaultDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate =
Program.TryParseDateTime((String)
t.Elements("ChildElement2")
.ElementAtOrDefault(0)
),
etc....
OR
public OranizationDataObject ExtractXmlData(XContainer root)
{
var myObject = (from t in root.
Elements("ElementA").Elements("ElementB")
select new OranizationDataObject()
{
DataObjectName = (String)t.Element("ChildElement1"),
DataObjectDate = Program.TryParseDateTime(
(String)t.Elements("ChildElement2")
.ElementAtOrDefault(0)),
DataObjectCode = (String)t.Element("ChildElement3"),
etc....
Again, thanks for reading. Don't forget to tip your wait staff....
Joe
First of all, your base class doesn't need to be abstract if it's a plain DTO class. If you don't have any functionality that needs to be implemented differently by derived classes, you can simply make it a plain base class which will hold common properties.
Next, there is no point in declaring properties in the base class (abstract in your case), if you are going to hide them (using the new keyword). You first code snippet of DefaultDataObject unnecessarily creates a bunch of new properties with the same name. Remove them completely - they are already defined in the base class.
[Edit] I didn't notice this initially, and #svick warned me, that your base class actually contained fields instead of properties, which makes me wonder why you needed to add the new keyword at all. I went over your code quickly and saw them as properties. In any case, you should never expose public fields - at least change them to auto-implemented properties by adding the { get; set; } block.
In other words, this would simply work:
// this doesn't need to be abstract.
// just put all the common stuff inside.
public class BaseDO
{
// as svick pointed out, these should also be properties.
// you should *never* expose public fields in your classes.
public string Name { get; set; }
public DateTime? Date { get; set; }
}
// don't use the new keyword to hide stuff.
// in most cases, you won't need that's behavior
public class DerivedDO : BaseDO
{
// no need to repeat those properties from above,
// only add **different ones**
public string Code { get; set; }
}
As a side note, but nevertheless important IMHO, you should simplify naming (and make it more clearer what your code does). There is no need to repeat "DataObject" in every property name, for example. But since your code is probably only a simplified version, it doesn't matter.
Lastly, have you heard of XmlSerializer? You don't need to traverse the XML elements manually. It is enough to call XmlSerializer to both serialize and deserialize your data.
Everything I need to know I learned from Sesame Street
Scrub your class design hard to make sure you've identified everything that is the same and different. Play computer, so to speak, with your classes and see how they do the same, different, or the same thing but in different ways.
What is the same, different, same but differently will likely change as you play computer.
Think in general terms of the two pillars of OO Classes. Polymorphism and Inheritance
As you do the above that is. Not so much in terms of C# implementation per se.
How things clump into same vs. different will help drive implementation
And it's all relative.
More of same default behavior? Perhaps a concrete base class instead of abstract.
More of same thing, but differently? Perhaps an abstract class instead of concrete base class.
A default way of doing x? Perhaps a virtual method.
Everyone does the same thing, but no two the same way? A delegate perhaps.
Implementation Suggestions
Make methods and fields protected as a default. Private does not get inherited. Designs change, stay flexible. If something just has to be private, fine.
virtual means you can change implementation in a sub class. It does not mean you must.
Folks seem to under-utilize delegates. They're super for polymorphic methods.
There is nothing wrong with public fields. What's the practical difference between a public field and a public auto-implemented property? Nothing. They both directly return (or set) the underlying value. So what's the point of even bothering with properties? If you want to publicly expose an underlying value differently than it's "natural" state. For example, returning a number in a specific format. And of course you can have different properties for the same field.
A Property can have a get without a set. Or vice versa. Also get and set can have different access levels. Often you'll see this as a public get and a protected (or private) set.
It depends on what the derived types will want to do. If they are going to use the default implementation and only expand on it somehow, then having the default class as the non-abstract base class is fine.
On the other hand, if they are most likely going to re-implement the functionality, you should have an abstract base class (or an interface) and a separate default class.
If you for some reason don't know which one is it, you can let the inheritors choose by having an abstract base class and leaving the default class unsealed.
Also, looking at your code, it seems you misunderstand what the various keywords do. Most of the time, you do not want to use new like this. What it does is to define another member with the same name, unrelated to the original one. Also, there's no reason to override something if you don't want to change it. So, if you expect that the derived classes won't have to reimplement the properties, you don't have to make them virtual at all.
An abstract class can already implement things that can be inherited
public abstract class DataObjectBase
{
public string DataObjectName { get; set; }
public DateTime? DataObjectDate { get; set; }
}
A concrete class can add new properties and methods
public class DerivedDataObject : DataObjectBase
{
public int NewProperty { get; set; }
}
The properties DataObjectName and DataObjectDate are already available in the new class, because they are automatically inherited from the base class.
If the abstract class defined an abstract member, however, you would have to implement it in the derived class.
Say the base class defines
public abstract void SomeMethod(string name);
The the derived class has to do this
public override void SomeMethod(string name)
{
...
}
If your base class does not have abstract members, it does not need to be abstract and can play the role of your default data object directly.
The keyword 'partial` is not needed here. It is only useful if you want to split one class into several pieces over several files.
The keyword new is wrong here. It is used to shadow an inherited member. This means that the inherited member will be hidden "behind" the new declaration. What you need, is to override. This does not hide a member, but provide an alternative implementation of the same member in the derived class.
I personally don't have my entities implement interfaces. For a Task class I wouldn't have ITask that just had the same properties defined on it.
I've seen it done a few times though, so I'm wondering where that advice comes from, and what benefits you get from it.
If you're using an ORM then the argument that says "I can change my data access" is irrelevent, so what other reason is there for doing this?
UPDATE:
A good point was made in the comments about INotifyPropertyChanged. That wasn't my point though - I'm talking about having something like this:
public interface ITask
{
int Id { get; set; }
string Description { get; set; }
}
public class Task : ITask
{
public int Id { get; set; }
public string Description { get; set; }
}
I went down this road once (interfaces for value objects). It was a royal pain in the backside, I recommended against it. The common arguments for it are:
Mocking:
They are value objects. Nought to mock. Plus mocking ends up being a large pain than either writing a builder (in Java) or using the named arguments stuff in C#.
Readonly views:
I must admit I still prefer to make something immutable by default, only making it mutable if absolutely required.
Hidden functionality:
Generally scope has covered this one for me.
The major benefit of this is that it is a way of exposing your entity as a "read-only" version (as long as your interface does not expose setters of course).
We're doing quite a bit of unit testing and so often want to mock out things we're not testing. Although I don't like it, we've ended up using interfaces all over the place because it makes it a lot easier to mock things.
In theory most of the mocking frameworks can mock normal classes too, but in practice this has caused us issues because we sometimes do clever things with reflection and the type of the mocked class isn't the same as the original. So doing:
var myTask = MyIoCProvider.Get<Task>();
var taskType = typeof(myTask);
Was unpredictable. Whereas:
var myTask = MyIoCProvider.Get<ITask>();
var taskType = typeof(myTask);
Gives you as taskType that IS definitely derived from ITask.
So interfaces just give us a way of making our system more mockable.
If you were thinking in terms of using DomainEvents than data structures such as the task really do need to implement an interface
public interface IDomainEvent
{
Guid EventId { get; }
Guid TriggeredByEvent { get; }
DateTime Created { get; }
}
public class OrderCancelledEvent : IDomainEvent
{
Guid EventId { get; set; }
Guid TriggeredByEvent { get; set; }
DateTime Created { get; set; }
// And now for the specific bit
int OrderId { get; set; }
}
Or similarly if you have a common data access layer that may need to take in a standard base class of IEntity but I wouldn't have an interface for each type if it is just a data structure as you describe in your post.
When you are handling Domain Objects that actually expose behaviour you may then want to have an interface for unit testing.
I think some programmers just use interfaces, because they heard interfaces are good so they ended using them everywhere without thinking about actual pros and cons.
Me personally, I never use interfaces for entities that only represent a piece of data like db row for example.