Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I have recently been experimenting with naming abstract classes and interfaces in a more descriptive way. Mainly to try and ensure that they do not stray from their intended purpose.
So for abstract classes I have been using IsA or IsAn for interfaces ICan or IPerform
For example, instead of IOperationManager; ICanPerformOperationManagement
I find this reads better when looking at class.
Im sure Im not the first to think like this and was wondering if anyone has used any sort descriptive naming convention for interfaces and abstract classes? Will it scale to large projects, or is it just adding confusion?
EDIT: Is this question too subjective!?
For me it's about being short and descriptive, eliminating redundant terms in the name.
Personally don't see the need to include Can or Perform in an interface name, because the very use of an interface in the first place describes that - the properties and methods then describe what it should be able to do. Think about it this way - would you have an ICantPerform... for types that don't implement the interface? Of course not; the interface is either implemented or it's not there to begin with.
If the developer understands what an interface is, then they understand this. If they don't; they shouldn't be using interfaces until they do.
It's the same with abstract types. IsA or IsAn is again redundant, because as soon as a type inherits from it, the relationship is complete. As Dr.Andrew says (+1 there) - the Base suffix is useful as it implies there is abstract behaviour there to be implemented (which fits nicely with the rest of the BCL too).
For me, IOperationManager makes sense; ICanPerformOperationManagement is clunky.
Abtract classes I tend to append Base to it, for instance ViewModelBase or NodeBase.
For interfaces, I tend to describe the object, so IOperationManager as opposed to ICanPerformOperationManagement. That being said I have occasionally renamed an interface from the rather boring IDrawable to a more interesting ICanBeDrawn
Consider how developers will use the codebase though. If you are tying into intellisense and know you have a class called OperationManager, you would expect its interface to be IOperationManager. Few would guess at first attempt that they should start typing I..C..a..n..P..e.. etc...
Related
This question already has answers here:
Default Interface Methods. What is deep meaningful difference now, between abstract class and interface?
(6 answers)
Closed 4 years ago.
It seems to me like the C# 8.0 feature, default interface member implementation, essentially allows one to create implementations at the interface level. Pairing that with the fact that a class can implement multiple interfaces, it seems eerily close to a multiple inheritance structure for classes. As far as I understand, this seems to be quite opposite to the core of the design of the language.
Where does this discrepancy stem from and what room does this leave for actual abstract classes to occupy?
This question has been suggested as an answer to mine and while it is useful, it doesn't exactly answer my question. To be more precise:
I always assumed that single inheritance is one of the core principles of C#'s design, which is why the decision to implement this feature is surprising to me, and I would be interested to know where it stems from (C#-specifically).
The linked question does not answer what room it leaves for abstract classes.
I always assumed that single inheritance is one of the core principles of C#'s design
This is just not accurate. Single inheritance is a means to design goal, but not a goal in itself.
It's like saying the automatic transmission is a core design principle for car makers, when the actual goal is making the car easier and safer. And looking the car market, manual transmissions still thrive in both the low end (because they're cheaper) and the high end (performance sports cars) of the market, where they are good fit for purpose. Many models in those areas can still be had with either type of transmission.
The actual design goal in C# leading to single inheritance is more about safety and correctness with regards to memory access and overload resolution. Multiple inheritance is difficult to verify mathematically for these things compared to single inheritance. But as they find elegant solutions, C# designers have added a number of features that stretch the bounds of single inheritance. Beyond interfaces, we have partial classes, generics (and later co/contravariance), and delegate members that all trend this direction.
In this case, the default implementation is effective in safely providing a weak multiple inheritance because the inherited functionality doesn't cascade down the inheritance tree from two directions. You can't create a conflict by inheriting two different classes with differing interface implementations; you are limited to either your own class implementation, the default implementation, or the single implementation available via inheritance.
Note that default interface implementation does not allow for multiple inheritance, at least not in the sense that was a problem for C++. The reason multiple inheritance is a problem in C++ is that when a class inherits from multiple classes that have methods with equal signatures, it can become ambiguous as to which implementation is desired. With default interface implementation, that ambiguity is impossible because the class itself does not implement the method. An object must be cast to the interface in order to call the implemented methods. So multiple methods with the same signature may be called on the same instance, but you must explicitly tell the compiler which method you are executing.
The linked post answers your first question to a good extent.
As for:
The linked question does not answer what room it leaves for abstract
classes.
While it may read and sound similar interface default method implementation certainly does not replace abstract classes nor does it make them redundant, the very big reason being:
an interface cannot define class level fields/variables whereas an abstract class can have state.
There are some other differences although not as big as the aforementioned, which you can find in various blogs/posts:
https://dotnetcoretutorials.com/2018/03/25/proposed-default-interface-methods-in-c-8/
https://www.infoq.com/articles/default-interface-methods-cs8
etc.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've seen a lot of different coding patterns over the last several years, and I was struck by vast differences between different shops and programmers. At my previous employer, nearly every single class had a defined interface, even if only a single class implemented that interface, and the interfaces were used as parameters instead of the classes themselves.
At my current employer, interfaces are practically unheard of, and I don't think I've ever seen a custom interface ever defined. As such, classes are pretty much exclusively passed around.
I understand that interfaces are a contract that defines what members and functions a class will implement, but are there any real reasons to define interfaces for some/most classes that will never share similarities to other classes?
For example, most of our operations are simple CRUD actions. While we handle reporting and other tasks, nearly every operation is either some sort of insert, update, delete, or select. Our data models tend to be pretty similar to our database structure at their base level. As we move higher through the application layers, we may combine or alter certain objects to contain related properties, but everything is pretty linear.
I'm just having a hard time seeing why interfaces would be such a good thing to implement in our situation, whereas my last company heavily relied upon them.
The primary benefit to all classes implementing an interface and then passing them around is that it greatly increases the ease of mocking them for unit tests.
If you always pass concrete classes around, the mocks have to derive from them. If they don't have virtual members, the mocks cannot override any behavior, and even if there are virtual members you may get side-effect code from the base class that you don't want in that environment.
None of these problems exist with interfaces, clean mocks are very easy (especially with a framework like NSubstitute). The interfaces also allow for implementing various patterns like Strategy, and help support the Open-Closed Principle (among others).
Granted, an interface for every class can seem to be a bit overkill, but at least interfaces around every process-external facing class is an excellent practice.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have a certain class Thing, and an interface that it implements, named IThing. Everybody who uses IThing can presume that it's really a Thing, since it's the only class which implements this interface, but at the same time he understands that he can only access a certain subset of the public members of Thing, and there's a pretty good design reason for this — basically, IThing is a read-only version of Thing (it's a little bit more complex than that, but let's pretend it's just read-only/write distinction for the sake of the question).
Is it a good convention though? As an alternative, I could name this interface IThingReadOnly or name the class ThingWritable, or something like this, but it seems that these names would be bulky and less readable in a big codebase.
I also use extension methods extensively for both interface and class, so I have ThingExtensions and IThingExtensions as well. It's very useful, because everyone who reads the code of this extensions can operate from an assumption that it only uses public members of Thing and IThing, respectively. However, having both ThingExtensions and IThingExtensions files sitting alongside in a project seem a little bit off for some reason.
So, which one is a better option — to keep Thing and IThing alongside, or to rename one of them?
Update about close vote:
This is an opinion-based question, because it's question about best practice — but it's not a primarily opinion-based question (please mind the distinction). SO has a lot of great question and answers about best practices, so I think that either there's a difference between this question and other best-practice question that I don't see, or this question has just the same right to exist as any other best-practice question.
First off I´d suggest using extension-methods just for types you do not have control on, e.g. the .NET-types like IEnumerable. However you may consider create two different interfaces, one base interface for reading (let´s call it IThingRead) and another one that represents your actual Thing-type (IThingWrite) with some write-modifiers.
Anyway creating an interface for every class is good practice and eases testing by mocking up some uof your types.
If you're sure that you will not need another implementation of the interface and you don't need to mock the interface for test purpose, you can simply remove the interface and use the concrete class.
Otherwise keep using IThing and Thing (this is the normal naming convention).
I would create only IThingExtensions though
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My application is mainly composed of Campaigns. They are the main object of my model.
I have two types of campaign:
Ad hoc: Campaigns that are run once immediately
Scheduled: Campaigns that are scheduled for future and can be run multiple times according to their schedule.
There are shared attributes between these two and there are attributes that are specific to each. What is the best way to design this data model? Interfaces or Abstract classes?
Let's say both types of campaigns can have an Id and a Name and:
Only Ad hoc campaigns have a DataTable called Recipients
Only Scheduled campaigns have a List<DateTime> called Schedule
If you're kind enough not to vote me down or ask to close this question, please provide a basic structure of your recommended model including access modifiers and the abstract/virtual or another keyword that will help me have a better structure for my model.
This is very difficult to answer without a very good understanding of what you're doing and it is unfortunately very opinion based.
However at a very simple level if you use an interface you will often have to duplicate code between the implementing properties (methods, properties and so on). A base class provides this functionality to them. For this reason I often use a base class unless there's a specific reason why an interface is more appropriate.
I would suggest different types of campaigns are all campaigns in essence and so have a base class. However they will target different entities (people, charities, companies) which will all need a way of contacting them (email/phone/address) I'd suggest that these unrelated entities (beyond the fact they can be targeted by a campaign) are a better example of when to use an interface.
However you will need to think about which methods you would override and which is the cleaner solution.
Generally speaking, if they share common behavior (code), that code should exist in an abstract class. If they perform the same role, put them behind an interface.
In your case you seem to have two shared properties, both a simple value, which does not really define behavior, so just based on those properties I'd go for just an interface.
If you do decide to create an abstract class (perhaps there is some code both types would like to share), you could still keep the interface. You could some day have a third campaign type that does not share behavior with the other ones (so does not implement the same abstract class), but does perform the same role (so does implement the same interface).
As for access modifiers in an abstract class, if both classes share only two properties, you just define them in the abstract class without abstract or virtual keyword.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
In Java, methods are virtual by default; C# is the opposite.
Which is better? What are the advantages and disadvantages in each approach?
Anders Hejlsberg: (C# lead architect)
There are several reasons. One is
performance. We can observe that as
people write code in Java, they forget
to mark their methods final.
Therefore, those methods are virtual.
Because they're virtual, they don't
perform as well. There's just
performance overhead associated with
being a virtual method. That's one
issue.
A more important issue is versioning.
There are two schools of thought about
virtual methods. The academic school
of thought says, "Everything should be
virtual, because I might want to
override it someday." The pragmatic
school of thought, which comes from
building real applications that run in
the real world, says, "We've got to be
real careful about what we make
virtual."
When we make something virtual in a
platform, we're making an awful lot of
promises about how it evolves in the
future. For a non-virtual method, we
promise that when you call this
method, x and y will happen. When we
publish a virtual method in an API, we
not only promise that when you call
this method, x and y will happen. We
also promise that when you override
this method, we will call it in this
particular sequence with regard to
these other ones and the state will be
in this and that invariant.
Every time you say virtual in an API,
you are creating a call back hook. As
an OS or API framework designer,
you've got to be real careful about
that. You don't want users overriding
and hooking at any arbitrary point in
an API, because you cannot necessarily
make those promises. And people may
not fully understand the promises they
are making when they make something
virtual.
Java's way is simpler, C#'s way is more granular, safer and more efficient by default. Which is better is in the eye of the beer holder.
.Net forces the programmer to define which functions may be overriden, whereas Java functions, by default, can be overriden unless the final keyword is used.
If you're a strong advocate of the Open/Close Principle you may tend to support the Java way. It's best to allow classes to be extended and methods to be overriden such that the base functionality/code is untouched. For this reason, I support/prefer the Java way. If I were looking at the question from a different perspective, my opinion may be the opposite.
There are 2 major reasons why virtual by default is so much better than non-virtual.
The main principles about usefulness of OOP is Liskov substitution principle, polymorphism and late binding . I use strategy pattern all the time and for that I want my methods to be virtual. If you are fan of Open/closed principle you should like Java philosophy more. You should be able to change behavior without changing your source code. You can do that with dependency injection and virtual methods.
If you call a non-virtual method then you want to know from your code which class method you are calling. The flaw of .net is that you cannot know that from your code.
Another benefit of virtual-only method is that it is much easier to test your code because you can make Mocks of your (or 3rd party) classes. Testing with Mockito is really easy in Java.
Example
In Java if you define ClassB as
public class ClassB extends ClassA {
#Override
public void run() {
}
}
and object
ClassA obj=new ClassB();
If you call obj.run() how will you know if that code is following the rules of polymorphic open/close principle or it will code method related to ClassA? In Java you will know that there is always polymorphism. It is easier to make mocks and it is easier to extend classes and follow Liskov substitution principle.
On the other hand static methods are bounded to a class so if you want to call a method that is related to ClassA you can define that method like this:
public static run(ClassA obj)
and you can call it with
ClassB obj=new ClassB();
ClassA.run(obj);
and from the code you will know that the method you are calling is defined in ClassA and not in ClassB. Also in that case you will not have the overhead of virtual methods. (Note that JIT will also reduce the overhead of virtual methods in many cases).
For C#, if the reason to make the method non-virtual is to be able to define it in a subclass but not involve polymorphism, you're probably subclassing for no real reason.
If it's for design, I'd suggest making the class sealed (final in java) instead of individual methods if possible.
Jon Skeet said that in C# the classes should be sealed by default because methods are non-virtual by default as well. Joshua Bloch said that you should design for inheritance or forbid it (make classes final). C# designers chose a hybrid approach which is non-consistent.
It's a perturbation in time. C++ uses the virtual keyword and final as default.
Java follows C++ and attempts to take the best and improve on its shortcomings. The dangers of overuse of inheritance haven't come to light, so Java chooses to use the final keyword and virtual as default.
C# follows Java and has the benefit of hindsight. Anders chooses to go back to the C++ convention after observing Java's experience.
As always, there are pros and cons. C# has made AOP more difficult to implement, but hindsight can be 20/20 as mentioned by others. It all boils down to whether or not you believe that classes must be designed for extension or simply left open for unforeseen behavior modifications. When designing a language, this is a tough question to answer. I think industry experience is leaning towards the more conservative approach that C# takes.