Using Interfaces vs. Func or Action [closed] - c#

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have been writing C# code for 10 years, but I am woefully weak on knowing exactly when to use an interface vs. using a Func or Action. It seems to me that in many places where a method on an interface is called, a Func or Action would work just as well. So, I guess my question is this. If I have an interface with just a single method, or perhaps a couple methods, is there any disadvantage to using a Func or Action instead? Using a Func or Action seems cleaner to me.
Thanks very much.

I guess you can compare an Action or Func with an interface containing one method, with the difference that you can supply any Action or Func that meets the parameter / return value requirements, where when using interfaces, the supplied object must implement that interface.
Perhaps you could call Action and Func "anonymous single method interfaces".
If you look at the design perspective though, your class model would be a drawing of blocks without any lines between them.

You should use delegates and lambda expressions if the implementations are expected to be very short (one or two lines), and especially if the implementations are expected to need local variables (closures).

I have to admit, I was a bit confused by this question. Like #deepee, I agree that a code example would have been good here to show why you think you would use one approach over the other.
The reason for my confusion is that I wouldn't have thought to ask this question since they serve different purposes. Interfaces are used mainly for polymorphism; so that one can treat different implementations all in the same way.
Jon Skeet has a good example of using Func and Action.
Interfaces allow you to do this:
IAnimal animal = AnimalFactory.GetAnimal();
animal.Run();
Using the above code, you don't know or care what kind of animal it is. You just know it can run and you want it to run. More importantly, the caller doesn't know how the animal runs. That's the difference between an Action and interfaces/polymorphism. The logic for doing something is in the concrete class.
An Action will allow you to do the same thing for each instance, when the actual logic is known by the caller, instead of having each concrete instance do something:
animals.ForEach(x => x.Run());
Or:
animals.ForEach(x => /* do something completely different here */);
The above line of code is action that only the caller decides what should happen, instead of delegating the logic to the actual instance by simply calling a method on it.
They solve different problems, so I'm curious to see how folks think they're interchangeable in certain situations.

You would use an Interface when you don't really care what kind of object you're working with...
Let's go with the textbook example
public class Animal;
public class Dog : Animal, IRunningAnimal { }
public class Cheetah : Animal, IRunningAnimal { }
public class Fish : Animal, ISwimmingAnimal { }
public class Gator : Animal, ISwimmingAnimal, IRunningAnimal { }
public interface IRunningAnimal
{
public void Run();
}
public interface ISwimmingAnimal
{
public void Swim();
}
public abstract class Animal
{
/// ...
public abstract void Move();
}
then somewhere in code...
RunningAnimal runner = getAnimal();
//make him run
runner.Run();
each running animal might run in a different way but they all can run.
or better
if(getAnimal() instanceof RunningAnimal) getAnimal().Run();
else getAnimal().Move();

Related

Should a concrete class that implements an interface have extra public methods for testing? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
When implementing an interface on a concrete class, is it appropriate to have extra public methods exposed to help facilitate unit tests?
For example, let's say I have the following concrete class:
public class MyClass : IMyInterface
{
public int InterfaceMethod(ComplexObject complexObject)
{
return NonInterfaceMethodOne(complexObject)
+ NonInterfaceMethodTwo(complexObject);
}
public int NonInterfaceMethodOne(ComplexObject complexObject)
{
//Do complex logic that needs to be unit tested
}
public int NonInterfaceMethodTwo(ComplexObject complexObject)
{
//Do more complex logic that needs to be unit tested
}
}
If I wrote my class this way, I could have unit tests for both non-interface methods, but I feel like this pattern is not correct. Is there a better way?
What you have there looks perfectly acceptable to me. A general answer to your question is "it depends," because there could be scenarios where you want to hide those methods, and there could be scenarios where you want to expose them.
It's reasonable to consider your test suite as the first client of your code base, and it makes sense to support the needs of your client--you would still want to give careful consideration to what functionality you want to expose and hide.
In spite of the fact that NonInterfaceMethodOne and NonInterfaceMethodTwo are both public, if you inject this implementation into a parameter of the interface type, the client will still only have access to the interface method and will have no knowledge of the other 2 methods.
A client that is using the implementation will of course have access to all 3 methods, but will still not know how the interface method is implemented.
If it would be useful to expose those methods for unit testing and if you can determine that no damage is done by keeping the methods public, then keep them public.
But, it could still be appropriate to write your tests to ensure that NonInterfaceMethodOne and NonInterfaceMethodTwo work the way you want, then cover your interface method with another test(s), and then you may possibly no longer have a need for the unit tests covering NonInterfaceMethodOne and NonInterfaceMethodTwo--in which case you could remove these tests, and then make NonInterfaceMethodOne and NonInterfaceMethodTwo private--because your unit test(s) covering the interface method covers the other 2 methods.
and if you find that this approach doesn't hide any functionality that your test suite needs, I would lean toward this approach, because it's normally good to limit the functionality you expose
You can get something similar to this, but without having to make the members public, by using the InternalsVisibleToAttribute.
Let's say your assemblies/projects are named ProductCode.dll and TestFixtures.dll. You can make the internal types and members in ProductCode.dll visible to TestFixtures.dll, but no other assemblies, by declaring the following in the ProductCode project (typically in AssemblyInfo.cs):
[assembly: InternalsVisibleTo("TestFixtures")]
Then you can declare these exposed-for-testing-only methods as internal instead of public, but the unit tests can still call them.
If you only run your tests in a Debug configuration, not in the Release configuration, you can make this access control exemption only happen in the Debug configuration by surrounding the attribute like this:
#if DEBUG
[assembly: InternalsVisibleTo("TestFixtures")]
#endif

Is it possible to define valid C# interface that cannot be implemented? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I'm thinking about this (meta) question for couple of days already:
Is it possible to define valid C# interface, that cannot be implemented in any way?
Possible variations of this question: Is it possible to define such interface in C# 2.0, 3.0, 4.0, 5.0? Is it possible to define such interface that would not even compile when implemented, or that would compile but throw runtime exception?
Edit: I know such interface will be useless just by definition, but is a nice answer for lectures or testing applicants for a programming job how good they know C#.
Is it possible to define valid C# interface that cannot be implemented?
This trivia question is not a good fit for StackOverflow, but what the heck, it is easily answered. (Wrongly, as it turns out! Read on!)
class C
{
private C() {}
}
interface IFoo<T> where T : C, new()
{
}
IFoo<T> cannot be implemented for any T because there is no type argument that can be substituted for T. C doesn't work because C does not have a public parameterless constructor, and there can be no derived class of C because the default constructor is private. (Well, there could be an accessible derived class of C inside C, but there isn't in this case.)
UPDATE: Commenter "mike z" correctly points out that
class X<T> : IFoo<T> where T : C, new() {}
implements the interface, though of course now there is no way to instantiate X<T>!
Even better, user "GranBurguesa" points out that a derived class of C is permitted to be declared, just so long as it never calls the private constructor; this is only possible if it crashes and dies on instantiation. (Well, to be picky, it would also be permitted for the recursive calls to be optimized down to an infinite loop instead of a crash.)
Both devious workarounds pose a philosophical question: if an interface is implemented by a class no one can instantiate, is it really implemented? Of course GranBurguesa demonstrates that IFoo<D> can be implemented and constructed, so my answer is actually wrong.
There are also cases, such as the one hinted at in SLaks' deleted answer, in which an abuse of the generic mechanism leads to an "infinitary" type. Such types are not legal in the CLR; the C# design team has considered adding similar language to the C# compiler spec but hasn't gotten around to it yet. Use of these types can crash the compiler or the runtime.
For an example of an infinitary type that crashes the compiler, see my article:
To Infinity But Not Beyond
Here's one. Cut n paste this code into Visual Studio and you'll see that this interface cannot be implemented:
interface ΙAmAPerfectlyOrdinaryInterface { }
class C : IAmAPerfectlyOrdinaryInterface { }
As long as we're talking trivia, I think this is a valid implementation of Eric Lippert's attempt:
class Program
{
static void Main(string[] args)
{
D test = new D();
}
}
class C
{
private C() { }
}
interface IFoo<T> where T : C, new() { }
class D : C
{
public D()
: this(5) { }
public D(int x)
: this() { }
}
class Dfoo : IFoo<D> { }
It compiles fine but crashes with a StackOverflowException when you instantiate D.
If you're trying to factor out an old interface you could mark the interface with the ObsoleteAttribute attribute.
Edit: as #Magnus noted in the comments, if you set the Error attribute to true it's usage will cause an error.
If a type is accessible and unsealed, it will be possible for outside code to create instances of that type and there isn't really anything the base type can do about it. No "full trust" or Reflection required.
public class CantDeriveMe
{
private CantDeriveMe()
{
}
public override string ToString()
{
return "My type is " + this.GetType().ToString();
}
}
public class OhYeah : CantDeriveMe
{
static OhYeah CapturedInstance;
~OhYeah()
{
CapturedInstance = this;
}
OhYeah() : this(1/String.Empty.Length)
{
}
OhYeah(int blah) : this()
{
}
public static OhYeah Create()
{
try
{
new OhYeah(4);
}
catch (DivideByZeroException)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return CapturedInstance;
}
public static void test()
{
OhYeah it;
it = OhYeah.Create();
Console.WriteLine("Result was ({0})", it);
}
}
Note that if code is written only in C#, a base-class destructor might squawk if it notices that the object isn't of a legitimate type, but code written in languages other than C# would allow the override of Finalize to exit without chaining to its parent.
I think it's possible to specify an open generic interface with a combination of struct and class constraints which no combination of types could possibly fulfill, e.g.
public interface evil<T, U>
where T : struct,U
where U : class
I'm not sure whether such an open-generic type would really qualify as an "interface", though, or whether only closed generic types can really qualify as interfaces (or classes, or structs).

Naming conventions in C# - Global Variables [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a debate/opinion about using this keyword or underscore in regards to private fields/properties (and I'll mention, I'm stuck on .NET 2.0)
Personally, I prefer this, but there are times you can't use it, for example when you need to reference a global variable from within a static method. Well, then we are forced to use the underscore (assuming we only have 2 choices, this or underscore). This means if my class uses any static methods I can't use this throughout the document.
Now, I've read the naming guidelines and used StyleCop, both would rather I don't use the underscore, but my Resharper pretty much insists on using _.
I don't feel it is right to have one class use the _ and the next class use this simply to accommodate for when the classes mixes non-static and static methods! The advice here on SO is to keep to one implementation/style but I don't know if that means I should ignore Microsoft (and I know MS don't always follow their own rules)!
It has been suggested to prefix with something else, similarish to Hungarian but prefix with globVariableName where glob indicates global. I hate this idea, it's too bespoke and won't be obvious to any other developer outside my team.
So, my question is, what is the best way to define global variables consistently? Since they are naming guides, may be I can just ignore (at least _ can be used consistently but it feels wrong to ignore the advice from the language creators).
Just use the class name in the same way you'd use "this", in a static class. Example follows:
public static class MyStatic
{
public static object Global;
public static void SomeMethod()
{
var theGlobal = MyStatic.Global;
}
}
public class MyNonStatic
{
public object Global;
public void SomeMethod()
{
var theGlobal = this.Global;
}
}
Note: I can't actually think of any other way to do it.
By global variables, I assume you mean const or static fields
I thing StyleCop used to encourage you to use ClassName.staticField for static and const fields, but it seems to have dropped that rule, at least by default. That is still a nice way to do it though.
Also, you can configure Resharper to play nicely with StyleCop.
I always use underscore for both static and instance variables.
For instance variables i use this.variable
For static variables i , sometimes, prefix them with the name of class, e.g., ClassName.variable
this is just my personal opinion;
I believe using this for every private variable is very useful; it has a positive effect on readability of the code. Also, when you are employing some DI constructor injection method, it enables you to use same variable without any confusion, which seems very proper.
public void SomeMethod(int someVariable)
{
this.someVariable = someVariable;
}
I prefer this instead of underscore; underscore seems pretty at first glance; but refering to the previous examples it has negative effect on readability.
I name static variables with the same way I name class variables; usage of this keyword lowers the risk of confusion between private and static variables.

Separate class for enums? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the general consensus towards a separate class in the business layer to store the definition of enums? Is this bad practice? Does this conform to good n-tier design? At the moment my enum definitions are dotted around different, what I would deem as, relevant classes - but I feel as though they should be in one place. Is this, in fact, a subjective question and relative to how I've structured the rest of the solution?
I don't really understand why you would place an enum in a class - perhaps you meant file?
Personally I have a separate file for each enum with the name of the enum.
I place this file close to where the enum is being used and namespace it accordingly.
If an enum is to be shared across assemblies/namespaces, I will use the lowest shared namespace, so it is visible to the using namespaces.
Having enums close to where they are used will make separating code out into projects that little bit easier (if needed).
I don't see the point in having them all in one file - navigation wise, Visual Studio has more than enough navigation capabilities that this is not needed.
Keeping enums in separate class
In this case you're tossing unrelated definitions into one class, for almost no benefits.
Defining enum as nested type for class it relates to
When you hold enums within a class, you may run into naming troubles:
class Foo
{
public enum SomeType { /* ... */ }
public SomeType SomeType { get; set; }
}
This would give an error that SomeType is already defined.
It probably just boils to personal taste, but most often I put my enums along with the class that they are related to, without nesting them:
public enum SomeType { }
public class Foo { }
I was tempted many times to have them nested (we're talking about public enums of course), but the naming issues weren't worth it, for example:
class Foo
{
public enum Enumeration { }
}
Then I can use such enum outside of Foo class, as: Foo.Enumeration, but following declaration (in same namespace):
enum FooEnumeration { }
class Foo { }
gives similar result as you just don't have to type '.' when you are referencing enum: FooEnumeration. Moreover, the latter allows you for this:
class Foo
{
public FooEnumeration Enumeration { get; set; }
}
which would cause aforementioned naming conflicts in previous case.
Summary
When using IDE with powerful GoTo capabilities, it seems to me that naming issues are far more important than 'physical' localization of the enum definition.
I would prefer having separate classes for all constants and Enums in my projects.It improves readability of the code. You should do it especially if you have a Comman proj you are referencing in your business layer and other layers. But if you'd be adding unnecessary references just for the sake of a Constant/Enum class then having them inside the same project makes more sense.
public class Enumerations
{
public enum Gender{
Male = 0,
Female = 1,
Unknown = 2
}
}
And when you consume you could do it like
GetPerson(Enumeration.Gender gender)
{
}

C#: Preferred pattern for functions requiring arguments that implement two interfaces [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
The argument to my function f() must implement two different interfaces that are not related to each other by inheritance, IFoo and IBar. I know of two different ways of doing this. The first is to declare an empty interface that inherits from both:
public interface IFooBar : IFoo, IBar
{
// nothing to see here
}
public int f(IFooBar arg)
{
// etc.
}
This, of course, requires that the classes declare themselves as implementing IFooBar rather than IFoo and IBar separately.
The second way is to make f() generic with a constraint:
public int f<T>(T arg) where T : IFoo, IBar
{
// etc.
}
Which of these do you prefer, and why? Are there any non-obvious advantages or disadvantages to each?
The second option is more flexible. By introducing a new interface, you're forcing classes to implement a third interface, which will only be possible if they have a reference to your library (where the interface is defined).
By using generic constraints, the class only needs a reference to the library containing IFoo and IBar, and not IFooBar.
The first way you mentioned by creating a super interface appeals OO code because it allows one to express a class as the combined interfaces and interact with it as such.
Since there is a need for such expression, why not make it official and tie the knot by making it a super interface and having it documented for possible future maintenance. IMHO

Categories

Resources