Answer the question
In order to leave comments, you need to log in
How often do you use interfaces?
Hello! I deal with the topic of interfaces, asking the question "why, why do we need interfaces", I often received an answer for the loose coupling of components / interchangeability of components, for better testing. And the question is how often do you surround your application layers with interfaces, or something else? How often have you had that your repositories surrounded by interfaces use MSSQL, and there are still the same repositories but already using MongoDB, for example, and where do you replace one with another? Have you often had that you have 2 different layers of services surrounded by interfaces, and again you replace one with another? This is really possible, if it is unlikely, or the probability is small, it turns out that interfaces are mainly used for testing, so that you can use mocks? So, explain, chew, give real examples,
Answer the question
In order to leave comments, you need to log in
The simplest example that comes to mind: imagine that you want to be notified about website errors via email/sms/whatever.
With interfaces, your solution would look something like this:
// Собственно, сам интерфейс оповещений
public interface INotification
{
void Notify(string text);
}
public class EmailNotification : INotification
{
public void Notify(string text)
{
// код по отправке почты
}
}
public class SmsNotification : INotification
{
public void Notify(string text)
{
// код по отправке смс
}
}
// ... Еще какие-нибудь классы оповещений
// В каком-нибудь классе, где может появиться ошибка
public class MaybeErrorClass
{
private INotification _notification;
public MaybeErrorClass(INotification notification)
{
// Класс не должен знать, по какому каналу оповещать об ошибках.
// Он работает с абстракцией
this._notification = notification;
}
// Очень простой пример метода, в котором ожидаем генерацию ошибки
public void DoSomething()
{
try {
// какой-то блок, в котором можем получить ошибку
}
catch (Exception e)
{
this._notification.Notify("А у нас тут ошибка!");
}
}
}
var maybeErrorEmail = new MaybeErrorClass(new EmailNotification());
var maybeErrorSms = new MaybeErrorClass(new SmsNotification());
How often do you use interfaces?
I use interfaces if necessary :-) As I understand it, it's hard to say that this is necessary. Everything depends on the task. If we consider the issue from the perspective of creating interfaces, then sometimes it can be obvious, and sometimes you have to think about whether to use interfaces or not. Pushing them anywhere is a bad idea.
Ready-made interfaces, yes, are often used. The most popular in .NET will probably be IDisposable :-)
From publicly available practical examples of using native interfaces:
interface ILoginForm
{
void WebDocumentLoaded(System.Windows.Forms.WebBrowser webBrowser, Uri url);
}
if (typeof(ILoginForm).IsAssignableFrom(this.GetType()))
{
this.CanLogin = false;
Debug.WriteLine("ILoginForm", "LoginForm");
((ILoginForm)this).WebDocumentLoaded(this.webBrowser1, e.Url);
}
export interface ILocalization {
Loading: string;
LoadingFileContents: string;
// ...
}
export class RU implements ILocalization {
public Loading: string = 'Загрузка...';
public LoadingFileContents: string = 'Получение содержимого файла...';
// ...
}
interface IDBClient
{
public function ExecuteNonQuery();
public function ExecuteScalar();
public function GetRow();
// ...
}
// реализация метода ToInt32
public int ToInt32(IFormatProvider provider)
{
// если пусто, возвращаем ноль
if (!this.HasValue) { return 0; }
// если что-то есть, извлекаем числа и пробуем вернуть int32
return Convert.ToInt32(OAuthUtility.GetNumber(this.Data));
}
public bool SupportRevokeToken { get; protected set; }
public bool SupportRefreshToken { get; protected set; }
public GoogleClient(string clientId, string clientSecret) : base(/*...*/)
{
// ...
base.SupportRevokeToken = true;
base.SupportRefreshToken = true;
}
export interface ILoginState {
Username?: string;
Password?: string;
// ...
}
export default class Index extends Page<any, ILoginState> {
constructor() {
this.state = {
Username: '',
Password: ''
};
}
// ...
}
The benefits of interfaces are so obvious, I don't even know where to start.
Read about OOP, patterns, testing.
Everyone has their own understanding of the interface, and depending on this, programs are written using certain templates. Usually, a technology stack is chosen for the task, and if it is chosen successfully, then the program will live happily ever after. Well, if not, then ... out of luck.
I start from the understanding of polymorphism .. that is, the variety of forms of an object (interface link). This is written in any book on the C # language and on any other language with the OOP paradigm..
Here
you yourself need to understand when to use it.
regardless of the source..
That is:
public interface IDataAccess{
void Connection();
void BeginTransaction();
}
public class MySqlDal:IDataAccess{
public void Contection(){
//TODO implement method!
}
public void BeginTransaction(){
//TODO implement method!
}
}
public class MsSqlDal:IDataAccess{
public void Contection(){
//TODO implement method!
}
public void BeginTransaction(){
//TODO implement method!
}
}
public IDataAccess mySqlDal = new MySqlDal();
public IDataAccess msSqlDal = new MsSqlDal();
At the risk of repeating myself, let me describe my vision.
There are several cases where it is convenient to use interfaces:
As for when to introduce an interface, I usually introduce an interface if I see the point in it for the reasons described above, if there is no sense, then I’m not in a hurry to introduce it, because it can always be distinguished, the main thing is that there is a clear reason for you.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question