我正在处理旧版C ++代码,需要积极地进行重构。代码中的主要问题是大量传递const char*
,char*
参数,如下所示。 const char*
变量将传递内部char数组(主要是用户输入)进行验证,并传递'char *`来从扩展验证器正常获取任何错误详细信息。这种类型的代码在代码库中无处不在。
virtual bool ValidateField(const char* pointerToDataBuffer, char* error)
{
// extended codes by client teams.
}
我正在考虑如下更改界面,
virtual bool ValidateField(const std::string copyOfBufferInside, std::string& error)
{
// do stuff as before.
}
我的问题:
注意:编译器为GCC 4.9.3。
已编辑: 内部缓冲区变量在char []中,而不在std :: string中。将来可能会转换为std :: string。但这不是事实。
答案 0 :(得分:1)
考虑使用基于类型的错误处理和boost :: string_view来处理各种类似于字符串的输入:
http://coliru.stacked-crooked.com/a/22e9ec17b14992d1
#include <string>
#include <boost/variant.hpp>
#include <boost/utility/string_view.hpp>
#include <iostream>
#include <type_traits>
struct validation
{
struct error
{
std::string message;
};
struct success
{
};
using result = boost::variant<success, error>;
template<class OnSuccess, class OnFailure>
struct visitor_impl : boost::static_visitor<void>
{
template<class A1, class A2>
visitor_impl(A1&& s, A2&& f)
: on_success(s)
, on_failure(f)
{}
void operator()(success const&) const
{
on_success();
}
void operator()(error const& f) const
{
on_failure(f.message);
}
OnSuccess on_success;
OnFailure on_failure;
};
template<class OnSuccess, class OnFailure>
static auto visitor(OnSuccess&& s, OnFailure&& f)
{
using success_f = typename std::decay<OnSuccess>::type;
using failure_f = typename std::decay<OnFailure>::type;
return visitor_impl<success_f, failure_f>
{
std::forward<OnSuccess>(s),
std::forward<OnFailure>(f)
};
}
};
validation::result ValidateField(boost::string_view value)
{
auto result = validation::result(validation::success {});
if (value != "foo")
result = validation::error { "not foo" };
return result;
}
int main()
{
std::string bar = "bar";
boost::apply_visitor(validation::visitor(
[]() { std::cout << "is foo\n"; },
[](std::string const& msg) { std::cout << msg << '\n'; }
), ValidateField(bar));
std::string foo = "foo";
boost::apply_visitor(validation::visitor(
[]() { std::cout << "is foo\n"; },
[](std::string const& msg) { std::cout << msg << '\n'; }
), ValidateField(foo));
const char* pfoo = "foo";
boost::apply_visitor(validation::visitor(
[]() { std::cout << "is foo\n"; },
[](std::string const& msg) { std::cout << msg << '\n'; }
), ValidateField(pfoo));
}
预期输出:
not foo
is foo
is foo