Is having class Thing that implements interface IThing a bad practice? [closed] - c#

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

Related

Using interfaces as parameters instead of classes? [closed]

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.

Static and Non Static methods [closed]

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
Good Morning,
I am working on WindowsForm. I came up with 2 solutions. I wanted to know which solution is good practice to follow?
Solution 1:
I have a written a common static methods for validation like phone-text box, mandatory_textbox-key press etc.I have many common methods like this. So what i did is i created a utility class and placed all these static methods in it. Then used these methods across the application.
Solution 2:
i got an idea, so what i did is i created a baseform-inherited Form class, Then i inherited this baseform in all the other forms(Multi-level inheritance).
In the baseform i moved all the validation methods from Utility class and made then non-static.
I also taught about UserControl. If i do that i have work with the alignment tasks again. So that only came up with the two solutions
So Can you suggest which to follow?
You can move the static methods inside non static classes, and pass concrete objects (maybe through interfaces) to the classes/methods who needs that functionality. This way you keep your code easy to test, and decoupled.
By example if you have a class PhoneNumberValidator implementing the interface IValidator which have a method bool Validate(string phoneNumber), and pass it where you need to validate a phone number.
I guess this wuould be the best practice to have a decoupled application.
There in no straightforward answer on whether one should declare methods as static or not. It depends on the context and functionality of your application.
Going with some assumptions for your situation, consider following thoughts on high level -
If the validation is related to one particular form only, and not applicable for other forms, declare it within your form class ans private method. If these validations do not require any class instance, you may declare them static.
If some validations are common for different form, you may declare them as static. Do take caution and do not pass controls to these methods, instead pass the values that you want to validate for better design.
Consider declaring validations in base form only if those are applicable to all or if not most of the forms, and again, if they do not use any instance object, you may mark them as static
A good discussion here.
Use User Control instead of a separate form, if these common controls are being used in every form. Static methods are supposed to be used for utils kind of requirements.
Some times ago I tried to use both solution described by you for different tasks. Every of this have own pluses and minuses.
So, in first case we have only one ststic class and one implementation of every static methods in memory. We can apply this methods to any quantity of other object instances. But we need access this class in every namespace where we will use it.
So, if we will make some changes in any code of this class, it will be applied to all object instances related this class. Sometimes it's convenient, sometimes not.
In second case we will got new instance of base form in memory (less efficient), but we also have one base implementation of methods for inherited forms like first approach. As additional benefit we always can override methods for special cases (if it's needed) for some specific instances only.
In any case, only you can make right decision based on your task context.

Interface vs. Abstract class for a model with objects that share some attributes [closed]

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.

Best practices for restricting access to enum parameter in C# [closed]

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
Consider for the question this String.Split overload, which takes a StringSplitOptions enum as a parameter.
Isn't it bad that the enum itself is public and accessible to everything that includes the System namespace? I mean, the enum is completely specific to options of the Split method, yet it's available outside of it's scope.
Perhaps there is a better way to model this, like putting the enum inside the String class itself, and accessing it by using String.SplitOptions for instance? I very rarely see this (I actually can't remember any such case now), so I assume it is not preferred for some reason. In general, I think reducing the scope of things is a best practice because you lower the chance of problems occurring by using a class/member in an incorrect scope, so to speak.
I'm using Split as an example here, but it is quite common for a Enum to be used only by a method or class in our code base too. I generally create the enum as a public type in a separate cs file like any other class, but I would love to hear other approaches to this 'problem'.
Update:
I just found this article that attacks this exact problem, with a Folder class and a Filter enum but again seems go against what I believe would be more correct in that case (placing the enum inside the class somehow). One of the comments in there from ToddM (which I happen to agree with) states:
...
But, even then, I feel your logic is wrong. Your main complaint
against embedding the enum inside of the class is that it will take
too long to type. Given how verbose C# tends to be, this is not really
a sensible argument. In VS, CTRL+SPACE is your friend.
Logically, I feel placing the enum inside of the class is far more
correct. Take your example: what is a MyNameSpace.Filter? Where does
it apply? I guess it's a filter for your namespace? It's impossible to
tell, especially if your namespace grows to contain dozens of classes.
Now consider MyNameSpace.Folder.Filter -- it is, in my mind, far more
intuitive that Filter applies in some way, shape, or form to the
Folder class. Indeed, another class can be added to the namespace with
its own concept of filter, one of whose members may be 'File'. Just
because you've introduced a new class into the namespace doesn't give
you the right to pollute that namespace with various 'helper' types.
If you are developing as part of a large development team, your style
is, well, rude.
...
It's an interesting idea to nest the enum in order to suggest that it has a reduced scope, or to give it better semantics. I have used this idea before in order to have both error codes and warning codes in a post-compiler I developed. This way, I could use the same enum name Code nested either in the Error class or the Warning class.
On the other hand, public nested types are generally discouraged. They can be confusing to clients who have to qualify them with the outer class name. Look at the related guidelines on MSDN. Some that are relevant:
DO NOT use public nested types as a logical grouping construct; use namespaces for this.
AVOID publicly exposed nested types. The only exception to this is if variables of the nested type need to be declared only in rare scenarios such as subclassing or other advanced customization scenarios.
DO NOT use nested types if the type is likely to be referenced outside of the containing type.
For example, an enum passed to a method defined on a class should not be defined as a nested type in the class.
I believe those guidelines were followed when developing the StringSplitOptions enum, and most of the others in the BCL.
String.Split() is public, so StringSplitOptions has to be public too. Both String and StringSplitOptions exist in the System namespace. Both have public scope. Neither is "available outside of [the other's] scope".
I think one of the reasons is that it would make every call using an embedded enum wider (the name of the class becomes a mandatory prefix).
I personally wouln't appreciate having to use ResultSetTransformer.ResultSetTransformerOptions every time I have to use this enum, it would make my line horribly long.
But as others pointed out, I don't think it's standard in the framework to embed enums in classes at all, possibly for this reason.

Descriptive naming conventions for Interfaces & Abstract Classes [closed]

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...

Categories

Resources