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.
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 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 9 years ago.
Improve this question
Apart of the atypical reasons to have classes with hundred members (eg DAO pattern to access hundred objects), what would be the best approach: Have only one class with all members or instead hundred of partial classes each one with one member ?
One partial class for each member looks nice because it facilitates the construction of automated solutions to insert and delete members, just creating or deleting files (classes).
Does C# or something in .Net limit the amount of partial classes ? What about others performances or resources consumption at design time or compilation, supposing that at runtime the two alternatives are the same ?
DETAILING A SAMPLE:
Databases with hundred of objects that need to be accessed from a DaoFactory (DAO pattern) would typically has one member to each object in the database. We aren't discussing the business behind that, why this system has and how it works, but we have a situation, and all objects need to be "exposed" by a DaoFactory. Of course, multiple DaoFactories grouping the objects can minimize its size (amount of members), but only if the division consider all possible relations between them, so all possible of database transactions combined among them to group them.
So, supposing that we cannot divide this DaoFactory, we have a class with hundred of members, and partial classes is an alternative like the one I asked, to have a kind of tool that can maintain it just creating or deleting partial class to each member.
That's not what partial classes are used for. Partial classes are supposed to be used when you do not want to touch the code in the main class. A very good example is the code generated by EF.
Or, when a couple of developers want to work on the same big class. They each develop part of the class as a partial class.
But, you don't divide a class into partial classes just because the class is big.
What would be the point of a class with a hundred, quite likely unrelated members.
If your're going to be generating code, as it appears you might from it facilitates construction of automated solutions... to do data access, create an abstract class or classes, possibly (likely, in fact) generic that implements the common functionality required.
Have your code generator construct suitable concrete instance of the same.
This approach works for manual construction as well.
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...