Design Pattern to Handle Grouping Similar Entities Together - c#

Over the past few years I've been on projects where we've run into a similar problem in our object hierarchy that always seems to cause problems. I was curious if anyone here knew of a classical OOP (Java, C#, PHP5, etc) design pattern that could gracefully handle this situation.
Say we have an existing system. This system has, among other things, two types of entities, each modeled with an individual class. Let's say
Customer
SalesRepresentative
For historical reasons, neither of these classes inherit from the same base class or share a common interface.
The problem I've seen is, inevitably, a new feature gets specced out that requires us to treat the Customer and the SalesRepresentative as the same type of Object. The way I've seen this handled in the past is to create a new class that includes a member variable for both, and then each method will operate on the objects differently depending on which is set
//pseudo PHPish code
class Participator
{
public $customer;
public $salesRepresentative;
public function __construct($object)
{
if(object is instance of Customer)
{
$this->customer = $object;
}
if(object is instance of SalesRepresentative)
{
$this->salesRepresentative = $object;
}
}
public function doesSomething()
{
if($customer)
{
//We're a customer, do customer specific stuff
}
else if($salesRepresentative)
{
//We're a salesRepresentative, do sales
//representative specific stuff
}
}
}
Is there a more graceful way of handling this type of situation?

Maybe a Wrapper can be used here. Create a Wrapper Interface say ParticipatorWrapper that specifies the new functionality and build concrete Wrappers for each class, say CustomerWrapper and SalesRepresentativeWrapper that both implement the new functionality.
Then simply wrap the object in its appropriate wrapper and write code that targets the ParticipatorWrapper.
Update: Javaish code:
interface ParticipatorWrapper{
public void doSomething();
}
class CustomerWrapper implements ParticipatorWrapper{
Customer customer;
public void doSomething(){
//do something with the customer
}
}
class SaleREpresentativeWrapper implements ParticipatorWrapper{
SaleRepresentative salesRepresentative;
public void doSomething(){
//do something with the salesRepresentative
}
}
class ClientOfWrapper{
public void mymethod(){
ParticipatorWrapper p = new ParticipatorWrapper(new Customer());
p.doSomething();
}
}

This is an alternative to that Vincent's answer, taking an opposite sort of approach. As I note below, there are some downsides, but your specific problem may obviate those and I think this solution is simpler in those cases (or you may want to use some combination of this solution and Vincent's).
Rather than wrapping the classes, introduce hooks in the classes and then pass them the functions. This is a reasonable alternative if you're looking to do the same thing with the same data from both classes (which I am guessing you are, based on lamenting that the two classes don't have a shared superclass).
This is using Visitor instead of Wrapper. Javaish this be something like:
public <Output> Output visit(Vistor<Output> v) {
return v.process(...all shared the fields in Customer/SalesRep...);
}
And then you have a Visitor interface which all your functions inherit from that looks like:
interface Visitor<Output> {
public Output process(...shared fields...);
}
There are someways to chop what gets passed to your Visitor, but the involves introducing new classes to specify which inputs to use, which becomes wrapping anyways, so you might as well use Vincent's answer.
The downside to this solution is if you do something that alters the structure of the class fields, you can buy yourself lots of refactoring, which is less of a problem in Vincent's answer. This solution is also a little bit less useful if you're making modifications to the data stored in the Customer/SalesRep instance, as you'd effectively have to wrap those inside the Visitor.

I think you could apply the concept of mixins to your classes to get the functionality you want.

Related

c# practices for correct object oriented techniques

I have some c# code that has been working well for a while now.. and I have to say, whilst I understand the basics of OO principles, there is obviously more than one way to skin a cat (although I hate that phrase!).
So, I have a base abstract class that is acting as a basic data service class as follows (much simplified just for ease of reading):
public abstract class dataservice
{
public enum OutputType : int { XmlTOJson = 0, Xml = 1, Json=2 }
protected object SomeDBcall(string StoredProcedure)
{
// Just assume we are using SQLclient/DB access..
object SomeReturnObjValue = db.ExecuteScalar(cmd);
return SomeReturnObjValue;
{
}
.. so basically I might have a few basic DB retrieve/update/delete calls in the abstract class.. mainly as there are the basis of any DB operation I have in my app.
So now we have a class that implements the base class, say in my case a customer class:
public class Customer : dataservice
{
Public String CustomerDoSomething(string SomeDataEtc)
{
// Ok, so again for simplicity sake, we are going to use the base class to
// call a DB retrieve
object ReturningObj = SomeDBcall("my stored procedure");
return ReturningObj.ToString();
}
}
So I guess my question is this: Is the above method "ok" to use? considering a virtual method could be over-ridden if required, however in this case I only want the base class to use those methods which are protected as the means to call the DB operations.
Any clarity/guidance very appreciated!
Sure, it's "ok", though I see no reason for the base class to be abstract. abstract classes are great for implementing some common logic and leaving the rest up to derived classes to implement. However, you have no abstract/virtual methods, so I don't see the point here.
Perhaps you can let your abstract class be concrete and use it as some kind of helper class which handles the database related stuff you need. As far as the example code shows, there is no need to have multiple database accessing classes, just different parameters.
Overview
Many times, your "development itself will guide you".
Practical answer.
(1) You define a base class "dataservice", and from that class, several other classes will be based upon. You marked as "abstract", thats good. It's not mean to have variables by itself.
Some developers won't mark that class as "abstract", its not obligatory, but, its a not a bad idea, but, its a "good practice", to marked "abstract".
And, other methods will be added, used by the subclasses, maybe overriden, maybe not.
For know, those methods are protected, and anot mean to be used outside the object, but, by other methods. That's ok.
Maybe, later, a method may be required to be used outside the class, and may have to change to public.
(2) You add a subclass "Customer" that is a descendant from "DataService" You add a method that has to be used outside the class, and marked as "public", good.
It's only meant to be used by this class, not the parent class. So, no "virtual" or "override" required. Good.
(3) Your example its very simple. Most things you did, seems fine to me.
Eventually, when you add more code, things may change, example a method in the base class that was private may become public, or you may "rename" or "refactor" a method, like "dosomething", and found out that its better to be in the base class, or maybe not.
Summary
There are other answers, that mention, rules, or concepts. Seems to me that they are OK, but, skip the fact that you are learning to use O.O.P. better. Some people just try to "eat the cake in one wingle big bite", and that's not a good idea.
P.D. "can ur skin ur rabbit", sounds better to me.
Cheers.
You might want to look to the Template pattern to define the interface in the base (abstract or not) class with defined protected virtual hooks that can be overridden in the concrete subclasses. As mentioned by another poster, if you just intend to add DB services to each of your domain areas you might look to encapsulate the basic database service methods into a helper class rather than deriving from the database service.
Thanks #jgauffin for questioning my LSP violation statement. It was not correct and has been removed. There are lots of cases where extending the public interface of the base class by subclasses is warranted. Of course, by doing that one needs to be careful that you have an instance of a Y and not an X or a Z when performing a Y-specific operation A(), assuming that both Y and Z derive from X where Y adds the new public method A() and Z does not.
An example of the Template pattern in the OP's context would allow better encapsulation of custom functionality within subclasses without extending the public interface. However, this only works if there is not external influence exerted on the subclass instance, such as the OP's SomeDataEtc parameter. This works best when the instance is immutable.
public abstract class DataService
{
protected object myWidget = new Widget();
public object SomeDataBaseCall(string storedProcedure)
{
DoSomeCustomThing();
//do db stuff
object SomeReturnObjValue = db.ExecuteScalar(storedProcedure);
return SomeReturnObjValue;
}
protected void DoSomeCustomThing() {}
}
public class Customer : DataService
{
override protected void DoSomeCustomThing()
{
// do your custom thing here
}
}
Additionally, in the OP's example, it would seem prudent to use delegation within the derived class's new public method to call the base class's SomeDBCall method to execute the stored procedure. If you are redundantly coding the db access methods then there is no benefit to the proposed inheritance.
As was also mentioned elsewhere, you might be better off altogether by using composition rather than inheritance for the data service functionality.
No. Guess your following data access object pattern (DAO). Either way your Customer is not your data access class. It uses a class for data access. What I mean is that your DAO should favor composition over inheritance.
Something like:
public class Customer : IDataAccessObject
{
public Customer()
{
_dataAccess = new DataAccess();
}
public string CustomerDoSomething(string SomeDataEtc)
{
object ReturningObj = _dataAccess.SomeDBcall("my stored procedure");
return ReturningObj.ToString();
}
}
Why? Your objects get's a single responsibility which means that it's easier to extend and refactor them.
You can read up about SOLID which is some fundamental programming principles.
Since you are a .NET developer I also recommend that you embrace the naming guidelines.

Is there a better design option?

Disclaimer: I would love to be using dependency injection on this
project and have a loosely coupled interface-based design across the board, but use of dependency-injection has been shot down in this project. Also SOLID design principles (and design patterns in general) are something foreign where I work and I'm new to many of them myself. So take that into
consideration when suggesting a better design to this problem.
Here is a simplified version of the code I'm working on, and as such it might seem contrived. If so I apologize. Consider the following classes:
// Foo is a class that wraps underlying functionality from another
// assembly to create a simplified API. Think of this as a service layer class,
// a facade-like wrapper. It contains a helper class that is specific to
// foo. Other AbstractFoo implementations have their own helpers.
public class Foo : AbstractFoo
{
private readonly DefaultHelper helper;
public override DefaultHelper Helper { get { return helper; } }
public Foo()
{
helper = new Helper("custom stuff");
}
public override void Operation1(string value)
{
Console.WriteLine("Operation1 using " + value);
}
public override void Operation2()
{
Console.WriteLine("Operation2");
}
}
// Helper derives from a default implementation and allows us to
// override it's methods to do things specific for the class that
// holds this helper. Sometimes we use a custom helper, sometimes
// we use the default one.
public class Helper : DefaultHelper
{
private readonly string customStuff;
public Helper(string value)
{
customStuff = value;
}
public override void DoSomethingHelpful()
{
Console.WriteLine("I was helpful using " + customStuff);
}
}
Say these two class are used as follows:
// foo referenced and used in one part of code
var foo = new Foo();
foo.Operation2(); // or foo.Operation1();
// some other point in the program where we don't have a reference to foo
// but do have a reference to the helper
helper.DoSomethingHelpful();
However I now find out that I also need to perform foo.Operation1 in some implementations of helper.DoSomethingHelpful();? Potential workarounds I thought of would be:
Have foo and helper have a bidirectional relationship. So that in DoSomethingHelpful we can call foo.Operation2
Have foo implement IHelp interface and move the "helper" code into foo
Use delegation and pass the method Operation2 as an Action<string> delegate into the constructor of Helper.
None of these approaches seem to be ideal (though I've pretty much determined I don't like option 1 and am worried about maintainability with option 3 if we find out later we need to pass in more delegates). This makes me wonder if there is a problem with the initial design of the Helper/Foo combo. Thoughts?
How about a casual ("uses") relationship:
public class Helper : DefaultHelper
{
private readonly string customStuff;
public Helper(string value)
{
customStuff = value;
}
public override void DoSomethingHelpful(AbstractFoo foo)
{
foo.Operation1();
Console.WriteLine("I was helpful using " + customStuff);
}
}
So you modify the abstract helper to expect a reference to the proper Foo implementation.
"None of these approaches seem to be ideal (though I've pretty much
determined I don't like option 1 and am worried about maintainability
with option 3 if we find out later we need to pass in more delegates).
This makes me wonder if there is a problem with the initial design of
the Helper/Foo combo."
You're exactly right - there IS a problem with the design of Helper and Foo. The basic Foo/Helper relationship as you initially described it is fine, and is a common pattern when you have to wrap other objects that you do not control. But then you say:
"What if I find out that I also need to perform foo.Operation1 in some
implementations of helper.DoSomethingHelpful();?"
This is where we have a problem. You started out describing a relationship where Foo is dependent on Helper; now you are describing a relationship where Helper is dependent on Foo. That immediately tells me that your dependency relationships are tangled up. Dependency relationships between objects should only go one way; in fact dependency injection relies on this.
I think you have what you need. Try not to design for the "just in case I need it later" and don't fix what is not broken. If in the future you need to use Operation1 from your helper, then add it as a dependency on the constructor (as you suggested), or just pass it to the method you are calling. It will depend on the scenario, and you will have it when you actually need something.
EDIT: changed the "Try not to design for the future" as it doesn't seem what I want to say.
EDIT again due changes in the question
You could so something like this:
helper.DoSomethingUsefulWith( foo );
so your helper method will receive the dependency it needs in order to work
I think all your solutions are good; they just offer different capabilities. These differences don't matter too much now but are likely to in the future.
You prefer the second one, and your instincts are the best guide here, you knowing more than the rest of us about your code's future. I like your second solution the best just because it gets rid of a class and is simpler. Due to it's simplicity, if you have to do something else later, you won't have to throw away a lot of work.
The first method lets you play games with different Helper (IHelper?) instances and subclasses. The last method adds a lot of flexibility to Helper. (Although it may add so much you don't need Helper, just the method you're passing to it.) You can switch to using them later if either seems to solve more of the future's unguessed problems.

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; } }
}

C# share code between classes

In Visual Studio 2008 using C#, what is the best way to share code across multiple classes and source files?
Inheritance is not the solution as the classes already have a meaningful hierarchy.
Is there some neat feature that's like a C include file that let's you insert code anywhere you want in another class?
EDIT:
ok, i guess we need a concrete example...
There are several hundred classes in the domain with a well thought out class heirarchy. Now, many of these classes need to print. There is a utility printer class that handles the printing. Let's say there are 3 different print methods that are dependent on the class that is being printed. The code that calls the print method (6 lines) is what I'm trying to avoid copying and pasting across all the different client class pages.
It'd be nice if people wouldn't assume they knew more about the domain that the op - especially when they specifically mention techniques that don't fit...
If you have functionality that you use frequently in classes that represent very different things, in my experience that should fall into just a few categories:
Utilities (e.g. string formatting, parsing, ...)
Cross-cutting concerns (logging, security enforcement, ...)
For utility-type functionality you should consider creating separate classes, and referencing the utility classes where needed in the business class.
public class Validator
{
public bool IsValidName(string name);
}
class Patient
{
private Validator validator = new Validator();
public string FirstName
{
set
{
if (validator.IsValidName(value)) ... else ...
}
}
}
For cross-cutting concerns such as logging or security, I suggest you investigate Aspect-Oriented Programming.
Regarding the PrintA vs. PrintB example discussed in other comments, it sounds like an excellent case for the Factory Pattern. You define an interface e.g. IPrint, classes PrintA and PrintB that both implement IPrint, and assign an instance of IPrint based on what the particular page needs.
// Simplified example to explain:
public interface IPrint
{
public void Print(string);
}
public class PrintA : IPrint
{
public void Print(string input)
{ ... format as desired for A ... }
}
public class PrintB : IPrint
{
public void Print(string input)
{ ... format as desired for B ... }
}
class MyPage
{
IPrint printer;
public class MyPage(bool usePrintA)
{
if (usePrintA) printer = new PrintA(); else printer = new PrintB();
}
public PrintThePage()
{
printer.Print(thePageText);
}
}
You can't just load in code that you'd like to have added into a class in C# via a preprocessor directive like you would in C.
You could, however, define an interface and declare extension methods for that interface. The interface could then be implemented by your classes, and you can call the extension methods on those classes. E.g.
public interface IShareFunctionality { }
public static class Extensions
{
public static bool DoSomething(this IShareFunctionality input)
{
return input == null;
}
}
public class MyClass : Object, IShareFunctionality
{
public void SomeMethod()
{
if(this.DoSomething())
throw new Exception("Impossible!");
}
}
This would allow you to reuse functionality, but you cannot access the private members of the class like you would be able to if you could, say, hash include a file.
We might need some more concrete examples of what you want to do though?
A C# utility class will work. It acts like a central registry for common code (or like the VB.NET Module construct) - it should contain code that's not specific to any class otherwise it should have been attached to the relevant class.
You don't want to start copying source code around if you don't have to because that would lead to code update problems considering the duplication.
As long as the source doesn't need to retain state, then use a static class with static method.
static public class MySharedMembers {
static public string ConvertToInvariantCase(string str) {
//...logic
}
// .... other members
}
If the classes are in the same namespace, there's no need for an include analog. Simply call the members of the class defined in the other function.
If they're not in the same namespace, add the namespace of the classes you want to use in the usings directives and it should work the same as above.
I'm confused by the question: it seems you need to work on your basic OO understanding.
Checkout extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
I don't know of a way to include portions of files but one thing we do frequently is to add an existing file and "link" it from its current location. For example, we have an assemblyInfo.cs file that every project refers to from a solution directory. We change it once and all the projects have the same info because they're referring to the same file.
Otherwise, suggestions about refactoring "common" routines in a common.dll are the best thing I've come up with in .Net.
I am not sure exactly what you mean by a "meaningful" structure already, but this sounds like a place where you could use base class implementation. Though not as "verbose" as C++ multiple inheritance, you might get some benefit out of using chained base class implementation to reuse common functions.
You can preserve class hierarchy, at least visually and override behavior as needed.
Pull out the repetitive code into services. The repetitive code is a clue that there might be some room for refactoring.
For example, create a "PrintingService" which contains the logic needed to print. You can then have the classes that need to print have a dependency on this service (either via the constructor or a parameter in a method which requires the service).
Another tip i have along these lines is to create interfaces for base functionality and then use the interfaces to code against. For example, i had bunch of report classes which the user could either fax, email, or print. Instead of creating methods for each, i created a service for each, had them implement an interface that had a single method of Output(). I could then pass each service to the same method depending on what kind of output the user wanted. When the customer wanted to use eFax instead of faxing through the modem, it was just a matter of writing a new service that implemented this same interface.
To be honest I can't think of anything like includes in Visual C#, nor why you would want that feature. That said, partial classes can do something like it sounds what you want, but using them maybe clashes against your "classes already have a meaningful hierarchy" requirement.
You have many options, TT, extension method, delegate, and lambda

Understanding Interfaces

I am still having trouble understanding what interfaces are good for. I read a few tutorials and I still don't know what they really are for other then "they make your classes keep promises" and "they help with multiple inheritance".
Thats about it. I still don't know when I would even use an interface in a real work example or even when to identify when to use it.
From my limited knowledge of interfaces they can help because if something implements it then you can just pass the interface in allowing to pass in like different classes without worrying about it not being the right parameter.
But I never know what the real point of this since they usually stop short at this point from showing what the code would do after it passes the interface and if they sort of do it it seems like they don't do anything useful that I could look at and go "wow they would help in a real world example".
So what I guess I am saying is I am trying to find a real world example where I can see interfaces in action.
I also don't understand that you can do like a reference to an object like this:
ICalculator myInterface = new JustSomeClass();
So now if I would go myInterface dot and intellisense would pull up I would only see the interface methods and not the other methods in JustSomeClass. So I don't see a point to this yet.
Also I started to do unit testing where they seem to love to use interfaces but I still don't understand why.
Like for instance this example:
public AuthenticationController(IFormsAuthentication formsAuth)
{
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
}
public class FormsAuthenticationWrapper : IFormsAuthentication
{
public void SetAuthCookie(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
public IFormsAuthentication FormsAuth
{
get;
set;
}
Like why bother making this interface? Why not just make FormsAuthenticationWrapper with the methods in it and call it a day? Why First make an interface then have the Wrapper implement the interface and then finally write the methods?
Then I don't get what the statement is really saying.
Like I now know that the statement is saying this
FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
if formsAuth is null then make a new FormsAuthenticationWrapper and then assign it to the property that is an Interface.
I guess it goes back to the whole point of why the reference thing. Especially in this case since all the methods are exactly the same. The Wrapper does not have any new methods that the interface does not have and I am not sure but when you do this the methods are filled right(ie they have a body) they don't get converted to stubs because that would really seem pointless to me(it it would be converted back to an interface).
Then in the testing file they have:
var formsAuthenticationMock = new Mock<AuthenticationController.IFormsAuthentication>();
So they just pass in the FormsAuthentication what I am guessing makes all the fake stubs. I am guessing the wrapper class is used when the program is actually running since it has real methods that do something(like sign a person out).
But looking at new Mock(from moq) it accepts a class or an interface. Why not just again made the wrapper class put those methods in and then in the new Mock call that?
Would that not just make the stubs for you?
Ok, I had a hard time understanding too at first, so don't worry about it.
Think about this, if you have a class, that lets say is a video game character.
public class Character
{
}
Now say I want to have the Character have a weapon. I could use an interface to determin the methods required by a weapon:
interface IWeapon
{
public Use();
}
So lets give the Character a weapon:
public class Character
{
IWeapon weapon;
public void GiveWeapon(IWeapon weapon)
{
this.weapon = weapon;
}
public void UseWeapon()
{
weapon.Use();
}
}
Now we can create weapons that use the IWeapon interface and we can give them to any character class and that class can use the item.
public class Gun : IWeapon
{
public void Use()
{
Console.Writeline("Weapon Fired");
}
}
Then you can stick it together:
Character bob = new character();
Gun pistol = new Gun();
bob.GiveWeapon(pistol);
bob.UseWeapon();
Now this is a general example, but it gives a lot of power. You can read about this more if you look up the Strategy Pattern.
Interfaces define contracts.
In the example you provide, the ?? operator just provides a default value if you pass null to the constructor and doesn't really have anything to do with interfaces.
What is more relevant is that you might use an actual FormsAuthenticationWrapper object, but you can also implement your own IFormsAuthentication type that has nothing to do with the wrapper class at all. The interface tells you what methods and properties you need to implement to fulfill the contract, and allows the compiler to verify that your object really does honor that contract (to some extent - it's simple to honor a contract in name, but not in spirit), and so you don't have to use the pre-built FormsAuthenticationWrapper if you don't want to. You can build a different class that works completely differently but still honors the required contract.
In this respect interfaces are much like normal inheritance, with one important difference. In C# a class can only inherit from one type but can implement many interfaces. So interfaces allow you to fulfill multiple contracts in one class. An object can be an IFormsAuthentication object and also be something else, like IEnumerable.
Interfaces are even more useful when you look at it from the other direction: they allow you to treat many different types as if they were all the same. A good example of this is with the various collections classes. Take this code sample:
void OutputValues(string[] values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This accepts an array and outputs it to the console. Now apply this simple change to use an interface:
void OutputValues(IEnumerable<string> values)
{
foreach (string value in values)
{
Console.Writeline(value);
}
}
This code still takes an array and outputs it to the console. But it also takes a List<string> or anything else you care to give it that implements IEnumerable<string>. So we've taken an interface and used it to make a simple block of code much more powerful.
Another good example is the ASP.Net membership provider. You tell ASP.Net that you honor the membership contract by implementing the required interfaces. Now you can easily customize the built-in ASP.Net authentication to use any source, and all thanks to interfaces. The data providers in the System.Data namespace work in a similar fashion.
One final note: when I see an interface with a "default" wrapper implementation like that, I consider it a bit of an anit-pattern, or at least a code smell. It indicates to me that maybe the interface is too complicated, and you either need to split it apart or consider using some combination of composition + events + delegates rather than derivation to accomplish the same thing.
Perhaps the best way to get a good understanding of interfaces is to use an example from the .NET framework.
Consider the following function:
void printValues(IEnumerable sequence)
{
foreach (var value in sequence)
Console.WriteLine(value);
}
Now I could have written this function to accept a List<T>, object[], or any other type of concrete sequence. But since I have written this function to accept a parameter of type IEnumerable that means that I can pass any concrete type into this function that implements the IEnumerable interface.
The reason this is desirable is that by using the interface type your function is more flexible than it would otherwise be. Also you are increasing the utility of this function as many different callers will be able to make use of it without requiring modification.
By using an interface type you are able to declare the type of your parameter as a contract of what you need from whatever concrete type is passed in. In my example I don't care what type you pass me, I just care that I can iterate it.
All of the answers here have been helpful and I doubt I can add anything new to the mix but in reading the answers here, two of the concepts mentioned in two different answers really meshed well in my head so I will compose my understanding here in the hopes that it might help you.
A class has methods and properties and each of the methods and properties of a class has a signature and a body
public int Add(int x, int y)
{
return x + y;
}
The signature of the Add method is everything before the first curly brace character
public int Add(int x, int y)
The purpose of the method signature is to assign a name to a method and also to describe it's protection level (public, protected, internal, private and / or virtual) which defines where a method can be accessed from in code
The signature also defines the type of the value returned by the method, the Add method above returns an int, and the arguments a method expects to have passed to it by callers
Methods are generally considered to be something an object can do, the example above implies that the class the method is defined in works with numbers
The method body describes precisly (in code) how it is that an object performs the action described by the method name. In the example above the add method works by applying the addition operator to it's parameters and returing the result.
One of the primary differences between an interface and a class in terms of language syntax is that an interface can only define the signature of a methd, never the method body.
Put another way, an interface can describe in a the actions (methods) of a class, but it must never describe how an action is to be performed.
Now that you hopefully have a better understanding of what an interface is, we can move on to the second and third parts of your question when, and why would we use an interface in a real program.
One of the main times interfaces are used in a program is when one wants to perform an action, without wanting to know, or be tied to the specifics of how those actions are performed.
That is a very abstract concept to grapsp so perhaps an example might help to firm things up in your mind
Imagine you are the author of a very popular web browser that millions of people use every day and you have thousands of feature requests from people, some big, some little, some good and some like "bring back <maquee> and <blink> support".
Because you only have a relitivly small number of developers, and an even smaller number of hours in the day, you can't possibly implement every requested feature yourself, but you still want to satisfy your customers
So you decide to allow users to develop their own plugins, so they can <blink 'till the cows come home.
To implement this you might come up with a plugin class that looks like:
public class Plugin
{
public void Run (PluginHost browser)
{
//do stuff here....
}
}
But how could you reasonably implement that method? You can't possibly know precisly how every poossible future plugin is going to work
One possible way around this is to define Plugin as an interface and have the browser refer to each plugin using that, like this:
public interface IPlugin
{
void Run(PluginHost browser);
}
public class PluginHost
{
public void RunPlugins (IPlugin[] plugins)
{
foreach plugin in plugins
{
plugin.Run(this);
}
}
}
Note that as discussed earlier the IPlugin interface describes the Run method but does not specify how Run does it's job because this is specific to each plugin, we don't want the plugin host concerned with the specifics of each individual plugin.
To demonstrate the "can-be-a" aspect of the relationship between a class and an interface I will write a plugin for the plugin host below that implements the <blink> tag.
public class BlinkPlugin: IPlugin
{
private void MakeTextBlink(string text)
{
//code to make text blink.
}
public void Run(PluginHost browser)
{
MakeTextBlink(browser.CurrentPage.ParsedHtml);
}
}
From this perspective you can see that the plugin is defined in a class named BlinkPlugin but because it also implements the IPlugin interface it can also be refered to as an IPlugin object,as the PluginHost class above does, because it doesn't know or care what type the class actually is, just that it can be an IPlugin
I hope this has helped, I really didnt intend it to be quite this long.
I'll give you an example below but let me start with one of your statements. "I don't know how to identify when to use one". to put it on edge. You don't need to identify when to use it but when not to use it. Any parameter (at least to public methods), any (public) property (and personally I would actually extend the list to and anything else) should be declared as something of an interface not a specific class. The only time I would ever declare something of a specific type would be when there was no suitable interface.
I'd go
IEnumerable<T> sequence;
when ever I can and hardly ever (the only case I can think off is if I really needed the ForEach method)
List<T> sequence;
and now an example. Let's say you are building a sytem that can compare prices on cars and computers. Each is displayed in a list.
The car prices are datamined from a set of websites and the computer prices from a set of services.
a solution could be:
create one web page, say with a datagrid and Dependency Injection of a IDataRetriever
(where IDataRetriver is some interface making data fetching available with out you having to know where the data came from (DB,XML,web services or ...) or how they were fetched (data mined, SQL Quering in house data or read from file).
Since the two scenarios we have have nothing but the usage in common a super class will make little sense. but the page using our two classes (one for cars and one for computers) needs to perform the exact same operations in both cases to make that possible we need to tell the page (compiler) which operations are possible. We do that by means of an interface and then the two classes implement that interfcae.
using dependency injection has nothing to do with when or how to use interfaces but the reason why I included it is another common scenario where interfaces makes you life easier. Testing. if you use injection and interfaces you can easily substitute a production class for a testing class when testing. (This again could be to switch data stores or to enforce an error that might be very hard to produce in release code, say a race condition)
We use interfaces (or abstract base classes) to allow polymorphism, which is a very central concept in object-oriented programming. It allows us to compose behavior in very flexible ways. If you haven't already, you should read Design Patterns - it contains numerous examples of using interfaces.
In relation to Test Doubles (such as Mock objects), we use interfaces to be able to remove functionality that we currently don't want to test, or that can't work from within a unit testing framework.
Particularly when working with web development, a lot of the services that we rely on (such as the HTTP Context) isn't available when the code executes outside of the web context, but if we hide that functionality behind an interface, we can replace it with something else during testing.
The way I understood it was:
Derivation is 'is-a' relationship e.g., A Dog is an Animal, A Cow is an Animal but an interface is never derived, it is implemented.
So, interface is a 'can-be' relationship e.g., A Dog can be a Spy Dog, A Dog can be a Circus Dog etc. But to achieve this, a dog has to learn some specific things. Which in OO terminology means that your class has to able to do some specific things (contract as they call it) if it implements an interface. e.g., if your class implements IEnumerable, it clearly means that your class has (must have) such a functionality that it's objects can be Enumerated.
So, in essence, through Interface Implementation a Class exposes a functionality to its users that it can do something and it is NOT inheritance.
With almost everything written about interfaces, let me have a shot.
In simple terms, interface is something which will relate two or more , otherwise, non related classes.
Interfaces define contract which ensures that any two or more classes, even if not completely related, happens to implement a common interface, will contain a common set of operations.
Combined with the support of polymorphism , one can use interfaces to write cleaner and dynamic code.
eg.
Interface livingBeings
-- speak() // says anybody who IS a livingBeing need to define how they speak
class dog implements livingBeings
--speak(){bark;} // implementation of speak as a dog
class bird implements livingBeings
--speak(){chirp;}// implementation of speak as a bird
ICalculator myInterface = new JustSomeClass();
JustSomeClass myObject = (JustSomeClass) myInterface;
Now you have both "interfaces" to work with on the object.
I am pretty new to this too, but I like to think of interfaces as buttons on a remote control. When using the ICalculator interface, you only have access to the buttons (functionality) intended by the interface designer. When using the JustSomeClass object reference, you have another set of buttons. But they both point to the same object.
There are many reasons to do this. The one that has been most useful to me is communication between co-workers. If they can agree on an interface (buttons which will be pushed), then one developer can work on implementing the button's functionality and another can write code that uses the buttons.
Hope this helps.

Categories

Resources