OO Design - Exposing implementation details through an interface - c#

I have a class, which holds some details in a large data structure, accepts an algorithm to perform some calculations on it, has methods to validate inputs to the data structure.
But then I would like to return the data structure, so that it can be transformed into various output forms (string / C# DataTable / custom file output) by the View Model.
class MyProductsCollection {
private IDictionary<string, IDictionary<int, ISet<Period>>> products;
// ctors, verify input, add and run_algorithm methods
}
I know that you are supposed to use the "depend on interface not implementation" design principle, so I want to create an interface for the class.
How can I avoid writing the following interface?
Reason being it would expose implementation details and bind any other concrete implementations to return the same form.
interface IProductsCollection {
IDictionary<string, IDictionary<int, ISet<IPeriod>>> GetData();
// other methods
}
How can I easily iterate over the data structure to form different varieties of outputs without bluntly exposing it like this?
EDIT:
Since the class takes in IFunc<IDictionary<string, IDictionary<int, ISet<IPeriod>>>> in the constructor to iterate over the data structure and perform calculations, I could supply it with another IFunc, which would construct the output instead of running calculations. However, I don't know how I could do this aside from the concrete class constructor.

The structure of the IDictionary<string,IDictionary<int,ISet<Period>>> is very suspicious indeed - when you see a dictionary of dictionaries, good chances are that you have missed an opportunity or two to create a class to encapsulate the inner dictionary.
Without knowing much of the domain of your problem, I would suggest defining an interface to encapsulate the inner dictionary. It looks like something that associates a number to a set of periods, so you would define an interface like this:
interface IYearlyPeriods {
bool HasPeriodsForYear(int year);
ISet<Periond> GetPeriodsForYear(int year);
}
I have no idea what's in the periods, so you would need to choose a domain-specific name for the interface.
Moreover, you can wrap the next level of IDictionary too:
interface IProductDataSource {
IEnumerable<string> ProductNames { get; }
IYearlyPeriods GetProductData(string productName);
}
Now you can define an interface like this:
interface IProductsCollection {
IProductDataSource GetDataSource();
// other methods
}
The main idea is to use domain-specific interfaces in place of generic collections, so that the readers and implementers of your code would have some idea of what's inside without referring to the documentation.
You could go even further, and replace the IDictionary with the complex structure that you keep internally with an IDictionary of IProductPeriods implementation. If you would like to keep IYearlyPeriods that you expose to the users immutable, but would like to be able to make modifications yourself, you can make a mutable implementation, and keep it internal to the implementing class.

I would suggest to keep the IDictionary private and provide a simple IEnumerable in the interface.
In your case this could be a custom DTO that hides all the nastiness of the IDictionary<int, ISet<IPeriod>> - which is already quite complex and could (probably) easily change as you need to implement new features.
This could be something like:
class ExposedPeriod
{
public int PeriodIdentifier { get; set; }
public IEnumerable<IPeriod> Periods { get; set; }
}
The ExposedPeriod and PeriodIdentifier probably need better names though. Good names might be found in your domain vocabulary.

Related

Interface Segregation Framework and Pattern

I am writing an app that processes a bunch of ticker data from a page. The main class that I am working with is called Instrument, which is used to store all the relevant data pertaining to any instrument. The data is downloaded from a website, and parsed.
class Instrument
{
string Ticker {get; set;}
InstrumentType Type {get; set;}
DateTime LastUpdate {get; set;}
}
My issue is that I am not sure how to properly structure the classes that deal with the parsing of the data. Not only do I need to parse data to fill in many different fields (Tickers, InstrumentType, Timestamps etc.), but because the data is pulled from a variety of sources, there is no one standard pattern that will handle all of the parsing. There are even some parsing methods that need to make use of lower level parsing methods (situations where I regex parse the stock/type/timestamp from a string, and then need to individually parse the group matches).
My initial attempt was to create one big class ParsingHandler that contained a bunch of methods to deal with every particular parsing nuance, and add that as a field to the Instrument class, but I found that many times, as the project evolved, I was forced to either add methods, or add parameters to adapt the class for new unforeseen situations.
class ParsingHandler
{
string GetTicker(string haystack);
InstrumentType GetType(string haystack);
DateTime GetTimestamp(string haystack);
}
After trying to adapt a more interface-centric design methodology, I tried an alternate route and defined this interface:
interface IParser<outParam, inParam>
{
outParam Parse(inParam data);
}
And then using that interface I defined a bunch of parsing classes that deal with every particular parsing situation. For example:
class InstrumentTypeParser : IParser<InstrumentType, string>
{
InstrumentType Parse(string data);
}
class RegexMatchParser : IParser<Instrument, Match> where Instrument : class, new()
{
public RegexMatchParser(
IParser<string, string> tickerParser,
IParser<InstrumentType, string> instrumentParser,
IParser<DateTime, string> timestampParser)
{
// store into private fields
}
Instrument Parser(Match haystack)
{
var instrument = new Instrument();
//parse everything
return instrument;
}
}
This seems to work fine but I am now in a situation were it seems like I have a ton of implementations that I will need to pass into class constructors. It seems to be dangerously close to being incomprehensible. My thoughts on dealing with it are to now define enums and dictionaries that will house all the particular parsing implementations but I am worried that it is incorrect, or that I am heading down the wrong path in general with this fine-grained approach. Is my methodology too segmented? Would it be better to have one main parsing class with a ton of methods like I originally had? Are there alternative approaches for this particular type of situation?
I wouldn't agree with attempt to make the parser so general, as IParser<TOut, TIn>. I mean, something like InstrumentParser looks to be quite sufficient to deal with instruments.
Anyway, as you are parsing different things, like dates from Match objects and similar, then you can apply one interesting technique that deals with generic arguments. Namely, you probably want to have no generic arguments in cases when you know what you are parsing (like string to Instrument - why generics there?). In that case you can define special interfaces and/or classes with reduced generic arguments list:
interface IStringParser<T>: IParser<T, string> { }
You will probably parse data from strings anyway. In that case, you can provide a general-purpose class which parses from Match objects:
class RegexParser: IStringParser<T>
{
Regex regex;
IParser<T, Match> parser;
public RegexParser(Regex regex, IParser<T, Match> containedParser)
{
this.regex = regex;
this.parser = containedParser;
}
...
T Parse(string data)
{
return parser.Parse(regex.Match(data));
}
}
By repeatedly applying this technique, you can make your top-most consuming classes only depend on non-generic interfaces or interfaces with one generic member. Intermediate classes would wrap around more complicated (and more specific) implementations and it all becomes just a configuration issue.
The goal is always to go towards as simple consuming class as possible. Therefore, try to wrap specifics and hide them away from the consumer.

Passing Property Classes to Plugin Infrastructure

I have the following problem on which I need some advice.
I have a configuration that has a large number of plugin defined by a standard IPlugin interface struture.
Each of these interfaces needs access to a large number of external classes which define properties of many
custom types.further these classes are inhereted from many base clases.
The issue here is one of design on how to present these property classes to each of the plugins in
order to fully access these structures.
To expand a little some classes have multiple lists, for sake of discussion up to 50 lists each having sub items
of 30 to 60 various propeties.
Now I can of course move all the property clases to the interface class as dependents, but as most of these clases
are inherted it becomes a horible solution. passing as ref object also does not appear to be a workable solution.
I have not included any speific code as I dont think it would help but here is a little psudo version of what I need to
achieve.
public interface IPlugin
{
ResultsList PluginProcess(Class1 L1, Class2 L2, ...);
}
class(n) may be
public class Class1 : SomeOtherClass
{
public object1 obj1 {get; set; }
...
public object50 obj50 { get; set;}
}
and mainly consists of other derived objects.
Within the plugins I need to be able to use code such as
L1.classes.data[0].codec[2].enabled = true;
and
L2 newclass2 = new L2();
newclass2.nnnn ...
ResultsList.classes.Add(newclass2);
Finaly I need to use a Plugin architecture in order for third partys to supply custom processing of the data.
Any constructive suggestions welcome.
I would consider an interface based around a Dictionary<string, object>.
Into that Dictionary add all of your classes with useful identifiers.
dictionary["Class1"] = new Class1(...);
dictionary["Class2"] = new Class2(...);
Then pass the Dictionary into your interface.
ResultsList PluginProcess(Dictionary<string, object> context);
This will allow you provide arbitrary data to your consumers. You can use API documentation to describe which Key to use to get each class. This allows you flexibility to grow the interface input over time.
Its probably worth taking this a step further and having a special class for the plugin context.
class Context
{
public Dictionary<string, object> Values;
...
}
You can then pass the Context object into your interface.
ResultsList PluginProcess(Context context);
This gives you a lot of flexibility to grow the interface inputs over time. You can also provide additional functions and data on the Context to assist your consumers.

Factory pattern with objects that have many optional properties

I'm refactoring a class that represents the data in some XML. Currently, the class loads the XML itself and property implementations parse the XML every time. I'd like to factor out the XML logic and use a factory to create these objects. But there are several 'optional' properties and I'm struggling to find an elegant way to handle this.
Let's say the XML looks like this:
<data>
<foo>a</foo>
<bar>b</bar>
</data>
Assume both foo and bar are optional. The class implementation looks something like this:
interface IOptionalFoo
{
public bool HasFoo();
public string Foo { get; }
}
// Assume IOptionalBar is similar
public class Data : IOptionalFoo, IOptionalBar
{
// ...
}
(Don't ask me why there's a mix of methods and properties for it. I didn't design that interface and it's not changing.)
So I've got a factory and it looks something like this:
class DataFactory
{
public static Data Create(string xml)
{
var dataXml = new DataXml(xml);
if (dataXml.HasFoo())
{
// ???
}
// Create and return the object based on the data that was gathered
}
}
This is where I can't seem to settle on an elegant solution. I've done some searching and found some solutions I don't like. Suppose I leave out all of the optional properties from the constructor:
I can implement Foo and Bar as read/write on Data. This satisfies the interface but I don't like it from a design standpoint. The properties are meant to be immutable and this fudges that.
I could provide SetFoo() and SetBar() methods in Data. This is just putting lipstick on the last method.
I could use the internal access specifier; for the most part I don't believe this class is being used outside of its assembly so again it's just a different way to do the first technique.
The only other solution I can think of involves adding some methods to the data class:
class Data : IOptionalFoo, IOptionalBar
{
public static Data WithFoo(Data input, string foo)
{
input.Foo = foo;
return input;
}
}
If I do that, the setter on Foo can be private and that makes me happier. But I don't really like littering the data object with a lot of creation methods, either. There's a LOT of optional properties. I've thought about making some kind of DataInitialization object with a get/set API of nullable versions for each property, but so many of the properties are optional it'd end up more like the object I am refactoring becomes a facade over a read/write version. Maybe that's the best solution: an internal read/write version of the class.
Have I enumerated the options? Do I need to quit being so picky and settle on one of the techniques above? Or is there some other solution I haven't thought of?
You can think of such keywords as virtual/castle dynamic proxy/reflection/T4 scripts - each one can solve the problem on a slightly different angle.
On another note, this seems perfectably reasonable, unless I misunderstood you:
private void CopyFrom(DataXml dataXml) // in Data class
{
if (dataXml.HasFoo()) Foo = dataXml.Foo;
//etc
}
What I did:
I created a new class that represented a read/write interface for all of the properties. Now the constructor of the Data class takes an instance of that type via the constructor and wraps the read/write properties with read-only versions. It was a little tedious, but wasn't as bad as I thought.

Generic Interface w/ Polymorphism to handle Objects

Previous Post removed; Updated:
So I have a unique issue, which is possibly fairly common though. Properties are quite possibly are most commonly used code; as it requires our data to keep a constant value storage. So I thought how could I implement this; then I thought about how easy Generics can make life. Unfortunately we can't just use a Property in a Generic without some heavy legwork. So here was my solution / problem; as I'm not sure it is the best method- That is why I was seeking review from my peers.
Keep in mind the application will be massive; this is a very simple example.
Abstract:
Presentation Layer: The interface will have a series of fields; or even data to go across the wire through a web-service to our database.
// Interface:
public interface IHolder<T>
{
void objDetail(List<T> obj);
}
So my initial thought was an interface that will allow me to Generically handle each one of my objects.
// User Interface:
public class UI : IHolder
{
void objDetail(List<object> obj)
{
// Create an Instance
List<object> l = new List<object>();
// Add UI Fields:
l.Add(Guid.NewGuid());
l.Add(txtFirst.Text);
l.Add(txtLast.Text);
// l to our obj
obj = l;
return;
}
}
Now I have an interface; which has been used by our UI to put information in. Now; this is where the root of my curiosity has been thrown into the mixture.
// Create an Object Class
public class Customer : IHolder
{
// Member Variable:
private Guid _Id;
private String _First;
private String _Last;
public Guid Id
{
get { return _Id; }
set { _Id = value; }
}
public String First
{
get { return _First; }
set { _First = value; }
}
public String Last
{
get { return _Last; }
set { _Last = value; }
}
public virtual objDetail(List<Customer> obj)
{
// Enumerate through List; and assign to Properties.
}
}
Now this is where I thought it would be cool; if I could use Polymorphism to use the same interface; but Override it to do the method differently. So the Interface utilizes a Generic; with the ability to Morph to our given Object Class.
Now our Object Classes; can move toward our Entity interface which will handle basic Crud Operation.
I know this example isn't the best for my intention; as you really don't need to use Polymorphism. But, this is the overall idea / goal...
Interface to Store Presentation Layer UI Field Value
Implement the Properties to a Desired Class
Create a Wrapper Around my Class; which can be Polymorphed.
Morphed to a Generic for Crud Operation
Am I on the right path; is this taboo? Should I not do this? My application needs to hold each instance; but I need the flexibility to adapt very quickly without breaking every single instance in the process. That was how I thought I could solve the issue. Any thoughts? Suggestions? Am I missing a concept here? Or am I over-thinking? Did I miss the boat and implement my idea completely wrong? That is where I'm lost...
After pondering on this scenario a bit, I thought what would provide that flexibility while still ensuring the code is optimized for modification and business. I'm not sure this is the right solution, but it appears to work. Not only does it work, it works nicely. It appears to be fairly robust.
When is this approach useful? Well, when you intend to decouple your User Interface from your Logic. I'll gradually build each aspect so you can see the entire structure.
public interface IObjContainer<T>
{
void container(List<T> object);
}
This particular structure will be important. As it will store all of the desired content into it.
So to start you would create a Form with a series of Fields.
Personal Information
Address Information
Payment Information
Order Information
So as you can see all of these can be separate Database Tables, but belong to a similar Entity Model you are manipulating. This is quite common.
So a Segregation Of Concern will start to show slightly, the fields will be manipulated and passed through an Interface.
public interface IPersonalInformation
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
So essentially the Interface is passing its variable, to the Interface. So you would culminate an interface to handle that entire form or individual interfaces that you wish to call so that they remain reusable.
So now you have a series of Interfaces, or a single once. But it contains all these variables to use. So you would now create a class:
public class CustomerProperties: IPersonalInformation, IOrderInformation
{
// Implement each Interface Property
}
Now you've created a container that will hold all of your values. What is nifty about this container is you can reuse the same values for another class in your application or choose different ones. But it will logically separate the User Interface.
So essentially this is acting similar to a Repository.
Now you can take these values and perform the desired logic. What becomes wonderful now, is after you've performed your logic you pass the object into our Generic List. Then you simply implement that method in another class for your goal and iterate through your list.
The honesty is it appears to work well and decouple nicely. I feel that it was a lot of work to do something similar to a normal Repository and Unit Of Work, this answers the question but weather or not it is ideal for your project I would look into Repository, Unit Of Work, Segregation Of Concern, Inversion Of Control, and Dependency Injection. They may do this same approach cleaner.
Update:
I thought about it after I wrote this up, I noticed you could actually implement those property values into the Generic List structure bypassing a series of interfaces; but that would introduce consistency issues as you'd have to be aware of what data is being passed in each time, in order. It's possible, but may not be ideal.

Workaround or alternative to no static methods on an interface

I'm implementing some naive searching in my application, and searches will take place on a couple of different object types (Customer, Appointment, Activity, etc.). I'm trying to create an interface that will have types that are searchable. What I'd like to do is something like this:
public interface ISearchable
{
// Contains the 'at a glance' info from this object
// to show in the search results UI
string SearchDisplay { get; }
// Constructs the various ORM Criteria objects for searching the through
// the numerous fields on the object, excluding ones we don't want values
// from then calls that against the ORM and returns the results
static IEnumerable<ISearchable> Search(string searchFor);
}
I already have a concrete implementation of this on one of my domain model objects, but I'd like to extend it to others.
The problem is obvious: you can't have static methods on an interface. Is there another prescribed method to accomplish what I'm looking for, or is there a workaround?
Interfaces really specify the behavior of an object, not a class. In this case, I think one solution is to separate this into two interfaces:
public interface ISearchDisplayable
{
// Contains the 'at a glance' info from this object
// to show in the search results UI
string SearchDisplay { get; }
}
and
public interface ISearchProvider
{
// Constructs the various ORM Criteria objects for searching the through
// the numerous fields on the object, excluding ones we don't want values
// from then calls that against the ORM and returns the results
IEnumerable<ISearchDisplayable> Search(string searchFor);
}
An instance of ISearchProvider is an object that does the actual searching, while an ISearchDisplayable object knows how to display itself on a search result screen.
I don't really know the solution for C#, but according to this question, Java seems to have the same problem and the solution is just to use a singleton object.
It looks like you will need at least one other class, but ideally you would not need a separate class for each ISearchable. This limits you to one implementation of Search(); ISearchable would have to be written to accommodate that.
public class Searcher<T> where T : ISearchable
{
IEnumerable<T> Search(string searchFor);
}

Categories