Trying to identify used pattern/paradigm (using C#) - c#

While working on a particular design for a object heirarchy I came up with a situation, and built a design that works, but it's pretty confusing pattern in use, and I wanted to check if anyone had seen this pattern before and if there was any literature on it:
So imagine you have a Heirarchy of Animals:
class Animal
class Mammal : Animal
class Dolphin : Mammal
Now imagine we have an interface:
interface IMating<T>
{
MateWith(T otherAnimal);
}
In this instance I'm using generics to strongly type the MateWith method. I could just use object and do some casting which could be unsafe, but I chose to strongly type things.
Given this interface what I ideally would want is:
class Animal : IMating<Animal>
{
}
class Mammal : Animal, IMating<Mammal>
{
}
class Dolphin : Mammal, IMating<Dolphin>
{
}
Doing this allows the derived IMating.MateWith method to extend it's parents behavior by use the base versions of these classes. Of course this means if I were to use an instance of Dolphin I would land up with the following methods on Dolphin:
Dolphin.MateWith(Animal a);
Dolphin.MateWith(Mammal m);
Dolphin.MateWith(Dolphin d);
Obviously I only want the last method in that list, and I want the others hidden from access and just used up the base chain (Animal and mammal are not abstract in my case and can be instantiated). One alternative is to make use of composition thus abstracting the inner "base" class under use.
Since this felt more like a heirarchy that lends itself to inheritance I solved my problem using generic constraints as follows (with some side effects):
class Animal<T> : IMating<T>
where T : Animal
{
}
class Mammal<T> : Animal<T>
where T : Mammal
{
}
class Dolphin<T> : Mammal<T>
where T : Dolphin
{
}
Basically I'm making each class in heirarchy generic but at mininum the type parameter must be at least of the type of the class itself or any derived version of that class.
The pattern for the most part solves what I'm trying to achieve, but I'm wondering if this kind of pattern is used anywhere else and what for? Is it documented somewhere? Is it well known?
Thanks in advance for any help/pointers

Related

Why is an Array an abstract class in C#? [duplicate]

The C# spec, section 10.1.1.1, states:
An abstract class is permitted (but
not required) to contain abstract
members.
This allows me to create classes like this:
public abstract class A
{
public void Main()
{
// it's full of logic!
}
}
Or even better:
public abstract class A
{
public virtual void Main() { }
}
public abstract class B : A
{
public override sealed void Main()
{
// it's full of logic!
}
}
This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.
If inheritors don't actually have to provide implementation, then why call it abstract?
Put another way, why does C# allow an abstract class with only concrete members?
I should mention that I am already familiar with the intended functionality of abstract types and members.
Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:
public abstract class Pet
{
public string Name{get;set;}
}
public class Dog : Pet
{
public void Bark(){ ... }
}
All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.
The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.
The idea is to force the implementor to derive from the class as it is intended to provide only a basis for a presumably more specialized implementation. So the base class, while not having any abstract members may only contain core methods an properties that can be used as a basis for extension.
For example:
public abstract class FourLeggedAnimal
{
public void Walk()
{
// most 4 legged animals walk the same (silly example, but it works)
}
public void Chew()
{
}
}
public class Dog : FourLeggedAnimal
{
public void Bark()
{
}
}
public class Cat : FourLeggedAnimal
{
public void Purr()
{
}
}
I think a slightly more accurate representation of your question would be: Why does C# allow an abstract class with only concrete members?
The answer: There's no good reason not to. Perhaps someone out there has some organizational structure where they like to have a noninstantiatable class at the top, even if a class below it just inherits and adds nothing. There's no good reason not to support that.
You said it -- because you can't instantiate it; it is meant to be a template only.
It is not "really a concrete class" if you declare it as abstract. That is available to you as a design choice.
That design choice may have to do with creating entities that are (at risk of mixing the terminology) abstractions of real-world objects, and with readability. You may want to declare parameters of type Car, but don't want objects to be declarable as Car -- you want every object of type Car to be instantiated as a Truck, Sedan, Coupe, or Roadster. The fact that Car doesn't require inheritors to add implementation does not detract from its value as an abstract version of its inheritors that cannot itself be instantiated.
Abstract means providing an abstraction of behaviour. For example Vehicle is an abstract form. It doesn't have any real world instance, but we can say that Vehicle has accelerating behaviour. More specifically Ford Ikon is a vehicle, and Yamaha FZ is a vehicle. Both these have accelerating behaviour.
If you now make this in the class form. Vehicle is abstract class with Acceleration method. While you may/ may not provide any abstract method. But the business need is that Vehicle should not be instantiated. Hence you make it abstract. The other two classes - Ikon and FZ are concrete classes deriving from Vehicle class. These two will have their own properties and behaviours.
With regards to usage, using abstract on a class declaration but having no abstract members is the same as having the class public but using protected on its constructors. Both force the class to be derived in order for it to be instantiated.
However, as far as self-documenting code goes, by marking the class abstract it informs others that this class is never meant to be instantiated on its own, even if it has no virtual or abstract members. Whereas protecting the constructors makes no such assertion.
The compiler does not prevent implementation-logic, but in your case I would simply omit abstract ?! BTW some methods could be implemented with { throw Exception("must inherit"); } and the compiler could not distinguish fully implemented classes and functions including only throw.
Here's a potential reason:
Layer Supertype
It's not uncommon for all the objects
in a layer to have methods you don't
want to have duplicated throughout the
system. You can move all of this
behavior into a common Layer
Supertype.
-- Martin Fowler
There's no reason to prevent having only concrete methods in an abstract class - it's just less common. The Layer Supertype is a case where this might make sense.
I see abstract classes serving two main purposes:
An incomplete class that must be specialized to provide some concrete service. Here, abstract members would be optional. The class would provide some services that the child classes can use and could define abstract members that it uses to provide its service, like in the Template Method Pattern. This type of abstract class is meant to create an inheritance hierarchy.
A class that only provides static utility methods. In this case, abstract members don't make sense at all. C# supports this notion with static classes, they are implicitly abstract and sealed. This can also be achieved with a sealed class with a private constructor.

Abstract class Vs Interface

An abstract class is the same thing as an interface except it is an actual class, not just a contract.
Why interface is refered to as a contract ?
Both interface and an abstract class are contracts, since they bind you.
But there other differences between an interface and an abstract class.
Like you said, if you need an actual class, with content to the functions or actual data members with default values, or a ctor, then obviously you will need an abstract class.
But many times, the choose between an interface or an abstract class will be technically the same. And sometimes even in the long term, it will be the same.
Your decision then should be based on the nature of what you are looking.
Is it an extra character to your data types? Or does it define what your data type is?
I've tried to think of any real world example, but I couldn't find any as I haven't done anything with the subject for years now, so I'll give you a book-like example.
Say we have an abstract class Animal:
public abstract class Animal
{
abstract string Name;
abstract bool IsWild;
abstract bool IsHappy;
}
This could have been easily an interface.
And choosing it to be an interface will actually won't have any negative effect on your design.
But in the matter of the nature of it, it must be an abstract class, since class Dog is an animal. It must be class Dog : Animal rather than class Dog : IAnimal.
Being an animal is not an extra character of Dog. It what defines it.
And you want the restrict all the animals to inherit only from Animal.
IAnimal let someone inherit something else. like:
public class Dog : Food, IAnimal {}
Interestingly enough, sometimes one might write an abstract class with nothing at all, just for the sake of the same thing.
For example, if there was no common property for any Animal you will still prefer to do:
public abstract class Animal { }
public class Dog : Animal // No actual added value.
{
.........
}
An abstract class is the same thing as an interface
Not true. An interface does not define method bodies, private methods, static fields/methods, etc.
Abstract methods can be private ones and therefore are not guaranteed to be accessible to the outside world, interface implementations are obliged to expose the methods of the interface and thus are "guranteeing" the presence and accessibility of such methods, hence the term contract.

Circular generic types in inheritance - why does it work?

Consider the following:
public class EntityBase<TEntity>
{
public virtual void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
public class PersonEntity : EntityBase<PersonEntity>
{
public override void DoSomethingWhereINeedToKnowAboutTheEntityType()
{
}
}
I added this into code and ran it and it worked ok, but I'm surprised that I can inherit a class who's definition is based on the inheriting class.
When I tried it I was expecting either it not to compile, or to fail once actually called.
You can do something similar with an interface:
public interface IEntityBase<TEntity>
{}
public class PersonEntity : IEntityBase<PersonEntity>
{}
I've actually switched my code from the former to the later, using the interface, but I'm still curious why this works.
It works because there's no reason why it wouldn't work. EntityBase<PersonEntity> doesn't inherit from PersonEntity, it merely references the type. There's no technical problem with a base class knowing about its own derived class. This also works (even though this specific example is a bad idea):
public class A
{
public B AsB()
{
return this as B;
}
}
public class B : A
{
}
I'm surprised that I can inherit a class who's definition is based on the inheriting class.
Careful - what you're inheriting is a class whose definition involves an arbitrary Type, is all. All of these are legal:
class O : EntityBase<object>
class S : EntityBase<String>
class Q : EntityBase<Q>
All you've said in the definition of EntityBase is that TEntity should be a type - well, PersonEntity is a type, isn't it? So why shouldn't it be eligible to be a TEntity? No reason why not - so it works.
You might be concerned about the order of definitions, but remember that within the unit of compilation, everything gets defined 'at once' - there's no sense in which PersonEntity needs to be compiled 'before' anything else (including itself!) can refer to it. Indeed, you're even allowed
class A : EntityBase<B>
class B : EntityBase<A>
for which no conceivable 'order of compilation' could work, if such a thing were needed.
A very simple example is the generic interface IComparable<T>. Usually, you implement it like this:
class MyClass : IComparable<MyClass> {/*...*/}
This implementation of the generic template is just saying that MyClass objects can compare to other MyClass objects. As you can see, there is no problem with the mental model. I can very well understand the concept of a class whose objects can compare between them without knowing anything else about the class.
The main point here is that template parameters are just used by the generic class or interface, but they need not be related by inheritance at all. IComparable<MyClass> does not inherit from MyClass. So there is no circularity.

Cannot create an instance of the abstract class or interface

I'm not familiar on using abstract class.
I'm trying to call a abstract class and get this error Cannot create an instance of the abstract class or interface and I already research this error but I'm really confused on this.
Here's my code:
string B1String;
while ((B1String = OasisFile.ReadLine()) != null)
{
Questions_Base oQuestions_Base = new Questions_Base(); // error here
oQuestions_Base.Import(B1String);
}
Please advice me.. thanks!
The purpose of an abstract class it to serve as part of a class hierarchy where more-derived classes share some common implementation.
If you have a flight simulator, you might define an abstract class ThingsThatFly that implements some properties (air speed, altitude, heading) and methods (TakeOff(), Land()) that all flying things have in common, but would be declared abstract because ThingsThatFly is an abstraction of all concrete things that fly. You could certainly have classes inbetween as well, for example Cessna172 could inherit from Airplane that inherits from ThingsThatFly. You would do that if all airplanes have some common implementation that e.g. birds don't have (for example, a Fuel Remaining property).
You would then have a number of concrete (= real life) things that fly like a Cessna 172, a Space Shuttle and a Duck. Each of those would be a concrete class that derives from ThingsThatFly
This is different than having the concrete classes implement an interface such as IThingsThatFly in that the abstract class provides not only a definition of the properties and methods that are expected, but also provides a (hopefully useful) implementation of those properties and methods.
An Abstract class can only be inherited.
public class CustomClass : Questions_Base {
}
Here's a link all about abstract classes and how to use them.
You cant create an instance of an abstract class.
You need to define a concrete class that inherits the abstract class, and create an instance of that.
Abstract class is made to be overriden by Derived class. If you have to have Abstract class, first create s Derived class from it and use Derived class contructor.
If it's not important, just remove abstract word from Questions_Base class declaration, so making that non abstract one. Also because in code provided I don't see any abstract member, so may this one is correct choice.
Regards.
An abstract class cannot be instantiated. You must provide an implementation for the class.
abstract class Animal
{
public abstract void Speak() { }
}
public class Dog : Animal
{
public override void Speak()
{
Console.WriteLine("Woof");
}
}
See MSDN on abstract for more information
From the documentation: "The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class."
The purpose of using abstract is exactly to prevent instantiation, because you only created the class to use as a base class and never want an instance created.
More here.
An abstract class is one which MUST be inherited.
It falls somewhere between an Interface, which defines only the interface that a class must implement and no implementation code and a class that you can create an instance of which defines both the interface and the implementation code. There are several abstract classes in the .NET framework such as CollectionBase. You cannot create an instance of CollectionBase, it is intended for you to create a class that inherits from it and extends it's capabilities.
You should simpley be able to remove the kwy work "abstract" from your class definition of Questions_Base or create a new class definition that inherits from it.
Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the chapter on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing.

Abstract class without any abstract method

I am surprised to know that an abstract class in C# is possible with no abstract methods also.
abstract class AbstractDemo
{
public void show()
{
Console.WriteLine("In Show Method");
}
}
class MainDemo:AbstractDemo
{
public static void Main()
{
Console.WriteLine("In Main Method");
}
}
Any explaination ?
Sometimes you don't want to give the possibility to instantiate a class but you need this class as a base class for other classes.
The reason for choosing abstract classes over interfaces is that you can provide some basic implementation.
This is entirely valid, and occasionally useful if you want to provide event-like behaviour: provide an abstract class with all the "event handlers" implemented as virtual methods with a default behaviour of doing nothing.
I've also personally used this a lot for abstract remote API client classes where all methods throw exceptions: they're abstract for the purposes of test doubles, expecting our implementations to be the only production implementations, but allowing users to create their own test doubles either by hand or via mocking frameworks. Making the methods virtual instead of abstract means that new RPCs can be added without that being a breaking change.
A derived class can then override some of the methods, but doesn't have to override any specific one, because nothing's abstract. It still makes sense for the class to be abstract because an instance of the base class would be pointless (as everything would be a no-op).
This pattern is much more common in Java than C#, however - as in C# you'd normally just use "proper" events.
An abstract class is a class that must be extended before it can be used. This does not it any way mean that the function themselves must be abstract.
Take for example an Animal class
public abstract class Animal
{
void Move()
{
//whatever
}
}
public class Fish : Animal
{
void Swim()
{
}
}
public class Dog : Animal
{
void Bark()
{
}
}
All animals can move but only the fish can swim and the dog can bark.
Or for a real life example. I have an Asp.net MVC base controller I use in my application. It has some basic methods I need very often like GetCurrentUser() and a function I wrote to help with localization. It also takes care of tracking so I don't have to rewrite that code in all of my controllers. The class has about 200 lines of code but not a single abstract method.
I think you're confusing abstract classes with interfaces. Interfaces can't have methods with body, abstract classes can. There are times when you want to prevent user from instantiating an object of a specific class; but still provide some base functionality for the classes that derive from it; this is what an abstract class is useful for.
If your class is just a base for other classes and it does not have an full usablility - in other words as a base itselfe is not usable at all then you want to prevent from creating instances of it. In this case you can make abstract class without abstract members.
You could use abstract keyword on a class just to signal the compiler that it can only used inheriting from it, and not directly; In this case you are not oblied to put abstract member on the class.
This is equivalent to put in the class only one protected constructor, but using abstract is more clear and understandable.
No better explanation than MSDN it self
http://msdn.microsoft.com/en-us/library/aa645615(v=VS.71).aspx
An abstract class cannot be instantiated directly, and it is a
compile-time error to use the new
operator on an abstract class. While
it is possible to have variables and
values whose compile-time types are
abstract, such variables and values
will necessarily either be null or
contain references to instances of
non-abstract classes derived from the
abstract types.
An abstract class is permitted (but not required) to contain abstract
members.
An abstract class cannot be sealed.
We have heard that in abstract class, there must be an abstarct member. But when I compile the abstarct class without an abstract method, it compiles. It gives me surprise. Now I am unable to find the article which explain exact behavior of an abstarct class.

Categories