I'm making a game in Unity C# using a Singleton GameManager and I was warned that using references of the class in other scripts like GameManager.instance.someVar makes the code fragile and difficult for later edit. So I looked for how to access a singleton with interfaces but haven't found what I was after. As I wish to code properly, I would like someone to point me to a decent source that tells me how to do so, or have him/her tell me in brief.
Well there is a general solution to this, I am not sure how feasible it will be for you.
Suppose we have a true singleton:
public static class Highlander //cos, there can be only one. Sorry. couldn't resist
{
public static void Quicken(string name)
{
Console.WriteLine("{0} gets their quickening on",name);
}
}
Suppose we want to be able to pass this around in an abstract manner, using Interfaces.
public interface IImmortal
{
void Quicken();
}
Well, you cannot implement an interface on a static class or member, so how do you pass references to this class around by interface?
Simple - create a wrapper/adapter class which implements the interface you want:
public class McLeod: IImortal
{
public void Quicken()
{
Highlander.Quicken("Conor");
}
}
public class Kurgen: IImortal
{
public void Quicken()
{
Highlander.Quicken("The Kurgen");
}
}
Now you can pass IImortal around, and the wrapping implementation(s) simply call through to the Singleton. Note how the Wrapper can supply data to the Singleton from within itself, as above, in which case it's more like an Adapter. But the concept is the same.
In the case of Unity, I don't know if this will suit, since the GameManager class likely exposes a ton of other properties and methods you would also have to wrap/adapt - it may not be worth creating wrapper interfaces for all of this, so consider perhaps that in this case you need to embrace it :)
Singletons, being static, dont support interfaces. Perhaps your other source might mean that you should use a Factory pattern or perhaps an Inversion of Control (IOC) method. In those cases the Factory would look like GameManagerFactory.GetGameInstance() rather than refer to the Instance static property of a GameManager.
The true limitation of Singlton programming is in the area of unit testing - because your code is bound directly to the specific class "GameManager" you could not replace it in a unit test with another "test version" of the GameManager. To support unit testing you should try to make sure that any significant classes your code depends on could be replaced by a test version of a class, without your code caring. When using Singletons this is hard (if not impossible) to do.
Usually I tend to create an empty GameObject, give it a proper name or a tag and attach a script component to it.
This way I can easily get a reference in any other GameObject that might need it and retrieve the script component from it.
Related
Don't have much experience with testing, trying to change that by testing libraries I've made recently.
Using nunit with nsubstitute for this.
So the situation I have is a class like this:
class MyClassToTest {
private ISomeOtherClass MyPrivateClass { get;set }
public MyClassToTest() {
MyPrivateClass = new SomeOtherClass();
}
public void DoSomething() {
MyPrivateClass.SayHello();
}
}
Now, a test for the DoSomething method would be to see if the method SayHello() was actually called on the ISomeOtherClass instance.
The problem is that it's private, when looking up the best way to test this, the only thing that came up was to make the property internal and set the InternalsVisibleToAttribute to the assembly the tests are in.
While this solution works and the external interface for my library is still ok, the correct accessor for this property in the context of the library would still be private.
The test I'd write is after making it interal:
public void MyTest() {
var objPrivateClass = Substitute.For<ISomeOtherClass>();
var obj = new MyClassToTest();
obj.MyPrivateClass = objPrivateClass;
obj.DoSomething();
objPrivateClass.Received().SayHello();
}
Is there a better way to test this without me having to modify my original code to make it testable?
It might be setting InternalsVisibleToAttribute and making the property internal is the correct thing here, but a couple of hours ago I didn't know about the existence of InternalsVisibleToAttribute so thought it best to ask :)
To answer the exact question, You can use reflection to reach private members, but that is a fragile and rather slow solution.
The best advice I can give you is that private things should stay private; test an object's behavior through its public interface. So if is too big and hard to test, just refactor it to be testable. Think of the Single Responsibility Principle and the Inversion of Control principles.
Edit 1.: You are probably looking for the concept of Dependency Injection. This should be alright most of the times; however when we talk about highly reusable libraries (you mentioned you are making a lib), other solutions may fit better for the users of your library (e.g. creating a Facade or rethinking your design).
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to Use Static Classes in C#
I will write code in which I need class which holds methods only. I thought it is good idea to make class static. Some senior programmer argue that do not use static class. I do not find any good reason why not to use static class. Can someone knows in C# language there is any harm in using static class. Can static class usage required more memory than creating object of class? I will clear that my class do not have single field and hence property too.
For further information I will explain code also.
We have product in which we need to done XML handling for chart settings. We read object from XML file in class Library which holds chart related properties. Now I have two Layers first is product second class Library and XML related operations. Actually senior programmers want independent class to read and write XML. I make this class static.
In another situation I have class of chartData. In that class I want methods like whether Line of Axis,series of chart is valid or not. Also whether color of chart stores in ARGB format or plain color name. They do not want those methods in same project. Now can I make class static or create object.
If your class does not have to manage state then there is absolutely no reason to not declare it static.
In C# some classes even have to be static like the ones that have extension methods.
Now if there's a chance that it requires state in the future, it's better to not declare it as static as if you change it afterwards, the consumers will need to change their code too.
One concern is that statics can be harder (not impossible) to test in some situations
The danger of static classes is that they often become God Objects. They know too much, they do too much, and they're usually called "Utilities.cs".
Also, just because your class holds methods only doesn't mean that you can't use a regular class, but it depends on what your class does. Does it have any state? Does it persist any data that's being modified in your methods?
Having static classes is not bad, but could make you think why you have those methods there. Some things to keep in mind about that:
if the methods manage behavior for classes you have in your project, you could just add the methods to those classes directly:
//doing this:
if(product.IsValid()) { ... }
//instead of:
if(ProductHelper.IsValid(product)) { ... }
if the methods manage behavior for classes you can't modify, you could use extension methods (that by the end of the day are static! but it adds syntactic sugar)
public static bool IsValid( this Product product ) { ... }
//so you can do:
if(product.IsValid()) { ... }
if the methods are coupled to external services you may want to mock, using a non-static class with virtual methods or implementing an interface will let you replace the instance with a mock one whenever you need to use it:
//instead of:
StaticService.Save(product);
//you can do:
public IService Service {get;set;}
...
Service.Save(product);
//and in your tests:
yourObject.Service = new MockService(); //MockService inherits from your actual class or implements the same IService interface
by the other hand, having the logic in non-static classes will let you make use of polymorphism and replace the instance with another one that extends the behavior.
finally, having the logic in non-static classes will let you use IoC (inversion of control) and proxy-based AOP. If you don't know about that, you could take a look at frameworks like Spring.net, Unity, Castle, Ninject, etc. Just for giving you an example of what you could do with this: you can make all the classes implementing IService log their methods, or check some security constraints, or open a database connection and close it when the method ends; everything without adding the actual code to the class.
Hope it helps.
It depends on the situation when to use static classes or not. In the general case you create static classes when you do not need to manage state. So for example, Math.cs, or Utility.cs - where you have basic utility functions - eg string formatting, etc.
Another scenario where you want to use static is when you expect the class to not be modified alot. When the system grows and you find that you have to modify this static class alot then its best to remove the static keyword. If not then you will miss out on some benefits of OOD - eg polymorphism, interfaces - For example you could find that I need to change a specific method in a static class, but since you can't override a static method, then you might have to 'copy and paste' with minor changes.
Some senior programmer argue that do not use static class.
Tell him he is a traineee, not even a junior. Simple. The static keyword is there for a reason. if your class only has methods without keeping state - and those cases exist - then putting them into a static class is valid. Point.
Can someone knows in C# language there is any harm in using static class.
No. The only valid argument is that your design isbroken (i.e. the class should not be static and keep state). But if you really have methods that do not keep state - and those cases exist, like the "Math" class - then sorry, this is a totally valid approach. There are no negatives.
I'm doing some internal domain-specific library development at the moment, and incidentally the stuff i'm trying to model mimicks "class" and "object" relations fairly well. So objects of my C# class MyClass should sort of act like a domain specific class for objects of my C# class MyObject who play the part of object or instance. Now I would like the code in MyObject to access methods of MyClass, which should not be accessible to other classes/code in the project. Any ideas how to enforce this, asside from documenting it at hoping my fellow developers will respect this.
I hope I made my question clear enough, otherwise let me know.
Best regards!
You could always split MyClass and MyObject up into another project, and define MyClass and/or MyObject as an internal class. That way it can only be accessed by other objects in that assembly.
See: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
The standard approach here is to declare the members internal and make sure MyClass and MyObject are part of the same assembly. That assembly should contain little else.
Additional: This is the tool that was designed for this purpose. Other languages have other means to fine-tune accessibility (C++: friend) but in .NET a simpler model was chosen.
And you don't have to take the 'nothing else' so strictly, the 2 classes could share an assembly with other related classes. you would then have to verify the no-access rule(s) manually inside that library.
I'd suggest a private nested class. That way, even if your fellow devs are writing code in the same namespace, they'll never be able to access the class.
Once the class declaration is fully enclosed within another class declaration, the class is considered nested and can only be accessed through the containing class.
Pehaps your MyObject should descend from MyClass and declare the methods in MyClas as protected.
If you don't want your consumers to invoke certain implementation specific methods you could try abstracting to interfaces or abstract base classes. That way the consumer will only 'see' the properties and methods you want them to see.
You do not have to use inheritance to provide shared functionality and you do not have to rely on member accesibility to prevent others from using methods you'd rather not expose.
For example:
public interface IDomainSpecific
{
void DoStuff();
}
public interface IDomainService
{
void HelpMeDoStuff();
}
public class DomainObject1 : IDomainSpecific
{
private readonly IDomainService _service;
public DomainObject1( IDomainService service )
{
_service = service;
}
public DoStuff()
{
// Do domain specific stuff here
// and use the service to help
_service.HelpMeDoStuff();
}
}
This uses classic constructor injection and works best when you already use dependency injection in your application, though it works perfectly well with factories as well.
The point is to keep responsibilities crystal clear. There's no chance of anybody invoking anything they shouldn't because the 'DomainObject' never knows what concrete type implements the shared service. The shared service is not exposed on the domain object either. The added bonus is testability and the possibility of swapping the service with another implementation without ever needing to touch the DomainObject.
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.
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
public interface ICut
{
void Cut();
}
public class Knife : ICut
{
void ICut.Cut()
{
//Cut Something
}
}
And to use the Knife object:
ICut obj = new Knife();
obj.Cut();
Would you recommend this method of interface implementation? Why or why not?
EDIT:
Also, given that I am using an explicit interface the following would NOT work.
Knife obj = new Knife();
obj.Cut();
To quote GoF chapter 1:
"Program to an interface, not an implementation".
"Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)
ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
I've only used it in scenarios where I want to restrict access to certain methods.
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
return "";
}
void IWriter.Write(string message)
{
// Implementation
}
}
public class Foo
{
readonly MessageLog _messageLog;
IWriter _messageWriter;
public Foo()
{
_messageLog = new MessageLog();
_messageWriter = _messageLog;
}
public IReader Messages
{
get { return _messageLog; }
}
}
Now Foo can write messages to it's message log using _messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.
Yes. And not just for testing. It makes sense to factor common behaviour into an interface (or abstract class); that way you can make use of polymorphism.
public class Sword: ICut
{
void ICut.Cut()
{
//Cut Something
}
}
Factory could return a type of sharp implement!:
ICut obj = SharpImplementFactory();
obj.Cut();
This is a bad idea because their usage breaks polymorphism. The type of the reference used should NOT vary the behavior of the object. If you want to ensure loose coupling, make the classes internal and use a DI technology (such as Spring.Net).
There are no doubt certain advantages to forcing the users of your code to cast your objects to the interface types you want them to be using.
But, on the whole, programming to an interface is a methodology or process issue. Programming to an interface is not going to be achieved merely by making your code annoying to the user.
Using interfaces in this method does not, in and of itself, lead to decoupled code. If this is all you do, it just adds another layer of obfuscation and probably makes this more confusing later on.
However, if you combine interface based programming with Inversion of Control and Dependency Injection, then you are really getting somewhere. You can also make use of Mock Objects for Unit Testing with this type of setup if you are into Test Driven Development.
However, IOC, DI and TDD are all major topics in and of themselves, and entire books have been written on each of those subjects. Hopefully this will give you a jumping off point of things you can research.
Well there is an organizational advantage. You can encapsulate your ICuttingSurface, ICut and related functionality into an Assembly that is self-contained and unit testable. Any implementations of the ICut interface are easily Mockable and can be made to be dependant upon only the ICut interface and not actual implementations which makes for a more modular and clean system.
Also this helps keep the inheritance more simplified and gives you more flexibility to use polymoprhism.
Allowing only callers expecting to explicit interface type ensures methods are only visible in the context they are needed in.
Consider a logical entity in a game and u decide that instead of a class responsibile for drawing/ticking the entities you want the code for tick/draw to be in the entity.
implement IDrawable.draw() and ITickable.tick() ensures an entity can only ever be drawn/ticked when the game expects it to. Otherwise these methods wont ever be visible.
Lesser bonus is when implementing multiple interfaces, explicit implementations let you work around cases where two interface method names collide.
Another potential scenario for explicitly implementing an interface is when dealing with an existing class that already implements the functionality, but uses a different method name. For example, if your Knife class already had a method called Slice, you could implement the interface this way:
public class Knife : ICut
{
public void Slice()
{
// slice something
}
void ICut.Cut()
{
Slice();
}
}
If the client code doesn't care about anything other than the fact that it can use the object to Cut() things, then use ICut.
Yes, but not necessarily for the given reasons.
An example:
On my current project, we are building a tool for data entry. We have certain functions that are used by all (or almost all) tabs, and we are coding a single page (the project is web-based) to contain all of the data entry controls.
This page has navigation on it, and buttons to interact with all the common actions.
By defining an interface (IDataEntry) that implements methods for each of the functions, and implementing that interface on each of the controls, we can have the aspx page fire public methods on the user controls which do the actual data entry.
By defining a strict set of interaction methods (such as your 'cut' method in the example) Interfaces allow you to take an object (be it a business object, a web control, or what have you) and work with it in a defined way.
For your example, you could call cut on any ICut object, be it a knife, a saw, a blowtorch, or mono filament wire.
For testing purposes, I think interfaces are also good. If you define tests based around the expected functionality of the interface, you can define objects as described and test them. This is a very high-level test, but it still ensures functionality. HOWEVER, this should not replace unit testing of the individual object methods...it does no good to know that 'obj.Cut' resulted in a cutting if it resulted in the wrong thing being cut, or in the wrong place.