public static method + interface - c#

Since we can't define a public static method in the interface, can such an interface be implemented in a class with public static?
public interface IValidator
{
bool IsValid(bool data);
}
public class MyValidator : IValidator
{
public static bool IsValid(string data)
{
//code which returns bool
}
}

No, C# does not allow for static interfaces.
Interfaces are designed to act as contracts between classes, that contract defines that each instance of these classes will have a set of method.
Jon Skeet has given a very good explanation in this question, I'd recommend reading it.

When you have an object instance, it makes sense to cast and use that as an interface. But when you work with static stuff, this isn't the case. You can only access static members through the name of the containing class, you can't pass them around like instances, etc.
It is possible to implement an interface and make sure it's not instantiated multiple times, it's called the singleton pattern. A singleton class is similar to a static class, but it has an instance that can be passed around and it can implement interfaces as well.

No, but you could get something close to it by having a static member return an instance of the interface.
Somthing like:
public class MyValidator : IValidator
{
public bool IsValid(string data)
{
//code which returns bool
}
public static readonly IValidator Instance = new MyValidator();
}
Then you could use it in a static sort of way:
bool isValid = MyValidator.Instance.IsValid("data");

You cannot define static members via the interface, so if static members are required by design they can only be added to concrete types.
This ultimately produces a lot of confusion. Any other implementation would not have that same member. Mocked instances will not have access to that member. And so on.
Solution is to avoid declaring static members. In your particular case, I would object to the very design of the interface. I would prefer to see classes implement some interface like IValidatable:
public interface IValidatable
{
bool IsValid();
}
...
public class SomeBoolClass: IValidatable
{
private bool Data;
public bool IsValid()
{
return this.Data; // i.e. return Data == true
}
}
...
public class SomeStringClass: IValidatable
{
private string Data;
public bool IsValid()
{
return !string.IsNullOrEmpty(this.Data);
}
}
In this way you obtain fully polymorphic validation across all current and future types.
If you insist on having a validator which receives low-level data (such as Boolean or string) to validate, then you are half-way doomed. Suppose that there are two classes which wrap string data. These two classes would normally have to be validated in different ways. But validator would not be able to distinguish which validation algorithm to apply based on input data. Even worse, validator would have to contain all validation logic for all types, existing and those yet to be coded. This means that validator would act as one giant (and inherently incomplete) switch statement.

Related

Alternative to traits

I'm quite new to C# coming from PHP and I have encountered a problem for which traits would be perfect but I understand that C# doesn't support traits. What is the best way to solve this?
In Godot I'd like to make the animation a bit easier on myself by adding a few methods for animation, according to PHP I'd do something like this. The methods can't really be static either.
public trait SpriteAnimator {
public void Animate(string animation)
{
// DO SOMETHING
}
}
public class Actor : KinematicBody2D
{
use SpriteAnimator;
public override void _Ready()
{
Animate("run");
}
}
How would I solve this in C#?
C# does not have anything that is completely analogous to PHP's trait system but some aspects of it can be emulated using interfaces, Extension Methods and occasionally Default Interface Methods.
The simplest usage of trait is to add methods to classes without subclassing. Extension methods allow you to effectively add methods to objects based on their type. Only members that are publicly visible on the targetted type will be accessible in the extension.
public interface INamed
{
string Name { get; }
}
public static class DemoExtensions
{
// This is available on instances of any type
public static void SayHello(this object self)
{
Console.WriteLine("Hello.")
}
// This one will work on instances whose type implements INamed
public static void SayHello(this INamed self)
{
Console.WriteLine($"Hello {self.Name}.");
}
}
Static trait data members are more difficult. While you can define a static field or property in the extension class (DemoExtensions above) the value is shared among all types that the extension method runs on. If you need static values based on the type of object the method is called against then you'll need to handle that manually with a Dictionary<type, ...> static in the extension class.
Another limitation is that extension methods require an object to invoke:
public class MyClass : INamed
{
public string Name { get; }
public MyClass(string name)
{
Name = name;
}
public void DoSomething()
{
this.SayHello();
}
}
Note the this.SayHello(); line in DoSomething. If you take the this. portion away the program will not compile.
Default Interface Methods can also be used as a sort of extension, but you have to force cast the type to the interface before you can access them. No more this.SayHello();, now it's ((INamed)this).SayHello(); and that's not even the worst of it. They have their place but mostly it's not useful to me. Your milage may vary.
As of C#9 there is no way to add extension types other than methods, and I very strongly doubt that we'll get Extension Properties at any point in the future. You'll have to figure your own way around trait properties until that changes.

Should all public methods be declared in the interface?

Given an interface like:
public interface IFoo
{
string Bar();
}
And a class that implements it like:
public class Foo : IFoo
{
public string Bar()
{
returns "Bar";
}
public string SomeOtherMethod()
{
returns "Something else";
}
}
Is there a problem with this code? Should we add all methods to the interface?
One example: imagine a private method that grows complex enough to need unit tests. Could you make it public (so it can be called from the test project) but not add it to the interface (because no clients need to call it)?
If what a class does is simple enough that we can test its public methods and private methods at the same time, then we can just test the public methods.
If the private method grows so complex that between the public and private method we need too many combinations of tests then it's time to separate the private method into its own class. Making the private method public would break the encapsulation of the class. Even if we don't add the method to an interface, making the class method public still adds the method to the public interface of the class itself.
So if we have this:
public class ClassWithComplexPrivateMethod
{
public void DoSomething(int value)
{
PrivateMethodThatNeedsItsOwnTests(value);
}
private string PrivateMethodThatNeedsItsOwnTests(int value)
{
// This method has gotten really complicated!
return value.ToString();
}
}
We might refactor to something like this:
public interface IRepresentsWhatThePrivateMethodDid
{
string MethodThatNeedsItsOwnTests(int value);
}
public class RefactoredClass
{
private readonly IRepresentsWhatThePrivateMethodDid _dependency;
public RefactoredClass(IRepresentsWhatThePrivateMethodDid dependency)
{
_dependency = dependency;
}
public string DoSomething(int value)
{
return _dependency.MethodThatNeedsItsOwnTests(value);
}
}
And now a new class implements IRepresentsWhatThePrivateMethodDid.
Now when we test the refactored class we mock IRepresentsWhatThePrivateMethodDid, and we write separate unit tests for any classes that implement IRepresentsWhatThePrivateMethodDid.
It may seem like a contradiction to say that exposing the private method as public breaks encapsulation, but exposing it as its own separate class doesn't. There are two differences:
The refactored class doesn't depend on the new class containing what used to be the private method. It depends on the new interface.
The interaction between the refactored class and the interface is still hidden within its methods. Other classes that call its public methods don't "know" about how it uses its dependency. (In fact, other classes will likely depend on abstractions instead of directly on the refactored class.)
It's also easy to get carried away with this and introduce the separate dependency too soon, when we could have tested the class - including its private methods - through the public methods. I've done this lots of times, and it can result in lots and lots of unnecessary interfaces and extra classes. There's no perfection, just our best efforts to balance it.
One more thought: We tend to use interfaces to represent dependencies, but we don't have to. If what we're extracting was just a single private method, then perhaps we can represent it with a delegate or a Func instead, like this:
public class RefactoredClass
{
private readonly Func<int, string> _dependency;
public RefactoredClass(Func<int, string> dependency)
{
_dependency = dependency;
}
public string DoSomething(int value)
{
return _dependency(value);
}
}
Or we can use a delegate, which I like better than Func because it indicates what the function does.
Generally when a class implements an interface all members of an interface must be implemented, it does not go the other way around.
Also when implementing an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and parameter signature as the interface member. You can have methods, even public, in the class that are not defined in the interface.
On top of that, the interface itself provides no functionality that a class or struct can inherit in the way that it can inherit base class functionality. However, if a base class implements an interface, any class that's derived from the base class inherits that implementation.
Interface should represent just the required API without regard to unit-testing and smth else.
To test public-methods of class you should do nothing because Test-project has access to them. You just need to instantiate a class and inject all required dependency using Mock.
Example: testing class without any dependencies
Example: testing class with dependency
To test private methods of a class need to make them visible to test-project:
mark private methods as internal
make internal-method visible to test-project: add to AssemblyInfo.cs the directive [assembly: InternalsVisibleTo("Project.Tests")] (see InternalsVisibleToAttribute)

Why can't interfaces specify static methods?

I know this question has been asked over and over, but I can't seem to find good enough answers. So to make it clear what I'm trying to know, I'll split this in two questions:
Why can't interfaces have static method signatures? I'll try to preempt the non-answers asking why in the world I would want to do this with the following: I would want to be able to statically invoke GetDbConnectionType() on SqliteCodeGenerator and MssqlCodeGenerator:
interface ICodeGenerator
{
// this is the method I would like to be static:
string GetDbConnectionType();
}
abstract class CodeGeneratorBase : ICodeGenerator
{
public abstract string GetDbConnectionType();
public void GenerateSomeCode(StringBuilder s)
{
s.AppendLine("var foo = new " + GetDbConnectionType() + "();");
}
}
class SqliteCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SQLiteConnection";
}
}
class MssqlCodeGenerator : CodeGeneratorBase
{
public override string GetDbConnectionType()
{
return "SqlConnection";
}
}
On the other hand, and this is the matter of this second question, if you know of a good alternative to reach the aforementioned goal, then by all means...
Suppose you could specify in an interface that a type had to have a particular static method... how would you call it? Polymorphism works through instances - whereas static members explicitly don't use instances.
Now, having said that, there's one situation in which I can see static interface members working: generic types. For example:
// This isn't valid code...
public void Foo<T>() where T : ICodeGenerator
{
string type = T.GetDbConnectionType();
}
That would call the static member on the concrete type T.
I've blogged more about this, but I suspect the benefit doesn't justify the complexity.
In terms of alternatives - usually you'd have another interface, and have separate types to implement that interface. That works well in some contexts, but not in others.
#JonSkeet: It's possible to create a static interface member in CIL, so I'm afraid your first statement is misleading. I assume it was omitted from C# as a design choice by the Microsoft team to encourage correct usage of interfaces.
The best way to get this functionality is probably with extension methods, these will allow you to add a method to all inheritors of your interface or to a specific implementation of that interface however you need to write a separate class to hold the implementation of the extension method which (if not planned for) can be easy to lose track of.
Jon's answer covers pretty much everything so my answer only includes a possible work around using the .NET configuration API. It requires a bit of syntax overhead but it does give you static access to the instance.
interface IStorage
{
void Store(string item);
}
static class Storage
{
private static readonly IStorage _instance;
static Storage()
{
var storageTypeString = ConfigurationManager.AppSettings["storageTypeString"];
var storageType = Type.GetType(storageTypeString, true);
_instance = (IStorage)Activator.CreateInstance(storageType);
}
public static void Store(string item)
{
_instance.Store(item);
}
}
It might be somewhat helpful if an interface could specify a static class, such that members of that class would be seen by the compiler as static members of that interface. Thus, instead of having to use static class Enumerable<T> to get Enumerable<T>.Default, one could instead syntactically specify IEnumerable<T>.Default.
It would be even more helpful if an interface could specify that some such static methods should be usable in a fashion similar to extension methods, but without the weird scoping rules associated with them (so an interface could appear to offer multiple "convenience" overloads for some member functions without requiring all of the implementations to provide them).
It would be extremely helpful if, combined with such a feature, interface methods could be declared "optional", such that when an implementation provided a method it would be used, and when it did not the extension-ish method would be automatically substituted. This would probably require changes to the CLR, however.
In any case, because interfaces do not include static classes, the best one can do is provide static classes which users of the interface will find helpful, even though the compiler will regard those classes and the interfaces as entirely independent entities.
I know this is old, but actually you can with static functions declared in a static class outside of a name space.
but they way your putting it you would just make the function static in the abstract class
to do it from an interface you do this
public static class Interfacefunction{
public static string GetDbConnectionType(this ICodeGenerator me)
{
// this is the method I would like to be static:
// you can even get access to me
return "SQLiteConnection";
}
}
A sort of workaround (though it may actually be better this way) for this I've decided to use is to use a static instance instead of a static interface.
Rather than:
// does not compile
ISomeInterface {
static void DoSomething();
static bool TestSomething(string pValue);
// etc...
}
static class SomeStaticClass : ISomeInterface {
public static void DoSomething() {
}
public static bool TestSomething(string pValue) {
}
}
Define a class (make it generic if the logic must vary between classes that you use it with):
sealed class SomeClass {
public void DoSomething() {
// reusable implementation
}
public bool TestSomething(string pValue) {
// reusable implementation
}
}
and give a static instance of that class to your static class:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
}
The only issue is that you have to decide whether to expose a property to the static instance:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
public static SomeClass SomeProperty { get { return sSomeClass; } }
}
...
SomeStaticClass.SomeProperty.DoSomething();
if (SomeStaticClass.SomeProperty.TestSomething(someValue))
...
or to wrap its methods:
static class SomeStaticClass {
static readonly SomeClass sSomeClass = new SomeClass();
public static void DoSomething() {
sSomeClass.DoSomething();
}
public static bool TestSomething(string pValue) {
sSomeClass.TestSomething(pValue);
}
}
...
SomeStaticClass.DoSomething();
if (SomeStaticClass.TestSomething(someValue))
...

Interface wonder question

We define interface as below:
interface IMyInterface
{
void MethodToImplement();
}
And impliments as below:
class InterfaceImplementer : IMyInterface
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
instead of creating a interface , why can we use the function directly like below :-)
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
public void MethodToImplement()
{
Console.WriteLine("MethodToImplement() called.");
}
}
Any thoughts?
You are not implementing the interface in the bottom example, you are simply creating an object of InterfaceImplementer
EDIT: In this example an interface is not needed. However, they are extremely useful when trying to write loosely coupled code where you don't have to depend on concrete objects. They are also used to define contracts where anything implementing them has to also implement each method that it defines.
There is lots of information out there, here is just a brief intro http://www.csharp-station.com/Tutorials/Lesson13.aspx
If you really want to understand more about interfaces and how they can help to write good code, I would recommend the Head First Design Patterns book. Amazon Link
instead of creating a interface , why
can we use the function directly like
below
Are you asking what the point of the interface is?
Creating an interface allows you to decouple your program from a specific class, and instead code against an abstraction.
When your class is coded against an interface, classes that use your class can inject whichever class they want that implements this interface. This facilitates unit testing since not-easily-testable modules can be substituted with mocks and stubs.
The purpose of the interface is for some other class to be able to use the type without knowing the specific implementation, so long as that type conforms to a set of methods and properties defined in the interface contract.
public class SomeOtherClass
{
public void DoSomething(IMyInterface something)
{
something.MethodToImplement();
}
}
public class Program
{
public static void Main(string[] args)
{
if(args != null)
new SomeOtherClass().DoSomething(new ImplementationOne());
else
new SomeOtherClass().DoSomething(new ImplementationTwo());
}
}
Your example doesn't really follow that pattern, however; if one that one class implements the interface, then there really isn't much of a point. You can call it either way; it just depends on what kind of object hierarchy you have and what you intend to do for us to say whether using an interface is a good choice or not.
To sum: Both snippets you provide are valid code options. We'd need context to determine which is a 'better' solution.
Interfaces are not required, there is nothing wrong with the last section of code you posted. It is simply a class and you call one of it's public methods. It has no knowledge that an interface exists that this class happens to satisfy.
However, there are advantages:
Multiple Inheritance - A class can only extend one parent class, but can implement any number of interfaces.
Freedom of class use - If your code is written so that it only cares that it has an instance of SomethingI, you are not tied to a specific Something class. If tomorrow you decide that your method should return a class that works differently, it can return SomethingA and any calling code will not need to be changed.
The purpose of interfaces isn't found in instantiating objects, but in referencing them. Consider if your example is changed to this:
static void Main()
{
IMyInterface iImp = new InterfaceImplementer();
iImp.MethodToImplement();
}
Now the iTmp object is of the type IMyInterface. Its specific implementation is InterfaceImplementer, but there may be times where the implementation is unimportant (or unwanted). Consider something like this:
interface IVehicle
{
void MoveForward();
}
class Car : IVehicle
{
public void MoveForward()
{
ApplyGasPedal();
}
private void ApplyGasPedal()
{
// some stuff
}
}
class Bike : IVehicle
{
public void MoveForward()
{
CrankPedals();
}
private void CrankPedals()
{
// some stuff
}
}
Now say you have a method like this somewhere:
void DoSomething(IVehicle)
{
IVehicle.MoveForward();
}
The purpose of the interface becomes more clear here. You can pass any implementation of IVehicle to that method. The implementation doesn't matter, only that it can be referenced by the interface. Otherwise, you'd need a DoSomething() method for each possible implementation, which can get messy fast.
Interfaces make it possible for an object to work with a variety of objects that have no common base type but have certain common abilities. If a number of classes implement IDoSomething, a method can accept a parameter of type IDoSomething, and an object of any of those classes can be passed to it. The method can then use all of the methods and properties applicable to an IDoSomething without having to worry about the actual underlying type of the object.
The point of the interface is to define a contract that your implementing class abides by.
This allows you to program to a specification rather than an implementation.
Imagine we have the following:
public class Dog
{
public string Speak()
{
return "woof!";
}
}
And want to see what he says:
public string MakeSomeNoise(Dog dog)
{
return dog.Speak();
}
We really don't benefit from the Interface, however if we also wanted to be able to see what kind of noise a Cat makes, we would need another MakeSomeNoise() overload that could accept a Cat, however with an interface we can have the following:
public interface IAnimal
{
public string Speak();
}
public class Dog : IAnimal
{
public string Speak()
{
return "woof!";
}
}
public class Cat : IAnimal
{
public string Speak()
{
return "meow!";
}
}
And run them both through:
public string MakeSomeNoise(IAnimal animal)
{
return animal.Speak();
}

multiple classes with same methods - best pattern

I have a few classes in my current project where validation of Email/Website addresses is necessary. The methods to do that are all the same.
I wondered what's the best way to implement this, so I don't need to have these methods copy pasted everywhere?
The classes themselves are not necessarily related, they only have those validation methods in common.
How about adding an interface, and using an extension method?
public interface IFoo { }
public class A : IFoo {}
public class B : IFoo {}
public class C : IFoo {}
public static class FooUtils {
public static void Bar(this IFoo foo) { /* impl */ }
}
That way:
no unnecessary inheritance
no duplication
You might want to put all the validation code into a Validator class, then use that class anywhere that validation is needed. Access to validation should be through a single method, Validate(object Something) maybe. I think this is called "Composition" (as far as design patterns go).
Later on, you can have sub-classes of Validator that maybe more specific or do different kinds of validation.
You could also have all classes requiring validation extend a base class or abstract class that has 90% of the validation in it.
Sounds like you just need a static class with a static method
public static class Utilities{
public static bool validEmail(string email)
{
//Your code here
}
}
Yes, duplicating this code would be a bad smell, you can extract these methods to single Helper class in static methods or you can define a "Validator" interface class and using this interface, you can link different validation methods with chain of responsibility pattern.
Create a Utility class and define these methods as extension methods for appropriate class/interfaces.
You really need to take a good look at the aspect oriented programming methodology (AoP). The Enterprise Library 4.1 has an AoP implementation called Unity Interception.
http://msdn.microsoft.com/en-us/library/dd140045.aspx
This framework allows you to code a single handler class for the email validation. So what this entails is that the validation code goes into a handler class, and no longer part of the class(es). Next thing you do is mark the classes for interception.
You can intercept the classes in a variety of ways, including setting an attribute on the desired method that should be intercepted and handled per your requirements. Setting an attribute is probably the easiest way to do an interception.
create validation logic classes and interfaces, and have them being injected in your code... so seperate the logic from validation so that it can be reused...
Create Email as a separate class.
Use Email as properties/parameters/return values in your classes instead of String.
Create EmailValidator to validate strings as email addresses.
Create EmailFactory that returns Email when passed a valid email address and null if not.
(Do same for Website).
I would recommend you create an IValidator interface then create multiple different validators that handle different scenarios. Here's one example:
public interface IValidator {
bool CanValidateType(string type);
bool Validate(string input);
}
The CanValidateType() method could be a bit more complex, but I hope you get the idea. It basically identifies whether the validator can handle the input supplied. Here are a couple implementations:
public class UrlValidator : IValidator {
bool CanValidateType(string type) {
return type.ToLower() == "url";
}
bool Validate(string input) {
/* Validate Url */
}
}
public class EmailValidator : IValidator {
bool CanValidateType(string type) {
return type.ToLower() == "email";
}
bool Validate(string input) {
/* Validate Email */
}
}
Now you will use constructor injection to inject the dependency into your class:
public class SomeSimpleClass {
private IValidator validator;
public SomeComplexClass(IValidator validator) {
this.validator = validator;
}
public void DoSomething(string url) {
if (validator.CanValidateType("url") &&
validator.Validate(url))
/* Do something */
}
}
The CanValidateType comes in handy when you have a class that can use multiple validators. In this scenario you pass in a list or an array of validators to the constructor.
public class SomeComplexClass {
private List<IValidator> validators;
public SomeComplexClass (List<IValidator> validators) {
this.validators = validators;
}
public bool ValidateUrl(string url) {
foreach (IValidator validator in this.validators)
if (validator.CanValidateType("url"))
return validator.Validate(url);
return false;
}
public bool ValidateEmail(string email) {
foreach (IValidator validator in this.validators)
if (validator.CanValidateType("email"))
return validator.Validate(email);
return false;
}
}
You would then have to pass in the required instance of the validator(s) to your classes somehow. This is often done with an IoC container (like Castle Windsor) or do it yourself.
IValidator emailValidator = new EmailValidator();
IValidator urlValidator = new UrlValidator();
SomeSimpleClass simple = new SomeSimpleClass(urlValidator);
SomeComplexClass complex = new SomeComplexClass(new List<IValidator> { emailValidator, urlValidator });
The above code gets tedious to do on your own, this is why IoC containers are so handy. With an IoC container you can do something like the following:
SomeSimpleClass simple = container.Resolve<SomeSimpleClass>();
SomeComplexClass complex = container.Resolve<SomeComplexClass();
All the mapping of interfaces is done in your app.config or web.config.
Here's an awesome tutorial on Dependency Injection and The Castle Windsor IoC container.

Categories