Working with different objects that inherit interface - c#

I've been working on learning how to use interfaces correctly in c# and I think I mostly understand how they should be used but still feel confused about certain things.
I want to create a program that will create a CSV from Sales Orders or Invoices. Since they are both very similar I figured I could create an IDocument interface that could be used to make a CSV document.
class Invoice : IDocument
{
public Address billingAddress { get; set; }
public Address shippingAddress { get; set; }
public Customer customer { get; set; }
public List<DocumentLine> lines { get; set; }
// other class specific info for invoice goes here
}
I can create a method CreateCSV(IDocument) but how would I deal with the few fields that differ from Sales Orders and Invoices? Is this a bad use of interfaces?

You don't inherit interfaces, you implement them; and in this case the interface is an abstraction; it says "all things that implement this interface have the following common characteristics (properties, methods, etc)"
In your case, you have found that in fact Invoices and Sales Orders don't quite share the exact same characteristics.
Therefore from the point of view of representing them in CSV format, it's not a great abstraction (although for other things, like calculating the value of the document, it's an excellent one)
There are a number of ways you can work around this though, here are two (of many)
Delegate the work to the classes
You can declare an ICanDoCSVToo interface that returns the document in some kind of structure that represents CSV (let's say a CSVFormat class that wraps a collection of Fields and Values).
Then you can implement this on both Invoices and Sales Orders, specifically for those use cases, and when you want to turn either of them into CSV format, you pass them by the ICanDoCSVToo interface.
However I personally don't like that as you don't really want your Business Logic mixed up with your export/formatting logic - that's a violation of the SRP. Note you can achieve the same effect with abstract classes but ultimately it's the same concept - you allow someone to tell the class that knows about itself, to do the work.
Delegate the work to specialised objects via a factory
You can also create a Factory class - let's say a CSVFormatterFactory, which given an IDocument object figures out which formatter to return - here is a simple example
public class CSVFormatterLibrary
{
public ICSVFormatter GetFormatter(IDocument document)
{
//we've added DocType to IDocument to identify the document type.
if(document.DocType==DocumentTypes.Invoice)
{
return new InvoiceCSVFormatter(document);
}
if (document.DocType==DocumentTypes.SalesOrders)
{
return new SalesOrderCSVFormatter(document);
}
//And so on
}
}
In reality, you'd might make this generic and use an IOC library to worry about which concrete implementation you would return, but it's the same concept.
The individual formatters themselves can then cast the IDocument to the correct concrete type, and then do whatever is specifically required to produce a CSV representation of that specialised type.
There are other ways to handle this as well, but the factory option is reasonably simple and should get you up and running whilst you consider the other options.

Related

Using interfaces in models with SQLite

Let's say I have an interface like this:
public interface IUser
{
int Id { get; }
string Name { get; }
List<IMonthlyBudget> MonthlyBudget { get; }
}
and then I have a model that implements this:
public class User : IUser
{
public int Id { get; set; }
public string Name { get; set; }
public List<IMonthlyBudget> MonthlyBudget { get; set; }
}
and here I have the IMonthlyBudget:
public interface IMonthlyBudget
{
int Id { get; }
float MonthlyMax { get; }
float CurrentSpending { get; }
float MonthlyIncome { get; }
}
Now I have my models. But the issue comes with using SQLite. SQLite can't understand what is the real implementation of IMonthlyBudget. I understand why, but I really don't want remove the interface and expose the real implementation to all the clients that use these models. In my project structure I have a Core project that has all the model interfaces, and the model implementation are in a data access project.
Is there something wrong with how I'm approaching this problem? I assume i'm not the first one to run into a issue like this. Isn't it completely normal practice to keep model interfaces (what repositories etc then use as their return types, parameters and stuff like that) and implement the actual concrete models in a data access project?
And can someone explain why I can't do this:
public class User : IUser
{
public int Id { get; set; }
public string Name { get; set; }
public List<MonthlyBudget> MonthlyBudget { get; set; }
}
MonthlyBudget implements IMonthlyBudget, shouldn't it be completely fine to use the concrete model as the type instead of the the interface when the concrete model actually implements the interface?
A few questions here, so I'll break it down into sections:
Use of Interfaces
It is definitely good practice to interface classes that perform operations. For example, you may have a data service (i.e. data access layer) interface that allows you to do operations to read and modify data in your persistent store. However, you may have several implementations of that data service. One implementation may save to the file system, another to a DBMS, another is a mock for unit testing, etc.
However, in many cases you do not need to interface your model classes. If you're using an anemic business object approach (as opposed to rich business objects), then model classes in general should just be containers for data, or Plain Old CLR Objects (POCO). Meaning these objects don't have any real functionality to speak of and they don't reference any special libraries or classes. The only "functionality" I would put in a POCO is one that is dependent only upon itself. For example, if you have a User object that has a FirstName and LastName property, you could create a read-only property called FullName that returns a concatenation of the two.
POCOs are agnostic as to how they are populated and therefore can be utilized in any implementation of your data service.
This should be your default direction when using an anemic business object approach, but there is at least one exception I can think of where you may want to interface your models. You may want to support for example a SQLite data service, and a Realm (NoSQL) data service. Realm objects happen to require your models to derive from RealmObject. So, if you wanted to switch your data access layer between SQLite and Realm then you would have to interface your models as you are doing. I'm just using Realm as an example, but this would also hold true if you wanted to utilize your models across other platforms, like creating an observable base class in a UWP app for example.
The key litmus test to determining whether you should create interfaces for your models is to ask yourself this question:
"Will I need to consume these models in various consumers and will those consumers require me to define a specific base class for my models to work properly in those consumers?"
If the answer to this is "yes", then you should make interfaces for your models. If the answer is "no", then creating model interfaces is extraneous work and you can forego it and let your data service implementations deal with the specifics of their underlying data stores.
SQLite Issue
Whether you continue to use model interfaces or not, you should still have a data access implementation for SQLite which knows that it's dealing with SQLite-specific models and then you can do all your CRUD operations directly on those specific implementations of your model. Then since you're referring to a specific model implementation, SQLite should work as usual.
Type Compatibility
To answer your final question the type system does not see this...
List<IMonthlyBudget> MonthlyBudget
as being type-compatible with this...
List<MonthlyBudget> MonthlyBudget
In our minds it seems like if I have a list of apples, then it should be type-compatible with a list of fruit. The compiler sees an apple as a type of fruit, but not a list of apples as a type of a list of fruit. So you can't cast between them like this...
List<IMonthlyBudget> myMonthlyBudget = (List<IMonthlyBudget>) new List<MonthlyBudget>();
but you CAN add a MonthlyBudget object to a list of IMonthlyBudget objects like this...
List<IMonthlyBudget> myMonthlyBudget = new List<IMonthlyBudget>();
myMonthlyBudget.Add(new MonthlyBudget());
Also you can use the LINQ .Cast() method if you want to cast an entire list at once.
The reason behind this has to do with type variance. There's a good article on it here that can shed some light as to why:
Covariance and Contravariance
I hope that helps! :-)

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.

OO Design - Exposing implementation details through an interface

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.

Huge object in web application

I am writing web application and I have huge class that have more then 40 members, 3 types of arrays and have many methods.
This class represents a task with all task's ingrediants including pricing of task.
The problem is that I need to pass the client list of 40 first tasks therefore I pass 40 complete task items which turns to be very big and weight a lot of KB.
How can I reduce this object??..
Here is a pic of the class diagram:
http://www.imagehousing.com/image/624350
The first thing I would tackle before even thinking of sending anything is that you refactor that class into more manageable subcomponents. Take for instance properties like DeliveryNote, DeliveryNoteId, DeliveryNoteSerial could be housed in a Delivery class. The same could be said for the Group, Payback and other similarly named properties. When designing properties of a class, you need to ask yourself whether the properties are specific to the parent model, or are specific to a smaller problem domain.
Once you've refactored that class, you then need to determine what data the client needs. Do they need every article of data in that class. If not, why not produce a view class based on what the client needs and send only that.
If you don't think a partial view is appropriate for your data, you can use DataContractAttribute and DataMemberAttribute attributes to control which parts of your model actually represent the data contract to be passed to the client. E.g.:
[DataContract]
public class Task
{
[DataMember]
public string PropertyA { get; set; }
[DataMember]
public string PropertyB { get; set; }
public string PropertyC { get; set; }
}
In the above example, using these attributes I can enforce that PropertyA and PropertyB form component parts of the data contract. PropertyC will not be part of the contract, so will not be serialised. This is of course dependent using the DataContractSerializer or a WCF-service (which uses that serialiser).
This also limits a single-data contract view of the model.
In first glance, I think you need to reduce/simplify your class, that 40 members ain't really necessary to be direct members, e.g.:
Discount, DiscountTypeCode, DiscountTypeId, DiscountTypeSign can all becomes a class ->
class Discount {
float rate;
int typeCode, typeId;
string sign;
}
Simpily group every member with same prefix to a class. This is needed not only to trim the size, but better maintenance. To reduce size, it's up to you whether you need to include those sub objects to send to the client, since it's a web application, I don't think everytime your client need everything in the object, so while you return your object, consider return just a partial of it, create that in another view model.
I think you have you to follow some basic rule.
Having big class create problem to understand the code and maintain it.
List down all the nouns and Verbs
Group common nouns and related verbs and create a class
Repeat same procedure untill there is no noun and verbs remain.
Now you to give serious thought to created classes and their methods
a. Findout Generic and Specialise Classes
b. If there is need of design pattern then think about and create relationship like
Generalisation and Specialisation, Association, Dependency and realization
The above step will automatic give better shape to classe.

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