Difference between IQueryable and Queryable - c#

I haven't quite got my head around interfaces so thought I'd word the question in a way that'd help me better understand it.
I'm following a tutorial which has had me make an IQueryable. Why couldn't I just make a Queryable?

Queryable is just a static class that contains extension methods to the IQueryable<T> interface. You wouldn't use Queryable directly in your code but rather invoke its methods given an IQueryable<T> instance.

Queryable is a static class that provides some convenient and useful methods to anything implementing IQueryable. You can't make it because it's already made. You need to make a new class that actually does what you want it to do, and implement IQueryable so other code written to use IQueryable (including Queryable) knows how to use it.

An interface is a contract that defines methods and properties, but there is no implementation in an interface.
A class implements the interface by supplying implementation for everything that is defined in the interface.
As an interface has no implementation, you can't create an instance of one. You have to create an instance of a class that implements the interface.
However, you can have a reference of the interface type, but it will point to an actual object. When you use the interface reference, you can use everything that is defined in the interface, but if the class contains more methods, you can't reach them without casting the reference to the actual class.

An interface does not imply how the class will be coded, only how the interaction with that class will be defined.
There may be many different implementations of a class that can query but that's unimportant as long as the interaction with all of those classes is the same.

Related

Handling differences between objects inheriting from an interface

I have 2 objects that inherit from an interface i created which worked nicely. The Objects are injected into another object calls the methods of both the object. The methods of the objects perform some simple XML manipulation which is then returned to the worker object.
I now have a change request which affects one object that inherits from the interface but not the other and I'm at a loss as to how I should handle this. I've created a couple of new methods and I simply throw a not implemented exception if its not used. This doesn't seem "Best Practice" to me. What is the best way to handle this scenario?
I think that this is a situation where the Interface Segregation Principle comes in place.
If you find yourself having two objects for which it does not make sense to expose the same set of public members, then probably they should not implement the same interface. Or at least not only the same interface. You have two options here, depending on your application's logic:
Leave the original interface as is, and the first class (the one not needing extra methods) unmodified. Define a new interface only for the new methods, and make the second class implement both interfaces.
Define a new interface that inherits from the old one and contains the new methods. Leave your first class unmodified, and have your second class implement the new interface.
Implementing an interface and doing nothing more than throwing an exception in some methods is indeed a bad practice, as it breaks the Liskov substitution principle.
An interface doesn't "need" to be fully implemented... Even in .NET there are classes that implement partially an interface (and that throw NotSupportedException() when used in an "illegal" way)... For example arrays are IList<> that don't support Add() or Remove()...
Or the Stream abstract class, that has an additional "pattern": CanRead, CanWrite, CanSeek, ..., so there are methods, and properties that tell if it is legal to use those methods.
Another way is to use an additional interface, and try casting it with as operator. The Entity Framework for example "returns" IQueryable<T>, that "are" IEnumerable<T>... But those objects even support the IDbAsyncEnumerable<T> interface... but not all the IQueryable<T> are IDbAsyncEnumerable<T>. You have to do a cast and see if the interface is present or not.
You could extend the interface like this:
public interface SimpleInterface
{
void SimpleMethod();
void OtherMethod();
}
public interface ExpandedInterface : SimpleInterface
{
void ExpandedMethod();
void OtherExpandedMethod();
}
That way you could declare, on your client code, if you really need an expanded interface implementer (in which case you should pass only an instance of the subset of concrete classes that implement ExpandedInterface) or it is enough to use a SimpleInterface implementer (in which case you can pass either).
The situation you presented (needing to add funcion to one object, but not other) has more to do with the client code than the interface implementers themselves. You have to think: "in this client class, what do I really need: an instance of SimpleInterface, or an instance of ExtendedInterface?"

Giving IFoo.Foo() an implementation via extension method

I came accross the following code:
public interface IFoo { }
Make IFoo do something via an extension method:
public static FooExtensions
{
public static string Foo(this IFoo foo, string bar)
{
// Do work
return bar;
}
}
Is this a good idea? Why not use an abstract class with a virtual Foo() instead? IFoo could have some contract methods but a consumer gets the Foo() extension method also.
My question is: When is something like this a good idea?
The extension method doesn't "make" IFoo do anything. Extension methods just let you extend a type that's closed... it's generally best used in conjunction with code which you don't have the ability to modify, such as framework types or third-party types.
Another possibility is if you have a lot of logic that's absolutely identical across all implementations of your interface, and you want consumers of your interface to have access to that functionality without having to use a base type. Think of LINQ -- it's implemented via extension methods, and you get all the benefits of it just by implementing IEnumerable.
In this case, you're not gaining anything other than an unnecessary layer of indirection. If IFoo should have the ability to do Foo, add Foo to the interface.
Extention methods is a good idea when you don't want or can't change implementation of the class you are extending. IFoo could be declared in a 3rd party library. Or there might be a lot of code dependent on it so that it is very hard to remake it to an abstract class (maybe some reflection rely on interface).
In general from the usage point of view you should use extention methods when it looks more readable than old-school static methods and anyway you would use static method instead of new class member. When considering extention method vs member, consider static method in helper class vs member and if you select static, then consider if it's better to implement it as extention.
But I often see using extention methods where it really isn't required and usually it makes code less readable. So I wouldn't recommend using them when it's easy and obvious how to avoid them.
When is something like this a good idea?
When you need to teach already existing members which implements this interface with new tricks, like this one from the System.Core assembly:
// System.Linq.Enumerable
public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
if (predicate == null)
{
throw Error.ArgumentNull("predicate");
}
foreach (TSource current in source)
{
if (predicate(current))
{
return current;
}
}
throw Error.NoMatch();
}
The reason you might want to do this is when you want an interface to provide a method and the implementation of that method can always be done using the other methods and properties in the interface.
An interface (unlike an abstract base class) give you no way to provide a "default" implementation for a method. By using an extension method you can provide such a method without all implementers of an interface having to provide the same repeated implementation code.
However, a major drawback of this approach is that the method in the extension method is effectively sealed - you cannot implement it differently. Sometimes this is ok, sometimes not - YMMV.
An alternative approach to this is as follows:
Specify your interface as usual, but add the method in question to it.
Provide an abstract base class which provides the default code for the method in question.
Derive from the abstract base class when you want to provide an implementation of this interface.
Another reason you might want to use an extension method is when you either cannot change the existing interface (because it is third-party, for example) or when you don't want to (because it would break existing code).
Extension methods are merely syntax sugar which allow you to change fun(t, x) into t.fun(x). They're useful for discovery (intellisense), or when you want to compose fluent pipelines of functions which follow a "more intuitive" left to right style, rather than right to left. Eg f(x).g(y).h(z) versus h(g(f(x),y),z).
There's not really any downside to using them other than cluttering intellisense.
This is a good idea when you want to give this implementation to any object which implement that interface, regardless of what implementation is that.
An abstract class provide that implementation only to its derived classes.
If that interface is yours, or, you have a single base-abstract class that implements that interface, and it's safe to assume that no implementations which doesn't derive from that class would be in your code - it would be a good idea to implement that functionality in that abstract class (but, you'll have to cast to that abstract class, to use that method, which makes the interface somehow redundant).
However, if you want to provide an implementation (of that method) to all types which implement that interface, regardless of their actual implementation - an extension method would be a better idea.
Moreover, a class can only derive from a single class - which means that by deriving from that abstract class, you cannot derive from any other class. So, if you'll have multiple inheritance chains which implements that interface, the only solution to provide that method to all of them (directly), without duplication of code, is via an extension (although there other solution to provider the functionality, but it wouldn't be directly: objWhichImplIFoo.Foo()).
BTW, there is another reason to want an extension: if you want it to be callable from nulls. A declared method will always throw a NullReferenceException if the object is null. Because extensions are actually static methods - they can be called upon nulls:
IFoo foo = null;
var something = foo.GetSomethingOrDefault();

C# : Static Members in Base Class

I have common data across different instances of derived classes.
So to share the common data properties, I made them static in base class.
But the static common properties can not be declared in the interface.
If we try, we get the error:
"cannot implement an interface member because it is static."
Is there any known design pattern or a best practice for this kind of requirement?
You're better off using an abstract base class instead.
Interface defines just that, an interface. As soon as you have anything "real", be it method implementation or shared data, you need a class, an abstract one in this case.
Alternative would be to keep the interface, but add singleton to hold the data related to the classes which implement the interface. If you need to use an interface, then this is the way to go, I think. Just name the singleton so, that it is obvious it's logically linked to the interface, and document, that implemenations of the interface should use it.
In your case, static class with the data might be enough, instead of full singleton implementation, but I will not get into this here, the whole "static classes vs singletons" is somewhat controversial subject.

When some methods will not be used/not implemented, use an Interface or Abstract Class?

I have a project where quite a few functions and variable getters will be defined, abstractly. My question is should I use an abstract class for this(with each function throwing NotImplementedException), or should I just use an interface? Or should I use both, making both an interface and then an abstract class implementing the interface?
Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases. For instance, AddUser in an authentication class may be defined in an interface, but not ever used in a website due to closed user sign up.
In general, the answer to the question of whether or not to use inheritance or an interface can be answered by thinking about it this way:
When thinking about hypothetical
implementing classes, is it a case
where these types are what I'm
describing, or is it a case where
these types can be or can do what I'm
describing?
Consider, for example, the IEnumerable<T> interface. The classes that implement IEnumerable<T> are all different classes. They can be an enumerable structure, but they're fundamentally something else (a List<T> or a Dictionary<TKey, TValue> or a query, etc.)
On the other hand, look at the System.IO.Stream class. While the classes that inherit from that abstract class are different (FileStream vs. NetworkStream, for example), they are both fundamentally streams--just different kinds. The stream functionality is at the core of what defines these types, versus just describing a portion of the type or a set of behaviors that they provide.
Often you'll find it beneficial to do both; define an interface that defines your behavior, then an abstract class that implements it and provides core functionality. This will allow you to, if appropriate, have the best of both worlds: an abstract class for inheriting from when the functionality is core, and an interface to implement when it isn't.
Also, bear in mind that it's still possible to provide some core functionality on an interface through the use of extension methods. While this doesn't, strictly speaking, put any actual instance code on the interface (since that's impossible), you can mimic it. This is how the LINQ-to-Objects query functions work on IEnumerable<T>, by way of the static Enumerable class that defines the extension methods used for querying generic IEnumerable<T> instances.
As a side note, you don't need to throw any NotImplementedExceptions. If you define a function or property as abstract, then you don't need to (and, in fact, cannot) provide a function body for it within the abstract class; the inheriting classes will be forced to provide a method body. They might throw such an exception, but that's not something you need to worry about (and is true of interfaces as well).
Personally, I think it depends on what the "type" is defining.
If you're defining a set of behaviors, I would recommend an interface.
If, on the other hand, the type really defines a "type", then I'd prefer an abstract class. I would recommend leaving the methods abstract instead of providing an empty behavior, though.
Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases.
If this is true, you should consider breaking this up into multiple abstract classes or interfaces. Having "inappropriate" methods in the base class/interface really is a violation of the Liskov Substitution Principle, and a sign of a design flaw.
If you're not providing any implementation, then use an interface otherwise use an abstract class. If there are some methods that may not be implemented in subclasses, it might make sense to create an intermediate abstract class to do the legwork of throwing NotSupportedException or similar.
One advantage of abstract classes is that one can add to an abstract class new class members whose default implementation can be expressed in terms of existing class members, without breaking existing inheritors of that class. By contrast, if any new members are added to an interface, every implementation of that interface must be modified to add the necessary functionality.
It would be very nice if .net allowed for an interface to include default implementations for properties, methods, and events which did not make any use of object fields. From a technical standpoint, I would think such a thing could be accomplished without too much difficulty by having for each interface a list of default vtable entries which could be used with implementations that don't define all vtable slots. Unfortunately, nothing like that ability exists in .net.
Abstract classes should be used when you can provide a partial implementation. Use interfaces when you don't want to provide any implementation at all - just definition.
In your question, it sounds like there is no implementation, so go with an interface.
Also, rather than throwing NotImplementedException you should declare your method/property with the abstract keyword so that all inheritors have to provide an implementation.
#Earlz I think refering to this: Note, even though all of these functions and such may be defined, it does not mean they will all be used in all use cases. is directly related to the best way to 'attack' this problem.
What you should aim at is minimizing the number of such functions so that it becomes irrelavant (or at least not that important) if you use either or. So improve the design as much as you can and you will see that it really doesn't matter which way you go.
Better yet post a high level of what you are trying to do and let's see if we can come up together with something nice. More brains working towards a common goal will get a better answer/design.
Another pattern that works in some situations is to create a base class that is not abstract. Its has a set of public methods that define the API. Each of these calls a Protected method that is Overideable.
This allows the derived class to pick and choose what methods it needs to implement.
So for instance
public void AddUser(object user)
{
AddUserCore(user);
}
protected virtual void AddUserCore(object user)
{
//no implementation in base
}

What do you use if you want to ensure that all methods and properties are implemented

I was giving a test and got one question.
QUESTION:
What do you use if you want to ensure that all methods and properties are implemented?
a)Inheritance.
b)Polymorphism.
c)Encapsulation
d)Interface.
I think its Interface. Am I right or the. ans is diff?
Yep, use an interface. An interface is basically a contract saying "hey, you need to implement these members, or I'm not going to compile."
An interface or an abstract class will accomplish what you want. In an abstract class, if a method is marked as abstract, then it must be implemented in the derived class. The question really comes down to which one you should use. An interface, or an abstract class.
The quick answer (and I do mean quick and dirty) is that you should use an interface when you are trying to set up contractual behavior between classes. You should use an abstract class when the set of derived class have some shared behavior.
An interface will ensure that the class has method stubs for all the methods, but they may not be implemented and may throw NotImplementedExceptions.
A better way to ensure that all methods are implemented would be using unit tests where you check that the methods actually do what they should.
Actually, these concepts don't even compare to each other.

Categories