Skip to content

Commit 137bd91

Browse files
committed
add non-exceptional error handling for title::create
While exceptions would do (and I do not expect them to be a performance or resource issue), I aim for non-exceptional error handling at least in the domain library
1 parent b610046 commit 137bd91

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed

src/domain/title.cpp

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,13 @@ using fix::domain::title;
55
constexpr size_t MIN_LENGTH = 6;
66
constexpr size_t MAX_LENGTH = 120;
77

8-
bool title::create(std::string_view text) {
9-
return (text.length() >= MIN_LENGTH) && (text.length() <= MAX_LENGTH);
8+
std::optional<title> title::create(std::string_view text) {
9+
if ((text.length() < MIN_LENGTH) || (text.length() > MAX_LENGTH)) {
10+
return std::nullopt;
11+
}
12+
return title{};
13+
}
14+
15+
std::string title::str() const { // NOLINT
16+
return "just some normal title";
1017
}

src/domain/title.hpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,17 @@
11
#ifndef FIX_SRC_DOMAIN_TITLE_HPP
22
#define FIX_SRC_DOMAIN_TITLE_HPP
33

4+
#include <optional>
5+
#include <string>
46
#include <string_view>
57

68
namespace fix::domain {
79

810
class title {
911
public:
10-
static bool create(std::string_view text);
12+
static std::optional<title> create(std::string_view text);
13+
14+
std::string str() const;
1115
};
1216

1317
} // namespace fix::domain

test/domain/title_test.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ using namespace std::literals;
1010
constexpr size_t MIN_LENGTH = 6;
1111
constexpr size_t MAX_LENGTH = 120;
1212

13+
TEST_CASE("Titles can be converted back to strings") {
14+
const auto title_text = "just some normal title"sv;
15+
const auto title = title::create(title_text);
16+
CHECK(title->str() == title_text);
17+
}
18+
1319
TEST_CASE("Titles have restricted length") {
1420
SECTION("titles may not be empty") {
1521
CHECK_FALSE(title::create(""));
@@ -22,7 +28,8 @@ TEST_CASE("Titles have restricted length") {
2228
CHECK_FALSE(title::create(long_scream));
2329
}
2430
SECTION("titles with a length in the allowed range can be created") {
25-
const auto valid_string = GENERATE(std::string(MIN_LENGTH, 'n'), std::string(MAX_LENGTH, 'x'), "some title with sufficient length"s);
31+
const auto valid_string
32+
= GENERATE(std::string(MIN_LENGTH, 'n'), std::string(MAX_LENGTH, 'x'), "some title with sufficient length"s);
2633
const auto title = title::create(valid_string);
2734
CHECK(title);
2835
}

0 commit comments

Comments
 (0)