I'm worried I'm adding too many interfaces - c#

I am building out my domain model and continuing to refactor it. As I do, I am finding that I like interfaces as it allows me to create reusable methods/controllers/views for concrete types based on their interfaces. However, I am finding that I am creating an interface every time I add a new property to one of my domain entities.
For example, I have a MemberStatus object which inherits from an abstract Entity object which in turn implements the IIdentifiableEntity interface meaning that it has an Id property. MemberStatus also implements the INamedEntity interface meaning that it has a Name property, the IOrderedEntity interface meaning that it has a DisplayOrder property and the IHasMembers interface meaning that it has a collection Member objects. Here's the code:
public class MemberStatus : Entity, INamedEntity, IOrderedEntity, IHasMembers
{
public string Name { get; set; }
public float DisplayOrder { get; set; }
public ICollection<Member> Members { get; set; }
}
public abstract class Entity : IIdentifiableEntity
{
public int Id { get; set; }
}
public interface IIdentifiableEntity
{
int Id { get; set; }
}
public interface INamedEntity
{
string Name { get; set; }
}
public interface IOrderedEntity
{
float DisplayOrder { get; set; }
}
public interface IHasMembers
{
ICollection<Member> Members { get; set; }
}
Now, this seems to work fine as I other similar objects such as MemberPosition and MemberTeam which all implement these same interfaces and I can use my repository methods and controller actions with generics that implement these interfaces and have a lot of code reuse.
However, my concern is whether or not it's appropriate to keep adding simple, one-property interfaces every time I add a new property to my concrete objects. For example, let's say I want to add a bool Enabled property... should I continue to create a IEnabled interface? The reason I'm asking is that some of controller "initializers" that are using generics are becoming very long as shown in the following line of code. Is this normal and best-practice?
public abstract class OrderedCrudController<TEntity> : CrudController<TEntity> where TEntity : Entity, INamedEntity, IOrderedEntity, IHasMembers, new()

The fact that you are using interfaces is a good thing. However, you should ask yourself, if I create an IEnabled interface, will I ever reference my class by that interface alone? i.e. will there be contexts where I interact with my class purely via the single property that interface exposes?
Also, can you consider contexts where you will interact with multiple implementation of this IEnabled interface?
If the answer to both of these question is "no", then the interface serves very little purpose.
Having said that, please don't worry too much about this! it does very little harm.

Don't create interfaces that you don't foresee an imminent need for. Observe the YAGNI (you ain't gonna need it) principle. Otherwise you'll wind up with needlessly complicated code.

I think your problem is that you are trying to shoe-horn your domain model into whatever gui that you're displaying data in.
Instead, consider your domain object things that have behaviour close to data and in its c'tor, give it an Action<DomainEvent>. Now, make sure that you ONLY EVER pass data OUT from a domain object through this action.
Now, you listen. Whenever you actually want to make a change to your domain, call a method on it. Let your GUI be updated through the Action<DomainEvent> by taking these events and saving them to whatever read model that you are interested in.
Have a look at http://www.infoq.com/presentations/ddd-eric-evans and consider his points about domain events.
Now you don't have to add strange interfaces related to a technical domain into your business domain anymore. And remember; if you are doing CRUD like your examples show, then you are NOT doing domain driven design. You have an anemic domain.
Final point: use interfaces for things that actually need to be interchangeable. Are you carrying around a lot of INamed things in your application that can be interchanged with one another?
Let me also link this, for you to consider:
http://lostechies.com/jimmybogard/2011/10/11/event-sourcing-as-a-strategic-advantage/
http://lostechies.com/jimmybogard/2010/04/08/strengthening-your-domain-domain-events/

Related

What is the practical usage of interface not directly implemented in class?

I think I have a very naive question here that I didn't knew before that it was even possible. Forgive me if my title question is a bit vague because I don't even know how to describe it. Here is the code that looks weird to me.
public interface IMyInterface
{
void ImplementMe();
}
public class StandAlone
{
public void ImplementMe()
{
Console.writeline("It works!");
}
}
public class SubClass : StandAlone, IMyInterface
{
// no need to implement IMyInterface here but it still work!!!
}
IMyInterface myInterface = new SubClass();
myInterface.ImplementMe(); // Output : "It works!"
I just want to know the following :
What is the right term to describe this approach?
What is the practical benefit of this kind of approach?
What kind of problem it tries to solve? or What scenario this will be applicable?
Well, first case that comes to my mind - when you don't own source code of StandAlone class, but later you decided to introduce interface which describes behavior of StandAlone class. E.g. for unit-testing (it's not best practice to mock code which you don't own, but sometimes it might be helpful) or you want to provide alternative implementation of StandAlone behavior in some cases. So either you have no options for unit-testing such code:
public class SUT
{
private readonly StandAlone dependency;
public SUT(StandAlone dependency)
{
this.dependency = dependency;
}
// ...
}
But if you'll introduce interface, you can actually switch to dependency from IMyInterface instead of StandAlone. And provide SubClass as implementation of interface with zero efforts.
public class SUT
{
private readonly IMyInterface dependency;
public SUT(IMyInterface dependency)
{
this.dependency = dependency;
}
// ...
}
But SubClass does implement the IMyInterface - it has all the required public members with the right signatures. There's no specific terminology since there's nothing weird about it.
In fact, some languages take this even further, and allow you to cast any object to an interface, as long as the class has the right members (and in yet more flexible languages, even if it doesn't).
The main benefit is again the same as any other way to use interfaces - it allows you to abstract the implementation away from the interface. It's just a shortcut to having to do an explicit interface implementation, something like:
class SubClass : BaseClass, IInterface
{
void IInterface.MyMethod()
{
base.MyMethod();
}
}
You might think that you could just implement the interface in the base class, but there's plenty of reasons why you wouldn't:
You don't want to maintain a public interface for the base class, it's just an internal class that shouldn't be exposed outside.
You don't have a way to change the base class to include the interface, so if you want to keep an inheritance chain, you must subclass and add the interface to the subclass.
The inferface contains some members that aren't contained in the BaseClass.
You'll probably find a couple more reasons if you try.
But the main point is: why not? You need a reason to do something (expand the definition of the base class instead of just the subclass). Adding abstraction everywhere along your codebase is rarely beneficial - you're trying to find a good trade-off between clarity of intent and clarity of implementation. An interface on a base class might help or hinder that.
One legitimate use of this pattern (Outside of simply the original programmer should have put the interface on the base class) could be that Standalone is in a 3rd party (or inaccessible) assembly, and IMyInterface was written in your own code to provide a Facade.
Consider this;
Your app wants to provide some functionality. You define an interface with method ImplementMe.
Standalone is in ThirdParty.dll and provides this exact method name (Perhaps you modelled your interface on that method name on purpose)
You subclass Standalone within your own code in order to implement your functionality.
Maybe you have a second way of implementing ImplementMe for which you have your onw class implementing your own interface. (public class MyOwnImplemetation : IMyInterface {... })
You could then use DI to instantiate the correct implementation of StandAlone or MyOwnImplemetation but treat them both as IMyInterface.
Not all classes are direct implementations of interfaces.
For example, let's put a good sample based on a simple class inheritance:
public class Person
{
public Guid Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
public class Employee : Person
{
}
Now, let's imagine that we need to store uniquely-identifiable objects in some common store where we don't care about the entities' types but just about they're uniquely-identifiable.
BTW, we consider that persons shouldn't be stored within such store, because they're not valid entities within our organization but they're just there to improve code reusability and don't repeat ourselves.
So we define an interface like this:
public interface ICanBeUniquelyIdentifiable
{
Guid Id { get; set; }
}
...and we don't implement it on Person but we do so on Employee:
// Now an employee is an actual object that can be uniquely identifiable,
// and this isn't true because Person has an Id property, but because
// Employee fulfills the contract!
public class Employee : Person, ICanBeUniquelyIdentifiable
{
}
Background
I would say that your reasoning should be that you implement interfaces where they really matter to be implemented, and reusability shouldn't be the key point when implementing interfaces.
Actually, you should implement interfaces on objects which should be accepted on some API and you just need a subset of the full type of a given object.

What's the use of interfaces if I have to implement all the members elsewhere anyway? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I can declare functions and properties in an interface, but I cannot implement them. When I inherit from the interface, I now have to implement all these members in my class. If I have to do that, what's the point of declaring the interface at all?
For example, here's an example interface:
namespace InterfaceExample
{
public interface IVehicle
{
int Doors { get; set; }
int Wheels { get; set; }
Color VehicleColor { get; set; }
int TopSpeed { get; set; }
int Cylinders { get; set; }
int CurrentSpeed { get; }
string DisplayTopSpeed();
void Accelerate(int step);
}
}
I've declared all the properties and functions in this interface. Now, when I use this interface in my class like this:
namespace InterfaceExample
{
public class Motorcycle : IVehicle
{
private int _currentSpeed = 0;
public int Doors { get; set; }
public int Wheels { get; set; }
public Color VehicleColor { get; set; }
public int TopSpeed { get; set; }
public int HorsePower { get; set; }
public int Cylinders { get; set; }
public int CurrentSpeed
{
get { return _currentSpeed; }
}
public Motorcycle(int doors, int wheels, Color color, int topSpeed, int horsePower, int cylinders, int currentSpeed)
{
this.Doors = doors;
this.Wheels = wheels;
this.VehicleColor = color;
this.TopSpeed = topSpeed;
this.HorsePower = horsePower;
this.Cylinders = cylinders;
this._currentSpeed = currentSpeed;
}
public string DisplayTopSpeed()
{
return "Top speed is: " + this.TopSpeed;
}
public void Accelerate(int step)
{
this._currentSpeed += step;
}
}
I have to declare all the properties again.
So why bother at all with the interface in the first place? It seems like a waste of time, since I will be implementing all the members in my class anyhow.
As other answers emphasize interfaces tell you what to do and how to do is up to you to implement.
1. Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Ok. You are creating a Motorcycle and by implementing the interface IVehicle, the MotorCycle class is forced to implement all the members of the interface IVehicle.
If you had not used an interface called IVehicle, you might actually forget to implement something that you should have been implemented.
Tomorrow, if somebody wants to build a Car then you can implement from IVehicle, people can implement all its methods and customize.
The purpose of the IVehicle interface is to make sure that whenever you build a vehicle class, it reminds and forces you to make sure that you rightly build a vehicle
2. For Properties, interface is a waste of time ?
No and definitely not.
For example, whenever you want to return the vehicle speed, instead of just rounding of the vehicle speed to integer you want in exact floating point,
10 // public float currentSpeed { get; set; }
10.5 // public float currentSpeed { get {return {//write custom logic}; set; }
Notice the customisation in Get accessor of the property.
3. When should abstract class be used ?
Abstract class should be used when all derived class would be using some repeated method. For example,
public abstract Class AbstractClass
{
public virtual int Doors { get; set; }
public virtual int Wheels { get; set; }
public virtual Color VehicleColor { get; set; }
public virtual int TopSpeed { get; set; }
public virtual int HorsePower { get; set; }
public virtual int Cylinders { get; set; }
public string WhatSideDriving
{
if (Country == "US") return "Keep Right";
if (Country == "India") return "Keep Left";
}
}
Do note that the method WhatSideDriving is already implemented and can be used by all the classes that derive from this class. However other members can be overridden and can be implemented according to the required functionality.
Then why I waste my time in create a Interface If I have to declare all the properties and functions of My Interface in my class.
Because an interface is just that; a (public) interface. It does not define an implementation, only the methods and properties used to interface to any of its implementations.
Of course, implementors of said interface must define the implementation of it. How else would you expect this to work?
That said, it's not inconceivable that properties could be implicitly (and invisibly) implemented as automatic properties, but that doesn't work for methods, and you often need more than get; set; anyway, so it would provide little benefit (i.e., a feature that isn't worth the effort).
Strictly speaking, declaring an interface is a waste of time. You could skip the interface and save some time.
However, you would be cutting the wrong corner. While it's a bit of extra time and work, in the long run interfaces are invaluable. One of the marks of a truly great software engineer is being able to design interfaces well.
To be less abstract, the interface is designed for precisely that purpose: To formalize the interface between two kinds of classes (in other words, how the two classes work together). It is a bit like a contract between classes, where each class says what they promise to provide and what they will expect. Your IVehicle example, for instance, vows that it will always have a property called doors. Then, any code which works with IVehicle can trust all implementations of IVehicle to always have a Doors. You can now safely write code which accesses IVehicle.Doors knowing that no matter what particular implementation happens to get passed to this method, your code will definitely work - even if the Vehicles package developer decides to one day add some vehicles you've never heard about or considered!
When you have only one small class implementing the interface, and you are the only developer, interfaces may be superfluous. However, what if there were multiple kinds of vehicles, each with their own logic and different members, which must nevertheless be used by some general code? For example, a vehicle tracking manager must handle classes Car, Truck, Plane and so on. Why not? They all have a speed and position, and that's all that matters.
Moreover, when you let other developers write their own vehicles, the interface is a great way of showing them how they must do this for it to work with the rest of your code.
Likewise, when you work on a large project, and split each part between different developers, well-designed interfaces can ensure that these programmers, working on different parts of the project in relative isolation, will still create a whole which works thanks to parts that fit together nicely.
Similarly, a good interface is a great way to start a complicated class even when coding on your own: It will help you keep track of what you need to implement and how, but unlike a more familiar technical specification, an interface can be understood by the compiler so that it can assist you in many ways (such as help from IntelliSense when you want to write logic using parts of your class that you will implement later).
In C# particularly, interfaces also have a practical benefit. You can't inherit from more than one class or abstract class in C# (unlike C++). This is done because multiple inheritance turns out to make life very difficult for programmers sometimes. But you can inherit from multiple interfaces, and because they are only interfaces (with no implementation) the "multiple inheritance" thing is much less of an issue.
Lastly, a real world example: Microsoft has provided for you a List.Sort method which will helpfully sort a list of any object. It is obviously easy to do this for things like numbers and strings, but it is possible to make it sort arbitrary objects you made, like vehicles. But how could Microsoft possibly know what kinds of classes you will implement, and how you intend for these to be sorted? They don't, but they provide for you an interface called IComparable. This defines the methods that sorting code needs to call to be able to compare two objects for sorting. If the object you put into your list implements this IComparable, you will have told Microsoft's List.Sort code how your objects should be sorted, and now you no longer have to write your own sort function since you can just use the well designed, tested, documented and debugged Microsoft one.
As an exercise, try writing a program which takes a list of Triangle classes (which have only a, b, c fields that store the length of each side, and a CalculateArea method) and then sorts it by area using Microsoft's List.Sort. Don't write your own sorting code, and don't use thing like LINQ OrderBy, instead do it by making Triangle implement IComparable. Then think about this: If you were the project manager in charge of development of all the .NET libraries, how would you write a sort function that anyone can use, even with their own weird classes?
You create an interface if you need to create an interface.
You can pass all types of vehicles as the interface type to methods. If you declare all three of the following and you need to calculate their fuel efficiency, you would need three separate methods that do that.
example:
public class Truck {}
public class Car {}
public class Motorcycle {}
With an interface you need one method:
public int GetFuelEfficiency(IVehicle vehicle)
The interface requires you or anyone else implementing it to declare ALL of its properties and methods. This way all classes implementing the interface will contain all the necessary properties and methods to be treated by other code in the same manner regardless of the classes specific implementations.
There are yet other reasons for declaring an interface like the lack of multiple inheritance in C#, etc.
Interfaces are definitions, and not implementations. Classes are both implementations and definitions.
The point of an interface is to separate implementation from definition, so that that the consumer does not have any knowledge of the actual object used to implement the interface.
Yes, it's more work, but good design is always more work than bad.
Interface provides a blueprint for implementation. You have the freedom to create the actual class from that blueprint. To be able to do so, you have to define all the aspects of that blueprint.
Interface is mostly used to create pluggable interfaces to applications and are also used to support multiple inheritance.
References:
Code Project
DZone
MSDN - Interfaces - C# Programming Guide
MSDN - When to use Interfaces
You may also use Abstract classes if it suits your purpose. But Abstract class != Interface.

Is there a way to restrict access to a public method to only a specific class in C#?

I have a class A with a public method in C#. I want to allow access to this method to only class B. Is this possible?
UPDATE:
This is what i'd like to do:
public class Category
{
public int NumberOfInactiveProducts {get;}
public IList<Product> Products {get;set;}
public void ProcessInactiveProduct()
{
// do things...
NumberOfInactiveProducts++;
}
}
public class Product
{
public bool Inactive {get;}
public Category Category {get;set;}
public void SetInactive()
{
this.Inactive= true;
Category.ProcessInactiveProduct();
}
}
I'd like other programmers to do:
var prod = Repository.Get<Product>(id);
prod.SetInactive();
I'd like to make sure they don't call ProcessInactiveProduct manually:
var prod = Repository.Get<Product>(id);
prod.SetInactive();
prod.Category.ProcessInactiveProduct();
I want to allow access of Category.ProcessInactiveProduct to only class Product. Other classes shouldn't be able to call Category.ProcessInactiveProduct.
Place both classes in a separate assembly and make the method internal.
You can if you make class A a private, nested class inside class B:
class B
{
class A
{
public Int32 Foo { get; set; }
}
}
Only B will be able to see A and it's members in this example.
Alternatively you could nest B inside A:
class A
{
Int32 Foo { get; set; }
public class B { }
}
In this case everyone can see both A and B but only B can see A.Foo.
You can restrict method/class access in this way:
[StrongNameIdentityPermissionAttribute(SecurityAction.Demand, PublicKey="…hex…", Name="App1", Version="0.0.0.0")]
public class Class1 { }
Take a look here http://msdn.microsoft.com/en-us/library/c09d4x9t.aspx for more info.
Managed code offers several ways to restrict method access:
...
Limit the method access to callers of a specified identity--essentially, any particular evidence (strong name, publisher, zone, and so on) you choose.
There is no out-of-the-box answer for your question.
If they are already in the same assembly, why not make the method internal scoped instead?
If they are in different assemblies, you can use the "friend" syntax which covers all internal methods.
Probably your best solution is to limit access to the public methods to specific assembly(ies). Which means that someone cannot just write a new assembly and go ahead an call your public methods. Given that you seem to have a domain model, it looks like you should allow this method to be called from other domain objects, but perhaps not from the business logic. This can be achieved by assigning a unique strong name to domain model DLL's.
You can restrict access to a public method to only allow it to be called by methods in assemblies satisfying a given public key. see msdn StrongNameIdentityPermission
You could use an Observer type of pattern, where the Category registers an interest in particular events on the Product (perhaps a ProductInactivated event?) and then handles the logic appropriately. This event-based pattern is very common and greatly reduces coupling. The Category is ultimately responsible for its own state and doesn't rely on the Product knowing something about what's containing it in order to keep the Category's state intact. The Product just tells interested clients when things have happened to it.
Another option is to refactor your Category class so that it contains or is contained by some CategoryProductServices object that encapsulates the methods that a Product would need to perform on its containing Category. In the context that creates the Categories and Products, pass the instance of this CategoryProductServices object to the Product rather than the full Category. This design keeps the interface public, but prevents your client from getting access to the services, as they can't retrieve an instance. It also loosens the tight coupling of Products to the Category class, limiting it to only those services that Products must be aware of. This leaves the Product in charge of the state, but at least limits what it needs to know/do.

Common Properties and Methods assigned to different subclass types

I'm working on building my own base user interface classes. On them, I want them to all have similar "common" properties and methods. I could define an interface class, but interface appears to only allow abstract methods, and no properties.
I don't want to copy the otherwise exact same code to each class, but not sure how to implement... Ex: I want this common stuff to be applicable to Buttons, Textbox, Checkbox, Listbox, etc user controls.
Suggestions???
In this situation I usually use abstract classes. Create your base abstract class and then inherit it from your new controls.
I myself come from a C++-background where multi-inheritance is allowed and used extensibly, so I often ran into the same problems as you.
The first thing you need to do is to read up on mix-ins - here you'll prolly notice that you've used them yourself all along, without ever naming them.
Second step is to start to recognize your mixins whenever you need them, and you'll often find out that you might as well use them via composition.
Third step is to implement them using composition... Yes, i hate this too, but there's no way around it if you wanna go .NET (or Java or...) :)
What you should use inheritence for is not for your mixins, but for stuff that actually identifies your items. I recommend looking at the .NET hierachy for some of the common controls (textbox and the likes) to get some inspiration.
Good luck
You can define properties on interfaces: interface properties
public interface ISampleInterface
{
// Property declaration:
string Name
{
get;
set;
}
}
You can declare a property in an interface as below:
public interface IMyInterface
{
string Name { get; set; }
int Age { get; set; }
}
However, in this situation it sounds like an abstract class would be better.
It's definitely possible to specify a property on an interface
interface IFoo {
string Name { get; set; }
string Age { get; } // Read Only
}
But otherwise you are correct. Interfaces specify no behavior and hence can only define "abstract" methods and properties. The implementation must be done on every single implementor. That's the price that is paid for flexibility in interfaces.
If the behavior is truly identical between all of the child classes then I usually go for an abstract class. Or often a combination. Namely define an interface and a base implementation which implements that interface.
class Foo : IFoo {
private string _name;
public Name { get { return _name; } set { _name = value; } }
public Age { get { return 42; } }
}
This allows you the flexibility of a quick implementation with the choice of usincg an interface for classes that for some reason cannot derive from Foo.
.Net doesn't allow multiple inheritance, but you can use an "inheritance hierarchy" to organize your base classes. This is how .Net itself is laid out.

It this an example of the Single Responsibility Principle?

I made the following code example to learn how to use a generics method signature.
In order to get a Display() method for both Customer and Employee, I actually began replacing my IPerson interface with an Person abstract class.
But then I stopped, remembering a podcast in which Uncle Bob was telling Scott Hanselman about the Single Responsibility Principle in which you should have lots of little classes each doing one specific thing, i.e. that a Customer class should not have a Print() and Save() and CalculateSalary() method but that you should have a CustomerPrinter class and a CustomerSaver class and a CustomerSalaryCalculator class.
That seems an odd way to program. However, getting rid of my interface also felt wrong (since so many IoC containers and DI examples use them inherently) so I decided to give the Single Responsibility Principle a try.
So the following code is different than I have programmed in the past (I would have made an abstract class with a Display() method and got rid of the interface) but based on what I have heard about decoupling and the S.O.L.I.D. principles, this new way of coding (the interface and the PersonDisplayer class) I think this is the right way to go.
I would like to hear if others think the same way on this issue or have experienced positive or negative effects of this (e.g. an unwieldy number of classes each doing one particular thing, etc.).
using System;
namespace TestGeneric33
{
class Program
{
static void Main(string[] args)
{
Container container = new Container();
Customer customer1 = container.InstantiateType<Customer>("Jim", "Smith");
Employee employee1 = container.InstantiateType<Employee>("Joe", "Thompson");
Console.WriteLine(PersonDisplayer.SimpleDisplay(customer1));
Console.WriteLine(PersonDisplayer.SimpleDisplay(employee1));
Console.ReadLine();
}
}
public class Container
{
public T InstantiateType<T>(string firstName, string lastName) where T : IPerson, new()
{
T obj = new T();
obj.FirstName = firstName;
obj.LastName = lastName;
return obj;
}
}
public interface IPerson
{
string FirstName { get; set; }
string LastName { get; set; }
}
public class PersonDisplayer
{
private IPerson _person;
public PersonDisplayer(IPerson person)
{
_person = person;
}
public string SimpleDisplay()
{
return String.Format("{1}, {0}", _person.FirstName, _person.LastName);
}
public static string SimpleDisplay(IPerson person)
{
PersonDisplayer personDisplayer = new PersonDisplayer(person);
return personDisplayer.SimpleDisplay();
}
}
public class Customer : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
}
public class Employee : IPerson
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int EmployeeNumber { get; set; }
}
}
I like to think of the Single Responsibility Principle as an implementation of separation of duties. Before I start splitting my classes as you have, I try to think of what each class should be responsible for.
Your classes are quite simple and lend themselves well to an abstract class with an implemented Print() and Save() functions as you mentioned. I would tend to keep that design over your current one.
However, if printing and saving were more complicated tasks which might be performed in different ways then a dedicated Printer or Saver class would be warranted, since that responsibility is now more complex. The 'complexity' threshold for making a new class is very subjective and will depend on the exact situation, but in the end, the code is just an abstraction for us lowly humans to understand, so make it such that it's the most intuitive.
You Container class is a little misleading. It doesn't actually 'contain' anything. It actually implements the Factory Method Pattern and would benefit from being named a factory.
Also, your PersonDisplayer is never instantiated and can provide all of its functionality through static methods, so why not make it a static class? It's not uncommon for utility classes such as Printers or savers to be static. Unless you have a need to have separate instances of a printer with different properties, keep it static.
I think you're on the right track. I'm not entirely sure about the Container class though. I'd generally stick with the simpler solution of just using "new" for these objects unless you have some business-driven need for that interface. (I don't consider "neat" to be a business requirement in this sense)
But the separation of "being" a customer responsibility from "displaying a customer" is nice. Stick with that, it's nice interpretation of SOLID principles.
Personally I have now completely stopped used any kind of static methods in this kind of code, and I rely on DI to get all the right service objects at the right place & time. Once you start elaborating further on the SOLID principles you'll find you're making a lot more classes. Try to work on those naming conventions to stay consistent.
Well, I've never heard of this 'single responsibility principle' before, but what it appears to me that what you're doing by having these CustomerPrinter class and CustomerSaver classes is simply converting classes back to structs, and de-object-orienting everything.
For example, this would mean that different customer types would need different cases in the CustomerPrinter class if they needed to be printed differently. But as I understand it, one of the point of OO organisation, and of using inheritance trees and all that, is to do away with the need of this CustomerPrinter to know how to print everything: Customers know how to print themselves.
I don't believe in following these paradigms rigidly in any case. For example I'm unsure what the difference between an Interface and an Abstract Class is in your case. But then again I'm a C++ programmer not a C# programmer...
A few notes:
Generally speaking SRP is all good, as is separation of display formatting from data.
Considering display etc. I would rather think in terms of services, i.e. a PersonDisplayer is single, stateless and offers a string Display(IPerson) function. IMHO, a special class wrapper just to provide display does not provide any advantage.
However, if you used data binding for wpf, you might have a DisplayablePerson class that would propagate PropertyChanged if Person changed. You would put DisplayablePerson objects into ObservableCollection and serve it as ItemsSource of some list control.
What do you need Container for, is it only for instantiating and configuring instance?Try then Customer customer1 = new Customer{FirstName= "Jim", LastName= "Smith"};
On a side note, I've tried object.Method < SomeType>(...) invocation a few times, as it seemed quickest and simplest solution. However, after some time I've always run into troubles with that one and ended up with object.Method(Type someTypeType, ...)
You might have a look at IFormattable and IFormatProvider.
The framework has formatting classes for support.

Categories

Resources