繁体   English   中英

C#:如何在没有“复制/粘贴”代码的情况下重写它

[英]C#: How to rewrite it without “copy/paste” code

我有2个类似的方法:

    /// <summary>
    /// 
    /// </summary>
    /// <param name="domain"></param>
    /// <exception cref="DomainRecordNotFoundException">Throw when the dns record is not found in Office365</exception>
    /// <exception cref="DomainNotFoundException">Throw when domain is not added to Office365</exception>
    /// <exception cref="UnknownException">Unknown exception from Microsoft Graph</exception>
    /// <returns></returns>
    public async Task<string> GetMxRecordForDomainAsync(string domain)
    {
        try
        {
            var records = await _graphClient.Domains[domain].ServiceConfigurationRecords.Request().GetAsync();
            string mxRecord = String.Empty;

            foreach (var record in records)
            {
                if (record.RecordType == "Mx")
                {
                    mxRecord = ((Microsoft.Graph.DomainDnsMxRecord)record).MailExchange;
                    break;
                }
            }

            if (String.IsNullOrWhiteSpace(mxRecord))
                throw new DomainRecordNotFoundException(DomainRegistrationCore.Models.DomainRecordType.MX);

            return mxRecord;
        }
        catch (ServiceException graphEx)
        {
            if (graphEx.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                throw new DomainNotFoundException();
            }

            throw new UnknownException(graphEx.StatusCode, graphEx.Error.Message);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="domain"></param>
    /// <exception cref="DomainRecordNotFoundException">Throw when the dns record is not found in Office365</exception>
    /// <exception cref="DomainNotFoundException">Throw when domain is not added to Office365</exception>
    /// <exception cref="UnknownException">Unknown exception from Microsoft Graph</exception>
    /// <returns></returns>
    public async Task<string> GetVerificationRecordForDomainAsync(string domain)
    {
        try
        {
            var records = (await _graphClient.Domains[domain].VerificationDnsRecords.Request().GetAsync());
            string verificationText = String.Empty;

            foreach (var record in records)
            {
                if (record.RecordType == "Txt")
                {
                    verificationText = ((Microsoft.Graph.DomainDnsTxtRecord)record).Text;
                    break;
                }
            }

            if (String.IsNullOrWhiteSpace(verificationText))
                throw new DomainRecordNotFoundException(DomainRegistrationCore.Models.DomainRecordType.TXT);

            return verificationText;
        }
        catch (ServiceException graphEx)
        {
            if (graphEx.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                throw new DomainNotFoundException();
            }

            throw new UnknownException(graphEx.StatusCode, graphEx.Error.Message);
        }
    }

我们可以看到,这两种方法只有这一部分不同:

        foreach (var record in records)
        {
            if (record.RecordType == **RECORD**)
            {
                mxRecord = ((**TYPE_OF_RECORD**)record).MailExchange;
                break;
            }
        }

        if (String.IsNullOrWhiteSpace(mxRecord))
            throw new DomainRecordNotFoundException(**RECORD**);

其他部分是一样的。 我想为一个常用方法重写它,但不明白如何。 我假设,我可以用Func<>Action<>来做

首先定义通用接口

public interface IExtractor
{
    string RecordType { get; }
    string ErrorMessage { get; }
    string GetValue(object record);
}

接下来创建实现

class MxRecordExtractor : IExtractor
{
    public string RecordType => "Mx";

    public string ErrorMessage => DomainRegistrationCore.Models.DomainRecordType.MX;

    public string GetValue(object record)
    {
        return ((Microsoft.Graph.DomainDnsMxRecord)record).MailExchange;
    }
}

class VerificationRecordExtractor : IExtractor
{
    public string RecordType => "Txt";

    public string ErrorMessage => DomainRegistrationCore.Models.DomainRecordType.TXT;

    public string GetValue(object record)
    {
        return ((Microsoft.Graph.DomainDnsTxtRecord)record).Text;
    }
}

稍后创建私有抽象版本的方法:

private async Task<string> ExtractForDomainAsync(string domain, IExtractor extractor)
{
    try
    {
        var records = (await _graphClient.Domains[domain].VerificationDnsRecords.Request().GetAsync());
        string extractedValue = String.Empty;

        foreach (var record in records)
        {
            if (record.RecordType == extractor.RecordType)
            {
                extractedValue = extractor.GetValue(record);
                break;
            }
        }

        if (String.IsNullOrWhiteSpace(extractedValue))
            throw new DomainRecordNotFoundException(extractor.ErrorMessage);

        return extractedValue;
    }
    catch (ServiceException graphEx)
    {
        if (graphEx.StatusCode == System.Net.HttpStatusCode.NotFound)
        {
            throw new DomainNotFoundException();
        }

        throw new UnknownException(graphEx.StatusCode, graphEx.Error.Message);
    }
}

最后修改现有方法以使用我们常用的方法:

public Task<string> GetMxRecordForDomainAsync(string domain)
{
    return ExtractForDomainAsync(domain,  new MxRecordExtractor());
}

public Task<string> GetVerificationRecordForDomainAsync(string domain)
{
    return ExtractForDomainAsync(domain, new VerificationRecordExtractor());
}

那么,您可以先写下方法的简化模式并分析它们的结构:

Method1(domain)
  some stuff...
  foreach if(c1) res = (Type1)smth
  if (res == null) throw ex(errMsg1)

Method2(domain)
  some stuff...
  foreach if(c2) res = (Type2)smth
  if (res == null) throw ex(errMsg2)

那么每个功能有什么?

  • 常用代码(包括foreach循环)
  • 'if'语句中的一些特定条件
  • 我们将结果转换为的特定类型
  • 在结果为null或为空的情况下,我们用于异常的特定错误消息

我们如何才能满足这些条件并创造一个功能?

  • 在我们的列表中排名第一,我们不需要任何东西
  • 对于第二个条件,我们可以传递然后在'if'条件中使用的参数。
  • 对于第三个,我们可以使用泛型并将类型作为类型参数或将结果传递给dynamic
  • 我们可以再次接受错误消息作为参数

因此,新方法的简化结构可能如下所示:

Method3<TDomainType>(domain, recordTypeToCheck, errorMsg)
  some stuff...
  foreach if(record.RecordType == recordTypeToCheck) res = (TDomainType)smth
  if (res == null) throw ex with errorMsg 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM