Is there a way to check if my element with elementtype class has a certain other class in his inheritance hierarchy?
My usecase is: I have to check if my Exceptions are prefixed with "Exception". To do so, i have to somehow determine if a certain class is an exception. The only way i can be sure is if it is inherited by the Exception class itself.
Checking the baseclass type for being an exception is easy enough, but imagine the following scenario:
class GenericMathException : Exception{}
class SpecificMathException : GenericMathException{}
The only information i can get about the SpecificMathException is that it's baseclass type is GenericMathException, but i can't go any further up in it's inheritance hierarchy.
The usual approach of reflection can't be used too, afaik.
So, anyone ever had to deal with this problem and found a solution? Or has any alternative approach to identify Exceptions?
Thanks in advance.
By its nature, StyleCop indeed works only with the contents of the file and can not use information from the assembly itself.
But, if you ask about "alternative approach to identify Exceptions", there is a rule in StyleCop+ which performs a checking very close to yours. You specify a list of base classes (Attribute, Exception, EventArgs and Stream by default), and it ensures that all classes inherited from them have the name that ends with ...Attribute, ...Exception and so on.
The checking works in the following way. If the name of the base class ends with a string from the list, it ensures that the name of the inherited class should also end with the same string. E.g., if it meets Class2 : InvalidOperationException or Class2 : SomeUnknownException, it will raise a violation in both cases.
Assuming that you follow this rule, all your inherited classes will always be named well, even if they are multi-inherited. The only thing that can not be checked in this way, is the situation where you deal with some classes not from "yours" assembly, that already have broken this rule. E.g., if some assembly has Class2 : Exception, and you reference this assembly as a binary (and do not have a chance to check it with StyleCop) then you will not be able to check if your Class3 inherited from Class2 should be prefixed with ...Exception.
But practice shows that the last issue is rather rare, so the method described above works really well for StyleCop.
Related
My company has a base database model class that is subclassed by particular instances of our product. The class represents primary keys in a database. The base class has a field, which we'll call AlwaysPresent, which is common to all instances of the product and is not used in querying.
abstract class BaseClass
{
private string AlwaysPresent
}
But it is a requirement that subclasses add at least one more field, as we will use reflection later to treat those other fields as database column names for a query. If there are no other fields, we can't query.
So, my question: is it possible to use C#'s reflection capabilities to force a non-abstract subclass to define new fields without specifying their names?
I am a Python programmer by trade, and I know exactly how to solve this kind of problem in Python using metaclasses. To my knowledge, C# does not have metaclasses. And I cannot raise an exception in the base class constructor, because (for various reasons) we don't use constructors for these classes (just initializers), and even if we did the base class constructor could be overridden.
Reflection cannot be used to force something. At least not at compile time. Via reflection you can read how a type is. In your case you can probably check its fields and throw an exception if required at run time.
In any case usually it is much better to use properties instead of fields. Properties are more extensible and better to hide the internal structure of a class.
A common way to enforce a specific design (properties or methods definition) of a class is to use interfaces.You can have also a class that implement more than one interface.
If properties names or fields are not know when designing the interface you cannot enforce your requirements at compile time but only at run time.
Another common c# technique is to decorate properties or fields with attributes. Maybe you can create a custom attribute and at run time check for fields with that attribute (always with reflection).
This can be done with aspects, specifically PostSharp. It allows you to execute custom code during compilation (in fact, it hooks on postcompile action) in the CompileTimeValidate:
http://www.postsharp.net/blog/post/Architectural-Validation
You can of course replace PostSharp with any custom code triggered on postcompile at build-time.
Turns out this is not a feature in C#, but you can write it like this to force people to implement it
abstract class BaseClass
{
private abstract string GetAlwaysPresent();
}
I am trying to initialize an object of DataEditor<Student>, where my DataEditor<T> class implements interface IDataEditor<T> where T : IEditableObject.
DataEditor<Student> editor = GetEditorFor(student);
During runtime, I got a TypeLoadException saying:
GenericArguments[0], 'Namespace.Data.Student', on 'Namespace.IDataEditor`1[T]' violates the constraint of type parameter 'T'. The exception happens on the line above, before it even goes inside the GetEditorFor method.
The only constraint on T is IEditableObject, and my Student class clearly implements it (I double checked the interface spelling, namespace, etc.), and also the compiler doesn't give me any error, so I have no idea why this error happens on runtime.
If I remove the IEditableObject constraint, the code runs without this exception, but my logic depends on the class being an IEditableObject, so it is not an option.
Any idea why this happens and how to fix it?
These pages seems to be related, but I still don't know the solution
https://connect.microsoft.com/VisualStudio/feedback/details/270717/reflection-emit-chokes-on-method-type-parameters
http://bytes.com/topic/c-sharp/answers/478595-reflection-generics-could-anyone-confirm-deny-bug
Is this a bug in .NET? Has anyone found a workaround?
Edit: declaration as requested
public class DataEditor<T> : ViewModel, IDataEditor<T> where T : IEditableObject
public interface IDataEditor<T> : IDataEditor
where T : IEditableObject
My project could not build because of the same error. Even if I did not use any of this generic typed class. Its assembly was just referenced.
When I delete the accessor file of it, problem solved. If you do not need accessor, deleting it may be a solution.
This answer may useful for someone.
What happens is that Student does not implement IEditableObject, the GetEditorFor method probably has a where clause where T must be IEditableObject, and the T that you are passing is Studentand not IDataEditor.
That's why you're getting this error, you're violating the method signature sending a T that is not IEditableObject.
You should either implement IEditableObjectinto the Studentclass, or remove the where T : IEditableObject clause.
Either in C# or Java or in any other language which follows oops concepts generally has 'Object' as super class for it by default. Why do we need to have Object as base class for all the classes we create?
When multiple inheritance is not possible in a language such as C# or Java how can we derive our class from another class when it is already derived from Object class. This question may look like silly but wanted to know some experts opinions on it.
Having a single-rooted type hierarchy can be handy in various ways. In particular, before generics came along, it was the only way that something like ArrayList would work. With generics, there's significantly less advantage to it - although it could still be useful in some situations, I suspect. EDIT: As an example, LINQ to XML's construction model is very "loose" in terms of being specified via object... but it works really well.
As for deriving from different classes - you derive directly from one class, but that will in turn derive indirectly from another one, and so on up to Object.
Note that the things which "all objects have in common" such as hash code, equality and monitors count as another design decision which I would question the wisdom of. Without a single rooted hierarchy these design decisions possibly wouldn't have been made the same way ;)
The fact that every class inherits object ensured by the compiler.
Meaning that is you write:
class A {}
It will compile like:
class A : Object{}
But if you state:
class B : A {}
Object will be in the hierarchy of B but not directly - so there is still no multiple inheritance.
In short
1) The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class.
2) You can have B extend C, and A extend B. A is the child class of B, and B is the child class of C. Naturally, A is also a child class of C.
Well, the multiple inheritance of Object does not apply - you can think of it as:
"If a type doesn't have a base type, then implicitly inject Object".
Thus, applying the rule ad-nauseam, all types inherit from object once and once only - since at the bottom of the hierarchy must be a type that has no base; and therefore which will implicitly inherit from Object.
As for why these languages/frameworks have this as a feature, I have a few reasons:
1) The clue's in the name 'Object Oriented'. Everything is an object, therefore everything should have 'Object' (or equivalent) at it's core otherwise the design principle would be broken from the get-go.
2) Allows the framework to provide hooks for common operations that all types should/might need to support. Such as hash-code generation, string output for debugging etc etc.
3) It means that you can avoid resorting to nasty type casts that can break stuff - like (((int *)(void*))value) - since you have a nice friendly supertype for everything
There's probably loads more than this - and in the time it's taken me to write this 6 new answers have been posted; so I'll leave it there and hope that better people than I can explain in more detail and perhaps better :)
Regarding the first part of your question, it's how classes receive common properties and methods. It's also how we can have strongly-typed parameters to functions that can accept any object.
Regarding your second question, you simply derive your class from the other class; it will then be a descendant of that class, which is in turn a descendant of Object. There's no conflict.
You have the Object base class because amongst others because the Object class has methods (like, in .NET, GetHashCode(), which contain common functionality every object should have).
Multiple inheritance is indeed not possible, but it is possible to derive class A from class B, because A may not directly derive from Object, but B does, so all classes ultimately derive from Object, if you go far enough in the class' inheritance hierarchy.
Just to compare, let's take a look at a language that doesn't enforce a single root class - Objective-C. In most Objective-C environments there will be three root classes available (Object, NSObject and NSProxy), and you can write your own root class by just not declaring a superclass. In fact Object is deprecated and only exists for legacy reasons, but it's informative to include it in this discussion. The language is duck typed, so you can declare a variable's type as "any old object" (written as id), then it doesn't even matter what root class it has.
OK, so we've got all of these base classes. In fact, even for the compiler and runtime libraries to be able to get anywhere they need some common behaviour: the root classes must all have a pointer ivar called isa that references a class definition structure. Without that pointer, the compiler doesn't know how to create an object structure, and the runtime library won't know how to find out what class an object is, what its instance variables are, what messages it responds to and so forth.
So even though Objective-C claims to have multiple root classes, in fact there's some behaviour that all objects must implement. So in all but name, there's really a common primitive superclass, albeit one with less API than java.lang.Object.
N.B. as it happens both NSObject and NSProxy do provide a rich API similar to java.lang.Object, via a protocol (like a Java interface). Most API that claims to deal with the id type (remember, that's the "any old object" type) will actually assume it responds to messages in the protocol. By the time you actually need to use an object, rather than just create it with a compiler, it turns out to be useful to fold all of this common behaviour like equality, hashing, string descriptions etc. into the root class.
Well multiple inheritance is a totally different ball game.
An example of multiple inheritance:-
class Root
{
public abstract void Test();
}
class leftChild : Root
{
public override void Test()
{
}
}
class rightChild : Root
{
public override void Test()
{
}
}
class leafChild : rightChild, leftChild
{
}
The problem here being leafChild inherits Test of rightChild and leftChild. So a case of conflicting methods. This is called a diamond problem.
But when you use the object as super class the hierarchy goes like this:-
class Object
{
public abstract void hashcode();
//other methods
}
class leftChild : Object
{
public override void hashcode()
{
}
}
class rightChild : Object
{
public override void hashcode()
{
}
}
So here we derive both classes from Object but that's the end of it.
It acts like a template for all the objects which will derive from it, so that some common functionality required by every object is provided by default. For example cloning, hashcode and object locking etc.
NOTE: This is not the popular interface naming question about
using or not using "I" at the beginning.
I encounter often the problem to name
an interface, which indicates a belonging or property of a class.
(Please see following list)
Let's brainstorm, what kinds of interfaces are there?
Indicate the "kind" of a class
DataStructure, Number, Thing
Indicate the "profession" of a class
Comparator, Executor, Listener
Indicate a possible action performed with a class
Comparable, Executable, Closeable
The above are all clear to anyone, but let's get to my problem:
Indicate a belonging or property of a class
HasListener, LinksToRoot, BelongsToParent, KnowsSibling, ContainsChildren,
Named, WithDescription, ...?
So, the last point is my problem. My english is not perfect,
but even I feel strange about such names.
They sound to me less successfully chosen then other, less meaningful.
But I often end up choosing right this kind of names.
It is even a greater discomfort in C# where interfaces are expected
to start with an 'I':
IHasListener, IKnowsSibling, ...
Sound to me like LOLSPEAK "I can haz a kitteh, tawtally being full of
cuteness, OMG!##!"
So, how should I name an interface which indicates a belonging or
property of a class?
The problem is the way you choose to describe the "belonging of a property".
Most of your examples you gave can be mapped to the other categories you mentioned.
Just a few, for example:
HasListener => implements Listenable
ContainsChildren => implements Parent
WithDescription => implements Descriptable
Try to stick with more conventional naming schemes, preferably ones that describe your object in the best, more readable manner.
Also, make sure you are not over-interfacing your classes with useless interfaces. Make it very concise and to-the-point, otherwise you'll developers reading your code will get lost very fast.
In some of the problem cases that you outline, I think there may be an answer by looking "from the other side":
HasListener -> Speaker
LinksToRoot, HasParent -> Child (or perhaps Node)
ContainsChildren -> Parent
Of course, different cases will be more or less obvious.
I think you can take some of what you're doing and turn them into "profession"-type interfaces:
HasListener -> ListenerContainer
WithDescription -> DescriptionContainer (Describable might also work, depending on what exactly a "description" is in this context)
A lot of your other interfaces seem to have something to do with a tree structure. I would suggest naming them according to their function in the tree.
ContainsChildren -> Parent or Collection
BelongsToParent -> Child
As for the other ones, I'd need to know more about what specifically these interfaces are for. Some of them, like Named, are probably named just fine.
Those sounds like terrible interface names to me, I agree. The "HasListener" sounds more like a method call that should return a boolean than an interface name.
Interfaces should not exist to hold/store properties of a class. They should be used to outline a relationship that all classes that implement it should follow. I personally stick with the "is a" relationship. If there is a direct relationship, i.e. a cat "is a(n)" animal, then I will create an interface for it and name it Animal giving it a reasonable name.
I would be really interested in knowing what the "HasListener" interface outlines. What exactly does it do? Why can't it be named MyProjectListeners(replacing MyProject with the project name) that describes what listeners defined for this project must adhere to?
HasListener is ok, as well as Listenable. I don't have anything against those.
But IHasListener is terrible: first because we don't really need the I prefix to tell that it is an interface (look at the class signature!) and second because it sounds like "I doesn't speak English".
The only interface in Java that I created with the I prefix was IRule. :)
I actually quite like the "IHasListener" approach.
In the .NET Framework, you'll find this in interfaces such as:
IRaiseListChangedEvents
IHasXmlNode
Names like "Listenable" suggest that the implementation does the listening, not that it contains a listener. IHasListener clearly says what it does.
As as rule of thumb I generally put classes in a file of their own. Visual studio seems to encourage this but what is appropriate with regards to interfaces?
e.g.
I have Class Foo that implements interface Bar
public interface IBar
{
}
public class Foo : IBar
{
}
it seems natural to group these within the same file until another class implements the interface but to dedicate a file to 2 lines code seems excessive but correct.
What is appropriate?
I would split them into 2 files. I often found classes starting to go unmanageable when they are not in their own files.
Imagine trying to find class Foo in a file named IBar.cs or vice versa.
Since the purpose of an interface is to define a "contract" for (potentially) multiple implementing classes, I'd say putting the interface definition in its own file makes more sense. i.e. What happens if you also want to make Baz implement Foo?
Depending on the situation I either split each interface into its own file, or alternatively have an Interfaces.cs file, where I group interfaces in a given namespace together.
I'd never put an interface in the same .cs file as a class that implemented it.
I have only two situations where I find myself putting multiple top level types in a single file:
If you're defining multiple delegate types. Each is only going to be a single declaration, so it makes sense to have a Delegates.cs file.
Sometimes it makes sense to declare that a whole bunch of autogenerated partial types implement a bunch of interfaces. Again, that's one line per type:
// Actualy code is in the autogenerated file
public partial class Foo : ICommon {}
Other than that, I use one file per top-level type, which goes for interfaces, classes and enums.
You should certainly put the interface in it's own file. You may even consider putting the interface in it's own class library. If the interface will be used by two different classes in two different libraries, it makes sense to put the interface in a third library, so you don't have to include any specific implementation if you want to add the interface to a new project. In the third library you might also place classes that work with classes that implement the interface (public void Cook(IBar x), for instance).
Yes, having an interface implies that you are going to have more than one class with the same methods and properties definitions. Having it in one file for the moment is convenient as it is easy to modify without changing files. As time goes on you will and other classes use it, and if you have to make a change to it down the road you will have to hunt and peck for the right file.
I always put them into separate files. Having more than one type per file is just distracting IMO. I might make a folder "Interfaces" for them though.
Also i think you shouldn't modify them as often as your actual implementations, anyway, so having them separated at least promotes that a bit.
In terms of encapsulation, each object, whether a class or an interface, should be in its own file. Even if the interface only contains one abstract method, the fact that it's in a different file allows for better organization and better encapsulation. You can store those different interfaces in a folder, give it an appropriate namespace, and therefore a cleaner solution.