简体   繁体   English

返回布尔值和字符串值的最佳做法是什么

[英]Whats the best practice for returning a Boolean and string value

I've created a method that performs some validations against an XML Hierarchy that is dynamically generated by another Class in Javascript text during run time.我创建了一个方法,该方法针对 XML 层次结构执行一些验证,该 XML 层次结构在运行时由 Javascript 文本中的另一个类动态生成。

My method currently returns either True or False, which is helpful for anyone using my Class but I'd like to also return more informative information since there may be several reasons that can throw a False message.我的方法当前返回 True 或 False,这对使用我的 Class 的任何人都有帮助,但我还想返回更多信息信息,因为可能有多种原因会引发 False 消息。

At first I thought to change the return type from bool to some Generic Collection type having a String key and Boolean value I don't know if this is the best approach.起初我想将返回类型从 bool 更改为具有 String 键和 Boolean 值的一些 Generic Collection 类型,我不知道这是否是最好的方法。

What is the Best Practice in this case?在这种情况下,最佳实践是什么?

Make a class like制作一个像

public class ValidationResponse
{
    public bool Successful { get; set; }
    public string Information { get; set; }
}

and return object of ValidationResponse并返回 ValidationResponse 的对象

One pattern, which is used in the TryParse methods of .NET datatypes (eg Int32.TryParse ), and is very common in the C world, is to return a boolean to signify success or failure.在.NET 数据类型的TryParse方法中使用的一种模式(例如Int32.TryParse )在 C 世界中非常常见,它返回一个布尔值来表示成功或失败。 The user also has to pass in a value by reference to the method to receive the parsed value back.用户还必须通过引用该方法传入一个值以接收返回的解析值。

For your circumstance, your method signature might look like:对于您的情况,您的方法签名可能如下所示:

bool DoSomething (out string anInformativeMessage)

HOWEVER I personally think the best approach is to return a Result class Dhinesh has described in his answer, as it's more flexible, and OO in nature.但是,我个人认为最好的方法是返回 Dhinesh 在他的回答中描述的Result类,因为它更灵活,并且本质上是 OO。 I'm adding this approach for completeness ;)为了完整性,我添加了这种方法;)

  1. Create your own results class, which your method returns and which contains all the information you need.创建您自己的结果类,您的方法将返回该结果类并包含您需要的所有信息。 With this, you can more easily extend it in the future (as in dhinesh's answer.)有了这个,您将来可以更轻松地扩展它(如 dhinesh 的回答。)

  2. Another option is to use a Tuple object to store both the string and bool : Tuple<string, bool> would be your return type.另一种选择是使用Tuple对象来存储stringboolTuple<string, bool>将是您的返回类型。 (Only available in .NET 4.0 onwards) (仅在 .NET 4.0 及更高版本中可用)

The Rust std::result type should also work similarly for C#: Rust std::result类型对于 C# 也应该类似地工作:

enum Result<T, E> {
   Ok(T),
   Err(E),
}

You either:你要么:

  1. return an Ok type with the value返回带有值的Ok类型
  2. or an Err type with the error message或带有错误消息的Err类型

Old answer:老答案:

I don't know about best practice but if you only have the two following cases:我不知道最佳实践,但如果您只有以下两种情况:

  1. Return true, with no extra information返回真,没有额外的信息
  2. Return false, with extra information返回 false,带有额外信息

Then you can simplify it down to just returning a string.然后您可以将其简化为仅返回一个字符串。 If there is no error then you return an empty string which is the equivalent of an error code of zero.如果没有错误,则返回一个空字符串,相当于错误代码为零。

string errorMsg = myObject.MyMethod();
if (errorMsg != String.Empty) {
    Console.Error.WriteLine(errorMsg);
}

Creating a Result class as a new return type as suggested in other answers has the problem of breaking existing code.如其他答案中所建议的那样,将 Result 类创建为新的返回类型存在破坏现有代码的问题。

If you want/need to avoid that, you could introduce a new string LastError property containing error messages of the last call to your method, and keep the method signature intact.如果您想/需要避免这种情况,您可以引入一个新的string LastError属性,其中包含上次调用您的方法的错误消息,并保持方法签名完整。 You'd use it like你会像这样使用它

bool success = myObject.MyMethod();
if(!success)
    Console.Error.WriteLine(myObject.LastError);

This approach is not well suited for multi-threading environments.这种方法不太适合多线程环境。

If it is expected that the XML Hierarchy will validate - Then I would say this is a typical example of where you should use an exception.如果预计XML 层次结构将验证 - 那么我会说这是您应该使用异常的典型示例。 The method then just returns void and throws on failure, like so:然后该方法只返回 void 并抛出失败,如下所示:

void validateXMLHierarchy();

and to use并使用

try
{
  validateXMLHierarchy();
}
catch (XmlValidationException ex)
{
  Console.Error.WriteLine(ex.Message);
}

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

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