It this an example of the Single Responsibility Principle? - c#

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.

Related

Understanding Interfaces V Classes

Hi I know this is a well trodden question but after reading the following post What is the difference between an interface and a class, and why I should use an interface when I can implement the methods directly in the class? I am struggling to understand why an interface really needs to be used. Sorry for the basic question here but while I get the theory as a contract between the interface and the class I cannot seem to see how useful this is. I know it can help you create objects easily but I feel like I am missing something.
I have read so many posts on here and all over the internet to how to use an Interface but half of the time I am like well if you create a class and inherit it would it not do the same thing? what am I missing here?
Why interfaces?
Do you drive a car? If not, I assume you know what driving a car generally entails (steering wheel, accelerator, brake). The rest of the answer assumes you drive a car and have a car that is a different brand than mine.
Have you ever driven my car? No. But if given access, would you be able to drive my car without needing to learn how to drive my car? Yes.
The same applies to me. I've never driven your car, but I would be able to drive it without needing to learn how to drive it.
Why is that? Because all cars share the same interface. Steering wheel, accelerator on the right, brake in the middle. No two cars are exactly the same, but they are built in a way that the interaction between a driver and any car is exactly the same.
Compare this to an F16 fighter jet. Being able to drive a car does not make you able to pilot a jet because its interface is different. It doesn't have a steering wheel, it doesn't have accelerator/brake pedals.
The main benefit is clear: drivers don't need to learn how to drive every car individually.
Now, to complete the analogy, the general concept of a car is an interface, whereas specific cars are classes. The main benefit is clear: you don't need to write custom code for every similar class.
A practical example
public class BMW
{
public SteeringWheel SteeringWheel { get; set; }
public Pedal Accelerator { get; set; }
public Pedal Brake { get; set; }
}
public class BMWDriver
{
public void ParticipateInRace(BMW myBMW)
{
myBMW.Accelerator.Press();
myBMW.SteeringWheel.TurnLeft();
myBMW.SteeringWheel.TurnRight();
myBMW.Accelerator.Release();
myBMW.Brake.Press();
myBMW.Brake.Release();
}
}
This driver only knows how to drive a BMW.
public class Audi
{
public SteeringWheel SteeringWheel { get; set; }
public Pedal Accelerator { get; set; }
public Pedal Brake { get; set; }
}
public class AudiDriver
{
public void ParticipateInRace(Audi myAudi)
{
myAudi.Accelerator.Press();
myAudi.SteeringWheel.TurnLeft();
myAudi.SteeringWheel.TurnRight();
myAudi.Accelerator.Release();
myAudi.Brake.Press();
myAudi.Brake.Release();
}
}
This driver only knows how to drive an Audi.
But in reality, a driver would be able to drive any car (that has a steering wheel and two pedals).
So how do we tell the compiler that any car can be used? We give them a commonality they both share: the interface.
public interface ICar
{
SteeringWheel SteeringWheel { get; }
Pedal Accelerator { get; }
Pedal Brake { get; }
}
public class BMW : ICar { /* same as before */ }
public class Audi : ICar { /* same as before */ }
public class Driver
{
public void ParticipateInRace(ICar anyCar)
{
anyCar.Accelerator.Press();
anyCar.SteeringWheel.TurnLeft();
anyCar.SteeringWheel.TurnRight();
anyCar.Accelerator.Release();
anyCar.Brake.Press();
anyCar.Brake.Release();
}
}
We now have a more generalized Driver who is able to drive any car that has a steering wheel and two pedals.
Why not inheritance?
half of the time I am like well if you create a class and inherit it would it not do the same thing? what am I missing here?
In some cases, inheritance would work. However, inheritance is generally an inferior solution, especially when you get into more complex codebases or more advanced architectures.
Don't worry, all developers once loved inheritance and then needed to learn to not use inheritance as a cure-all. It's part of the normal lifecyle of a developer :)
One of the biggest reasons why is that you can't derive from more than one class, but you can implement multiple interfaces.
Let's say we have three types of sports that can be done
public class Runner
{
public void Run() { /* running logic */ }
}
public class Swimmer
{
public void Swim() { /* swimming logic */ }
}
public class Cyclist
{
public void Cycle() { /* cycling logic */ }
}
Now we need to create a specialized sport which entails running, e.g. basketball.
public class BasketBallPlayer : Runner
{
public void ThrowBall() { /* throwing logic */ }
// Running is already inherited from Runner
}
Great, no problems yet. But now, we need to create a triathlete class, which entails all three sports (running, swimming, cycling)
public class Triathlete: Runner, Swimmer, Cyclist { ... }
And this is where the compiler breaks down. It refuses to allow you to inherit from multiple base classes at the same time. The reasons are much deeper than this answer can delve into, Google it if you want to know more.
However, had we used interfaces:
public interface IRunner
{
void Run();
}
public interface ISwimmer
{
void Swim();
}
public interface ICyclist
{
void Cycle();
}
Then the compiler would've allowed this:
public class Triathlete: IRunner, ISwimmer, ICyclist
{
public void Run() { /* running logic */ }
public void Swim() { /* swimming logic */ }
public void Cycle() { /* cycling logic */ }
}
And this is why interfaces generally beat inheritance (among other reasons).
There are more reasons why interfaces are generally better, but this is the biggest one. Google it if you want more explanation, I can't delve into it all for a StackOverflow answer.
one scenario where you (the creator of the overall algorithm) simply doesn't know the implementation in advance.
To convert them into real life scenarios:
FxCop + StyleCop both use the visitor pattern to scan code. So, the creators of the tool (FxCop) in this example, has some basic code that couples to some UI/CLI and expects some certain properties in the scan result such as severity/problem etc.
And while FxCop ships with default rules, you, as end customer, can also extend these rules to your own liking. The only way for FxCop to do that is to rely on polymorpishm Interfaces/Abstract Classes.
So the FxCop tool expects a rule instance which detects something and reports back success or failure.
But your organization might have a custom rule which only you need. Let's say it's something like: All our namespaces must begin with myorg.mytool
That's an example of where you must use abstraction (can't just implement the code in a class up front) since Microsoft doedn't know anything in particular about the custom code rules tha you enforce in your organisation.
Another example is the way that Domain- and Infrastructure code are separated in Domain Driven Design.
So, let's say you have a book collection app. One where you can get a book, all books books by an auther etc.
You will then have a Domain Type call something like BookRepository where all your books are persisted. There's two sides of this: 1. Domain where all handling logic of books are placed and 2. persistence code (IO/Database or whatever).
The reason to split these two is because then the domain logic (business logic) doesn't get entangled with persistance code. The Domain code doesn't want to know how a book is persisted. It only cares about what you can do with a book (Get by Author, Buy, Sell etc.).
The interface in this case comes in as you place an interface in your Domain code called something like IBookRepository and you go on creating all the code you need with unit tests. At this point, you don't care much about how books are stored - you just care that they are stored. Then another team or later, you can dive into the details about how the book sa restored. In a database, in cache or something else. The persistence code can also evolve without touching the domain code which is an integral part of Continuous Release principles: As small updates as possible. In other words, it allows you to ship infrastructure updates wo touching the business code. It could be that you app is working excellent but you wan't to update the database drivers.
Abstract classes are something in between interfaces and classes but should be used similar as to interfaces / they're close in usage to interfaces than classes.
**
finally, there's another reason to use interfaces which is that an interface can be considered an aspect and you can apply multiple interfaces (aspects) to a single class (multiple inheritance) with little friction whereas placing it in classes forces you to do single inheritance which can result in large and overly complex inheritance hierachies.
Hope it helps you a bit
Well in essence and with as few words as i can think of for each case:
Abstract should be used when you have different entities sharing
common behavior.
Interface should be used when you want different entities to be able to work with the same code
For example you would use abstract when:
You want to create an app that handles animals.
You create an abstract class Animal which contains some fields NoLegs,HasTail,NoEyes.
You create a Dog , a Cat and a Panda class, all inheriting from Animal.
Now you end up having 3 classes, but with the shared code defined in 1 other class, because all of them share those descriptive traits.
Now for the interface:
Inside a service in your project you create a method called 'StartRunning'.
The definition of the method is :
public void StartRunning(List<ICanRun> thingsThatRun)
{
thingsThatRun.forEach(t => t.StartRunning());
}
Now you go back to your animal abstract class and you declare that it should implement ICanRun interface, and the compiler will force you to go and define the method on Dog,Cat and Panda classes. The great part now is that:
You have defined properties that are common in different objects only once. ( number of eyes is a trait common when describing animals)
The way each animal runs is different.Your dogs run method could 'just run straight ahead', while your cat run method could 'look for the closest wall and climb'. The Panda would probably throw cause pandas don't run.
The real magic on the interface:
Because your StartRunning method does not consider classes, but rather that the objects passed comform to the ICanRun interface, you can have an other class, say Bike, that also implements ICanRun and defines the method StartRunning.
Then you can create a list containing a dog, a cat and a bike and throw those 3 unrelated classes to the same list and pass that list to StartRunning, and they will all "Start running".
List<ICanRun> runableThings = new List<ICanRun>(){new Dog(), new Cat(), new Bike()};
StartRunning(runableThings);
I hope this example helps

Inherit class minus some fields - possible workarounds?

I don't have access to the definition of a class but I can inherit from it. I want in the derived class to be denied from accessing some fields that are public in the base class for obvious reasons of accidentally accessing/setting/getting the fields/properties.
What choices do I have?
EDIT:
Why the downvote? I have to refactor a large code that was using the said inherited fields and I have to manually treat the lines involving not only those but also the chained inherited fields down the hierarchical tree.
Additionally I have to make sure even I or my partners won't access those fields/properties and still using those intentedly inherited.
EDIT:
A distinction must be made between 2 separate cases: when the programmer designs the application from ground up and when s/he is compelled to proceed from inaccessible code.
In the former case s/he is responsible for applying OOP and design patterns as best fit for the future intended use s/he envisions.
In the latter, situations often come up when the programmer needs to develop from a slightly modified proprietary given class to avoid unneeded complications for the long term. Often times the original code designer can't exhaust the use cases. Thus the developer makes a custom version of the class with the "promise" the original class won't be used and even if ever used, it will only be used for the purposes originally intended, and no inheritance or other relation exists with the new version. This new version would have additional members and other missing members as compared to the original class. This would be consistent with I in SOLID, albeit adapted for classes.
In these cases I admit that inheritance is not the way to go, as it has a different purpose and the developer would break L (and conceptually I) from SOLID by using inheritance. But there's no feature of any language that provides for this, so there's no choice left.
The way I see it, you need to use the Decorator/Wrapper design pattern. Instead of inherinting it, you wrap a class around it.
The class you have:
public class SealedPerson
{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
The class you need:
public class SealedPersonWrapper
{
public SealedPersonWrapper(SealedPerson person)
{
this.Prop1 = person.Prop1;
}
public string Prop1 {get; private set;}
}
You can do this by separating interfaces:
public class BaseClass:IBase
{
private int A;
private int B;
void IBase.SetA()
{
A=10;
}
public void SetB()
{
B=10;
}
}
public class DerivedClass:BaseClass
{
public Set()
{
base.SetB();
//method SetA will not accessible through base class, but will accessible with IBase interface
}
}
Hide the inherited fields/properties/methods that you want unusable and make so using them would generate an error, like so:
public class Base // not owned code
{
public int free {get; set;};
public int limited {get; set;};
}
public class Derived:Base // owned code
{
// public new int limited; // NOT hidden! Still accessing Base.limited!
// working:
[Obsolete("Inaccessible hidden inherited variable", true)]
public new int limited {get; set;}
}
true is necessary to prohibit the compilation (trigger an error) instead of compiling with warning.
It's way much easier to write code especially for the unwanted fields than for the wanted ones, since using 90% of the base class.

Shortcuts, Suggestions When Using Static Wrappers for Direct Function Calls to Ubiquitous Interface-Wrapped Classes?

So I've (mostly) wrapped my head around C#'s componentization paradigm and why that's a superior (more predictable, flexible) alternative to confusing and quasi-unpredictable multiple inheritance of c++.
However, I have a couple things that are trouble me.
So if I understand correctly the general approach to adding a component is:
Create an interface that has that component of name I<ClassName adjective>
public interface IHasGear { Gear gear { get; set; } }
public interface IBladeEquipped { Blade blade { get; set; } }
Create an extension class that calls appropriate methods in the interfaced classes.
public static class GearExtensions
{
public static void Stop(this IHasGear machine)
{
machine.gear.KineticStop();
}
public static void Accelerate(this IHasGear machine)
{
machine.gear.ApplyAngularAcceleration();
}
}
public static class BladeExtensions
{
public static void Cut(this IBladeEquipped machine)
{
machine.blade.Cut();
}
public static void ReSharpen(this IBladeEquippeded machine)
{
machine.blade.ReSharpen();
}
}
And then finally add the interface reference and instance of the referenced class to my class that uses the selected component.
public class MeatGrinder : IHasGear, IHasBlade
{
public Gear oldToothyOne { get; set; }
public Blade mrPointy { get; set; }
public MeatGrinder() { oldToothyOne = new Gear(); mrPointy = new Blade();}
}
Now my couple of questions:
Why ALWAYS force the instantiation of the var?
I understand that you might want this if there is inheritance, as you could implement the var with different children. But what about the simplest case of non-inheritance? Why not build in an automatic mechanism to auto-implement in the compiled code the base class(es) in the interfaces is (are) implemented if they are not explicitly implemented
Is there a way to template this process in a ubiquitous fashion?
Obviously this is a repetitive task, if you have several components. Given the ambiguity, is there a way to streamline the workload??
Is there a superior componentization(/inheritance) scheme to the method I describe?
Things to keep in mind:
There's only a few component classes.
I want to be able to use the component class functions as direct calls in the composited class.
There are multiple composited classes (component classes << composited classes)
The components are dissimilar and thus not appropriate for unification in one class.
Given the above considerations an approach that forces me to write individualized code for each composited class is not a desirable approach.
EDIT 1:
I shouldn't have been ambiguous. The reason why I'm not using direct inheritance here is because I have multiple "key" components with functionality that I want to be able to directly address ubiquitously and publicly... e.g. I want to be able to say:
Machine myMachine = new Machine();
myMachine.Accelerate();
myMachine.Cut();
myMachine.ReSharpen();
Hopefully that helps to clarify my question and why I'm adopting this scheme.
Also, I had a couple errors in my example code (a var was non-public and my naming was consistent... these have been corrected.
EDIT 2:
Things that don't make sense for me (to my understanding):
a) Abstract Classes
Why? No multiple inheritance
b) Implicit Operators, a la, hcb's suggestion:
http://www.codeproject.com/Articles/10072/Simulated-Multiple-Inheritance-Pattern-for-C
Why? This approach requires you to create operators for ever class utilizing the component classes, which would result in much more code in a scheme where the interface is commonly used. To me if you're going to go that route, just make traditional wrapper functions rather than get all fancy.
My need for a more elegant solution is driven by ubiquity and mass use of a couple common components that perform redundant functionality, but are dissimilar and thus inappropriate to lump in a single class (despite the convenience that would provide).
Edit 3:
Props to svick for showing me how to format my code nicely without edit diving! :)
Retitled the question to make it more clear, added more precise requirements for suggesting alternate solutions.
What you're doing is just an attempt to emulate multiple inheritance. I don't think it's “the general approach to adding a component”.
I don't think what you're doing is a good way of using extension methods, it looks more like an anti-pattern to me. Especially since you're doing it just to save a few keystrokes, it doesn't add you any other benefit.
I think the answer to your questions about why you can't use some simpler way to do that is that C# tries to be explicit and consistent.
Explicit in that it won't guess what you mean, it makes you spell it out. This is because its guess could be very easily wrong. And the rules how exactly does it guess would probably have to be very complicated and thus confusing. (“I made this little change and now my code behaves completely differently.”)
Another thing is consistency: if you usually implement interface one way, but sometimes you do it differently, it makes the language more complicated and more confusing. Of course, there are cases where inconsistencies like this are worth it.
Specifically, if the feature of automatic implementation of properties from interfaces would work, your code would compile, but wouldn't work correctly: IBladeEquipped defines the property blade, but your class contains the property mrPointy. The compiler would see that you don't implement the required property and implement it for you. And then your code would fail with a NullReferenceException, because blade will always be null. So I think your code presents a good argument against that feature.
Also, I think your example is actually quite good at explaining why you shouldn't write the code the way you want. If you want to resharpen the knife of a meat grinder, do that: grinder.blade.Resharpen(). Writing it differently would feel less natural and more confusing to me.
I'm not sure if this is what your looking for but i like to couple interfaces with abstract base classes to implement default methods and properties:
public interface IHasGear { Gear gear { get; set; } }
public abstract class BHasGear : IHasGear { public virtual Gear gear { get; set; } }
public class MeatGrinder : BHasGear
{
//no need to implement gear, the abstract class already implemented it
private Gear oldToothyOne { get; set; } }
}

I'm worried I'm adding too many interfaces

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/

Creating a Namespace -> Class -> Nested Class? or

I was reading about creating classes and nested classes to determine what is the best approach for my needs, but I couldn't find something similar to what I need ( or couldn't understand it ;) ).
I will give you guys a (almost) real-life example:
Let's say I own a factory which manufactures different kinds of vehicles. So, my namespace would be Factory I figure.
Now, lets say the factory manufactures cars, boats and airplanes. So I will add three classes to my Factory namespace with those names.
Here is where my problem is with understanding the other methods:
I have some common things between the three types of vehicles. For example, they all have an engine (might be different HP or shapes which I understand are properties of the engine, but still they all have an engine). Also, cars and airplanes have doors (sometimes boats do too). On the other hand, they also have some unique things (airplanes have propellers for example that might come in different sizes or shapes).
Can someone please describe what I said in code so I could understand the differences between them?
Your question is a bit vague. Rather than try to answer it, I'll answer two related questions.
What is the purpose of a namespace?
The primary purpose of a namespace is to organize type declarations into a hierarchy so that they can be found by users easily.
The secondary purpose of a namespace is to provide a mechanism for disambiguating name collisions. That is, if XYZ Corp has a type Vehicle and ABC Inc has a type Vehicle, and PQR Ltd wants to use code from XYZ and ABC at the same time, the PQR programmers need a way to tell the compiler which type "Vehicle" actually refers to.
You suggest naming your namespace "Factory". That's probably a bad idea. A factory is probably a class, not a namespace. A factory is a kind of thing, not a way of organizing things. I would be inclined to name my namespace "Dementic.Manufacturing" and have it contain a Factory class. Now things are organized in two ways: first, by the company, Dementic Incorporated, that is producing the code, and by what the code is related to, namely, manufacturing. And it is unlikely that any competitor of yours will also make a namespace called Dementic.Manufacturing.
When should I make a nested type as opposed to a top-level type?
Make a nested type when the nested type is an implementation detail of the outer type. It is generally considered a poor practice to make a public nested type, though it is occasionally done.
A common example is an enumerator class; it is usually a private implementation detail of a enumerable collection.
You could stick all these in your Factory namespace.
A vehicle class would contain shared components, and classes for your specific vehicle types would inherit from the vehicle class... is that what you're asking?
public class Engine
{
public int HorsePower {get;set;}
}
public class Vehicle
{
public Vehicle() { }
public Engine Engine;
public int Doors;
}
public class Airplane : Vehicle
{
public Airplane () { }
public string PropellerModel;
}
public class Boat : Vehicle
{
public Boat () { }
public string RudderModel;
}
If you want to be as generic as possible, you can approach it something like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public abstract class Vehicle
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
public class Airplane : Vehicle
{
public ICollection<IPropeller> Propellers { get; protected set; }
}
}
Then have the specific concrete types provide the relevant collections to the supertype properties.
This is a bit of a hack, but modeling any real-world objects as classes in a programming language is going to break down sooner or later.
Note that I've made the engine property a collection too. This is to support, for example, the Prius class, which would have two engines.
An alternate approach would be to define the vehicles in terms of interfaces, somewhat like this:
namespace Factory
{
public interface IDoor { }
public interface IEngine { }
public interface IPropeller { }
public interface IDoorProvider
{
ICollection<IDoor> Doors { get; }
}
public interface IEngineProvider
{
ICollection<IEngine> Engines { get; }
}
public interface IPropellerProvider
{
ICollection<IPropeller> Propellers { get; }
}
public abstract class Vehicle { }
public class Car : Vehicle, IDoorProvider, IEngineProvider
{
public ICollection<IDoor> Doors { get; protected set; }
public ICollection<IEngine> Engines { get; protected set; }
}
// And so on...
}
This approach has the advantage that you don't have to define much on Vehicle itself, but this also means that you can't easily share the definitions of these members across all of the classes. However, this prevents you from defining members on the base type that are not relevant to the concrete types.
You have the wrong concept of what namespaces are. Namespaces have nothing to do with this.
I think you're also confusing inheritance and factories. Again, those are very separate ideas.
First think about creating your class heirarchy with the common base class that provides the basic structure of your objects and then the specialized subclasses that provide the specific details. And be careful not to use inheritance unless it truly works. Don't force your model into an inheritance heirarchy if it doesn't make sense.
Then you can worry about creating one or more factories to create instances of these objects.
As for namespaces, a namespace is just a way to group related pieces of code together in a logical, meaningful way. You might have a factory namespace, but you could just as well have a "factories" namespace or a "vehicles" namespace or something completely different which is relevant to your domain.
Since the person asking the question might actually get some value out of it, here my take:
If your software deals in some ways with objects of the real world, don't try to model the set of classes that represent the core of your application according to the real world. Rather, let the requirements of the software guide as to how your objects will look like.
For example, is this an order management system?
In that case it may be more relevant that certain orderable items have other orderable items directly associated with it. For a boat you can order certain parts, engines, etc. That is, it may more important to express the relationships between orderable items instead of having them available as concrete types.
For example, is it a tool to draw new boats, planes, propellers, etc.? Then a more relevant base class maybe that of a shape. Is it more about calculating the power of an engine or the efficiency of a propeller? Then you may need some concept of mathematical bodies and additional physical relationships and characteristics need to be defined between the different objects.
Lastly, as a rule of thumb you can think of inheritance as a somewhat overrated concept in that it is the first thing that starters think of when touching OO. The predominant concept of reuse in nature is composition - ultimately all natural things are composed of small items with very clear interfaces. Ideally, you will try and compose your OO application in a similar fashion.
I would rather go for VehicleFactory namespace, Factory as a class (there are many design patterns addresing the problem of creating objects and usually this needs to be a class, or at least (usually in non-objective programming) function. Namespace won't provide you this.

Categories

Resources