Situation:
I implement an interface implicit and remove a property on the interface (later).
There is no warning that this property should be removed on the implementation class.
I know I could implement the interface explicitly, but I would try to go around that.
EDIT: (added a question)
How can I be notified/warned/... that I maybe no longer need the member in the implementing class?
There is no way the compiler can give you such a warning in C#. It would somehow need to have knowledge of past versions of the interface to know what method/property was removed and therefore identify possible candidates for removal.
And answering your commentary, you can not make the compiler / refactoring tool decide if any given method is a candidate simply based on the #region its defined in. There is absolutetly nothing that enforces any given method to be defined in any given region, its just visual sugar so refactoring based on regions would be completely unsafe.
Sometimes verbose languages do have advantages, and in this case VB with the implements keyword would make this a compile time error. In C#, you have to use explicitly implemented interfaces which is not a bad option at all. Read here for more details.
Related
I am doubting my understanding of the System.Collection.Generic.IReadOnlyCollection<T> semantics and doubting how to design using concepts like read-only and immutable. Let me describe the two natures I'm doubting between by using the documentation , which states
Represents a strongly-typed, read-only collection of elements.
Depending on whether I stress the words 'Represents' or 'read-only' (when pronouncing in my head, or out loud if that's your style) I feel like the sentence changes meaning:
When I stress 'read-only', the documentation defines in my opinion observational immutability (a term used in Eric Lippert's article), meaning that an implementation of the interface may do as it pleases as long as no mutations are visible publicly†.
When I stress 'Represents', the documentation defines (in my opinion, again) an immutable facade (again described in Eric Lippert's article), which is a weaker form, where mutations may be possible, but just cannot be made by the user. For example, a property of type IReadOnlyCollection<T> makes clear to the user (i.e. someone that codes against the declaring type) that he may not modify this collection. However, it is ambiguous in whether the declaring type itself may modify the collection.
For the sake of completeness: The interface doesn't carry any semantics other than the that carries by the signatures of its members. In this case the observational or facade immutability is implementation dependent (not just implementation-of the-interface-dependent, but instance-dependent).
The first option is actually my preferred interpretation, although this contract can easily be broken, e.g. by constructing a ReadOnlyCollection<T> from an array of T's and then setting a value into the wrapper array.
The BCL has excellent interfaces for facade immutability, such as IReadOnlyCollection<T>, IReadOnlyList<T> and perhaps even IEnumerable<T>, etc. However, I find observational immutability also useful and as far as I know, there aren't any interfaces in the BCL carring this meaning (please point them out to me if I'm wrong). It makes sense that these don't exist, because this form of immutability cannot be enforced by an interface declaration, only by implementers (an interface could carry the semantics though, as I'll show below). Aside: I'd love to have this ability in a future C# version!
Example: (may be skipped) I frequently have to implement a method that gets as argument a collection which is used by another thread as well, but the method requires the collection not to be modified during its execution and I therefore declare the parameter to be of type IReadOnlyCollection<T> and give myself a pat on the back thinking that I've met the requirements. Wrong... To a caller that signature looks like as if the method promises not to change the collection, nothing else, and if the caller takes the second interpretation of the documentation (facade) he might just think mutation is allowed and the method in question is resistant to that. Although there are other more conventional solutions for this example, I hope you see that this problem can be a practical problem, in particular when others are using your code (or future-you for that matter).
So now to my actual problem (which triggered doubting the existing interfaces semantics):
I would like to use observational immutability and facade immutability and distinguish between them. Two options I thought of are:
Use the BCL interfaces and document each time whether it is observational or just facade immutability. Disadvantage: Users using such code will only consult documentation when it's already too late, namely when a bug has been found. I want to lead them into the pit of success; documentation cannot do that). Also, I find this kind of semantics important enough to be visible in the type system rather than solely in documentation.
Define interfaces that carry the observational immutability semantics explicitly, like IImmutableCollection<T> : IReadOnlyCollection<T> { } and IImmutableList<T> : IReadOnlyList<T> { }. Note that the interfaces don't have any members except for the inherited ones. The purpose of these interfaces would be to solely say "Even the declaring type won't change me!"‡ I specifically said "won't" here as opposed to "can't". Herein lies a disadvantage: an evil (or erroneous, to stay polite) implementer isn't prevented from breaking this contract by the compiler or anything really. The advantage however is that a programmer who chose to implement this interface rather than the one it directly inherits from, is most likely aware of the extra message sent by this interface, because the programmer is aware of the existence of this interface, and is thereby likely to implement it accordingly.
I'm thinking of going with the second option but am afraid it has design issues comparable to those of delegate types (which were invented to carry semantic information over their semanticless counterparts Func and Action) and somehow that failed, see e.g. here.
I would like to know if you've encountered/discussed this problem as well, or whether I'm just quibbling about semantics too much and should just accept the existing interfaces and whether I'm just unaware of existing solutions in the BCL. Any design issues like those mentioned above would be helpful. But I am particularly interested in other solutions you might (have) come up with to my problem (which is in a nutshell distinguishing observational and facade immutability in both declaration and usage).
Thank you in advance.
† I'm ignoring mutations of the fields etc on the elements of the collection.
‡ This is valid for the example I gave earlier, but the statement is actually broader. For instance any declaring method won't change it, or a parameter of such a type conveys that the method can expects the collection not to change during its execution (which is different from saying that the method cannot change the collection, which is the only statement one can make with existing interfaces), and probably many others.
An interface cannot ensure immutability. A word in the name wont prevent mutability, that's just another hint like documentation.
If you want an immutable object, require a concrete type that is immutable. In c#, immutability is implementation-dependant and not visible in an interface.
As Chris said, you can find existing implementations of immutable collections.
In C# and C++/CLI the keyword sealed (or NotInheritable in VB) is used to protect a class from any inheritance chance (the class will be non-inheritable). I know that one feature of object-oriented programming is inheritance and I feel that the use of sealed goes against this feature, it stops inheritance.
Is there an example that shows the benefit of sealed and when it is important to use it?
On a class that implements security features, so that the original object cannot be "impersonated".
More generally, I recently exchanged with a person at Microsoft, who told me they tried to limit the inheritance to the places where it really made full sense, because it becomes expensive performance-wise if left untreated. The sealed keyword tells the CLR that there is no class further down to look for methods, and that speeds things up.
In most performance-enhancing tools on the market nowadays, you will find a checkbox that will seal all your classes that aren't inherited.
Be careful though, because if you want to allow plugins or assembly discovery through MEF, you will run into problems.
An addendum to Louis Kottmann's excellent answer:
If a class isn't designed for inheritance, subclasses might break class invariants. This really only applies if you're creating a public API, of course, but as I rule of thumb I seal any class not explicitly designed to be subclassed.
On a related note, applicable to unsealed classes only: any method created virtual is an extension point, or at least looks like it should be an extension point. Declaring methods virtual should be a conscious decision as well. (In C# this is a conscious decision; in Java it isn't.)
And then there's this:
Sealing can make unit testing more difficult, as it prohibits mocking.
Some relevant links:
Effective Java, 2nd Edition by Joshua Bloch. See item 17 (requires Safari subscription)
Effective Java Item 17: Design and document for inheritance or else prohibit it (discussion of same item)
Also note that Kotlin seals classes by default; its open keyword is the opposite of Java's final or the sealed of C#. (To be sure, there is no universal agreement that this is a good thing.)
Marking a class as Sealed prevents tampering of important classes that can compromise security, or affect performance.
Many times, sealing a class also makes sense when one is designing a utility class with fixed behaviour, which we don't want to change.
For example, System namespace in C# provides many classes which are sealed, such as String. If not sealed, it would be possible to extend its functionality, which might be undesirable, as it's a fundamental type with given functionality.
Similarly, structures in C# are always implicitly sealed. Hence one cannot derive one structure/class from another structure. The reasoning for this is that structures are used to model only stand-alone, atomic, user-defined data types, which we don't want to modify.
Sometimes, when you are building class hierarchies, you might want to cap off a certain branch in the inheritance chain, based on your domain model or business rules.
For example, a Manager and PartTimeEmployee are both Employees, but you don't have any role after part-time employees in your organization. In this case, you might want to seal PartTimeEmployee to prevent further branching. On the other hand, if you have hourly or weekly part-time employees, it might make sense to inherit them from PartTimeEmployee.
I think this post has some good point, the specific case was when trying to cast a non-sealed class to any random interface, compiler doesn't throw error; but when sealed is used the compiler throws error that it can't convert. Sealed class brings additional code access security.
https://www.codeproject.com/Articles/239939/Csharp-Tweaks-Why-to-use-the-sealed-keyword-on-cla
Sealing is a conscious decision that should be considered only when you want to clearly reveal your intent about the structural characteristics of your class. It is a structural choice about your object model. It should never be a decision about performance, or security(**). But more importantly, never about arbitrary limits to your inheritance tree.
I am putting forward this rule of thumb:
A class should never be sealed if you have to think whether it is a good idea to seal it. A decision to seal a class should be obvious to you and will be made even before you write the class's first line of code.
As an example, since we can't derive from them but they look so much like a regular class, we often think of structs as sealed classes. Which is what they are. It is this limitation that allows them to implement value-type semantics since inheritance and polymorphism can only work with reference types. So the "struct class" is sealed because any class that implements value-type semantics must give away inheritance and have its memory managed differently. (Note that this is true of any value-type object in C#, not just structs).
Another example: A code generator may write a sealed class representing a window and all its elements for the user to define the behavior on, because the UI engine expects this class, and no other, in order to be able to render the window.
And last example: A math utility class may be sealed because it is built around truisms, and any extended behavior can never be correct or "work as intended". This is one example that doesn't exactly fall under the rule of thumb above. Never blindly trust rules of thumb.
(**) If performance is an issue in your application, you can be sure unsealed classes are not the reason. Similarly, if you depend on sealed classes to enforce security in your application, the problem must be on your base classes -- what they expose or allow to be extended.
Im currently working on a c# project that uses another .net library. This library does (amongst other things) parse a sequence into a tree. All items are of some type that inherits from the abstract class Sequence. I needed to alter the behaviour slightly and subclassed Sequence myself (lets call it MySequence). After the tree was created, I could replace some tree nodes with objects of my own class.
Now, a new version of the library was published, and a Copy function with the following signature was introduced:
internal abstract Sequence Copy();
I tried to adopt my code to the new version and override it, but whatever I am doing, I get the two errors:
MySequence does not implement inherited abstract member 'Sequence.Copy()'
and:
MySequence.Copy()': no suitable method found to override
This makes sense, since it is abstract (--> it must be overwritten) and internal (--> it can not be overwritten, due to hidden visibility from outside the assembly)
So, the problem is, I understand why this is happening, but dont know what to do against it. It is crucial for my project to subclass Sequence.
And what I also dont understand is, why the internal abstract modfier is allowed in the first place as it basically permits any subclassing of the whole class from outside the assembly!?
Is there any way to solve this? Via reflection or something?
Thanks in advance!
Basically, you are out of luck without altering the library. There may be a subclass of Sequence that does implement Copy, which you can derive from in the new version. But it is likely that the Copy method is need in other parts of the library to create clones.
This modifier means that the class can only be inherited in the assembly that defined it.
There is no way around that.
If a library has a type with a member with the modifiers internal abstract, I conclude that the developers of that library didn't want anyone to derive their own type from that type. You cannot work around this.
You can consider whether this was done deliberately. You should ask the publishers. It might be a mistake, in which case the publishers will probably issue a fix. If it is done deliberately, you should come up with an alternative solution without deriving from that type.
EDIT: Or perhaps they intended for you to derive only from derived types in the same assembly that already implement that member.
There are quite a lot of deviations in Java and C# languages, one of which I observed was we cannot add variable constants in an interface. Being from Java background I got baffled to see compilation error when I tried this.
Does anyone has explanation why it is so?
A field is an implementation detail of a class and should not be exposed an its interface.
An interface is a way to abstract away implementation details of a class. These two concepts look contradictory and don't really fit together.
You can declare properties in interfaces instead.
UPDATE (after realizing the question was about constants, not variable fields): I think (purely my personal speculation) that Java decided to allow such a construct because it didn't have enum types back then. C# has had enums since the beginning and preferred those to constants most of the time. Moreover, you can create a static class in C# and add everything you like in it and ship it along the interface without any real hassles. Supporting such a construct would just make interface definitions more complicated.
I've rarely wanted to have an actual constant in an interface - they usually make more sense in classes. The practice of using a Java interface to just contain constants (in order to reduce typing in classes that use them) is nasty; I'd only put constants in interfaces where they were related to functionality within the interface itself.
However, on occasion I've thought it would be nice to be able to define an enum within an interface, if that's the only context in which the enum is anticipated to be used. Interestingly, VB allows this even though C# doesn't.
Effectively both of these would be a way of turning the interface into a "mini-namespace" in its own right. However, I can't say I've missed it very often when writing C#. As the C# team is fond of saying, features aren't removed - they're added, and the cost of adding a feature is very high. That means the feature really needs to pull its weight - there has to be a significant benefit before the feature is added. I personally wouldn't put this very high up on the list.
Related thought: it might be nice to be able to define a nested class within the interface, usually an implementation of the interface - either to express its contracts or to act as a "default" implementation for situations where there is such a thing.
and adding constants to interfaces is discouraged in Java too (according to Effective Java at least)
Adding constants to an interface is wrong and should almost never be done. In the past many people declared Interfaces with many constants and then made another class implement this interface so they could make use of the constants without qualifying said constant. This is of course another anti pattern and was only done because people were lazy. If you really want a constant in an interface define a method that returns that constant.
what are the benefits of implementing an interface in C# 3.5 ?
You'll be able to pass your object to a method (or satisfy a type constraint) that expects the interface as an argument. C# does not support "duck typing." Just by writing the methods defined by the interface, the object will not automatically be "compatible" with the interface type:
public void PrintCollection<T>(IEnumerable<T> collection) {
foreach (var x in collection)
Console.WriteLine(x);
}
If List<T> did not implement the IEnumerable<T> interface, you wouldn't be able to pass it as an argument to PrintCollection method (even if it had a GetEnumerator method).
Basically, an interface declares a contract. Implementing an interface enforces your class to be bound to the contract (by providing the appropriate members). Consequently, everything that relies on that contract (a method that relies on the functionality specified by the interface to be provided by your object) can work with your object too.
The main benefit is about code readability, code maintainability and code "semantics".
Code readability: An interface constitutes a declaration about intentions. It defines a capability of your class, what your class is capable of doing. If you implement ISortable you're clearly stating that your class can be sorted, same for IRenderable or IConvertible.
Code semantics: By providing interfaces and implementing them you're actively separating concepts in a similar way HTML and CSS does. A class is a concrete implementation of an "object class" some way of representing the reality by modeling general properties of real life objects or concepts. An interface define a behavioral model, a definition of what an object can do. Separating those concepts keeps the semantics of your code more clear. That way some methods may need an instance of an animal class while other may accept whatever object you throw at them as long as it supports "walking".
Code maintainability: Interfaces helps to reduce coupling and therefore allow you to easily interchange implementations for the same concept without the underlying code being affected. You can change the implementation of a IMessage easily by defining a new class that implements the interface. Compare that to sistematically replacing all references from CMessage to CMyNewMessageClass.
It will help when you try to:
Unit test with Stubs / Mocks
Implement Dependency injection
Solve world hunger (although this unproven!)
Kindness,
Dan
Interfaces provide no actual advantage. Anything that can be done with an interface can, and should be done using other language constructions. Multiple inheritance is oft quoted as the only REAL benefit derived from using interfaces, but I can do multiple inheritance quite easily and clearly in C# - I do it every day. Changing the code without "breaking" the interface is the silliest of all excuses... That applies the same to concrete classes as it does to abstract classes or interfaces. As long as the functional signature does not change, you haven't broken the interface. Doesn't matter where it was declared. Simply putting a functional prototype in a separate file and naming it with an "I" in front buys nothing - except that you end up with twice as many source files to maintain. The supposition that the interface is defined early, and then maintains the contract is ridiculous. Interface methods and their parameters change ALL the time, because everything is never known up-front. That's why MicroSof stopped using them long ago. They had IUnKnown, IUnknown2, etc. It created a mess.
The main benefits of interfaces is mostly related to project design.
If you use an interface:
The consumer of the interface should implement that interface.
Designing bridge patters.
Creating a contract so that user must adhere the rules of the interface.
Can take only interface part (Object) from the main class.
Even class is private, can obtain the interface object from that
Multiple inheritance kind of style.
Need not be should implement, simple go for if implements that means if you want you can implement other wise can drop it..
Cleaner code.
Implementation which changes depends on class can go ahead with interface.
If each class have separate implementation of a method better to go for interfaces. For example IEnumerable in collections.
According to C# Architect, in a simple word it's a contract. Consumer must adhere to it.
An interface defines a contract (things that an object is able to do), while a concrete class (or struct) defines the concrete behavior.
For an example, IList is an interface, it defines the methods that a concrete object has to provide in order to be used like any other object implementing IList. Everywhere an IList can be used, your object that implements IList can be used as well. The way you concretely implement it and the way your object behaves when those IList methods are called is left to you.
If you work in a huge, commercial software house - you MIGHT want to consider the judicial use of Interfaces. Otherwise, you should stay away from them. Same for multi-threading. If I see one more script-kiddie app that spawns 20 threads to write "Hello World" I'm gonna freak. Multi-threading should be completely reserved for apps that require it, usually in a multi-processing environment. 90% of the time it causes more harm than good. And don't bother with the thread highjack / off-topic comments. I don't care. I've been doing this longer than most of you have been alive. Rank has its privileges.
You aren't tied to class inheritance - you can apply an interface to any class. Any class can have multiple interfaces - C# doesn't support multiple class inheritance, i.e. you are providing a good abstraction layer through the interface
An Interface is a reference type and it contains only abstract members. Interface's members can be Events, Methods, Properties and Indexers. But the interface contains only declaration for its members. Any implementation must be placed in class that realizes them. The interface can't contain constants, data fields, constructors, destructors and static members. All the member declarations inside interface are implicitly public.
The way I understand it interfaces are most useful in these cases:
Cleaner division of labor among programmers. Lead programmer writes interface and junior programmer writes its implementation. That makes perfect sense to me. Lead programmer could write pseudocode instead of interface though.
Some specific situation, where you need 2 or more different implementations of the same class, for example interface animal and classes tiger and lion that use it. And even here it doesn't makes much sense, because lions and tigers share some things in common. Abstract class would be better, because if you use interface you have to write common functions in separate classes which leads to code duplication, which is bad.
You write a library and want it to be modifiable by users. So you write interface and its class implementation. User of your lib still has the possibility to write his own implementation class, which may use different technology/algorithm which achieves the same result, but maybe in a faster way for example. This is also the reason why we meet so many interfaces in libs we use, but rarely feel the need to write our own interfaces. Because we don't write libraries.