Ofe*_*mon 21 c# oop string design-patterns interface
说我有一个界面:
public interface IFeature
{
Task execFeature();
}
Run Code Online (Sandbox Code Playgroud)
和两个实现:
public class FirstFeature : IFeature
{
private IWebApi webApi;
public FirstFeature(IWebApi webApi)
{
this.webApi = webApi;
}
public async Task execFeature()
{
string response = await webApi.getClassName();
IResult result;
if(response==null)
result = new TextResult("Error accessing api - check internet connection/api address");
else
result = new TextResult("Hello dear user – the selected class name is " + response);
result.display();
}
}
public class SecondFeature : IFeature
{
private IWebApi webApi;
public SecondFeature(IWebApi webApi)
{
this.webApi = webApi;
}
public async Task execFeature()
{
List<string> classNames = new List<string>();
var classNameTasks = Enumerable.Range(1, 3).Select(i => webApi.getClassName()).ToArray();
classNames.AddRange((await Task.WhenAll(classNameTasks)));
IResult result;
if (classNames[0] == null)
result = new TextResult("Error accessing api - check internet connection/api address");
else
result = new TextResult("Hello dear user – we’ve selected three new class names for you, and they are " + classNames[0] + ", " + classNames[1] + ", and " + classNames[2]);
result.display();
}
}
Run Code Online (Sandbox Code Playgroud)
如您所见,在两种实现中,我都必须执行该result = new TextResult("Error accessing api - check internet connection/api address");行来报告错误.
在error_string我的所有实现中,我可以访问OOP/Good Design中的最佳实践是什么?
现在的方式,代码是重复的.
Win*_*Win 37
我认为没有最好的做法.这只是一个偏好问题.
我将常量存储在静态类中.
public static class Constants
{
public static class Messages
{
public const string Error = "Error accessing api...";
public const string Hello = "Hello ...";
}
}
Run Code Online (Sandbox Code Playgroud)
var result = new TextResult(Constants.Messages.Error);
Run Code Online (Sandbox Code Playgroud)
仅供参考:一些开发人员更喜欢Enum.
我通常会根据消息的目标受众进行区分.因此,我将它们分为两类.
无论类别如何,我都避免多次编写相同的代码(例如消息字符串).
开发者消息
实施选项是多方面的.我通常使用静态类中的字段来保持简单.请注意,您可以为每个将显示消息的类型设置一个消息类,或者您可以在其中设置一个中央消息类,您可以在其中对多个类进行分组.您可以拥有嵌套的邮件组.您还可以添加其他类型的常量以在您的代码中使用...正如我所提到的,选项和首选项比比皆是.
public static class FeatureMessages
{
#region Public Fields
public const string ApiAccessError =
@"Error accessing api - check internet connection/api address";
public const string SelectedClassFormatString =
@"Hello dear user – the selected class name is {0}";
#endregion
}
Run Code Online (Sandbox Code Playgroud)用户消息
| 归档时间: |
|
| 查看次数: |
20298 次 |
| 最近记录: |