text
stringlengths
1
2.12k
source
dict
php, mysql, database, mysqli, sql-injection This all results in the following code: <?php require 'init.php'; $userEmail = trim(filter_input(INPUT_POST, 'Email', FILTER_VALIDATE_EMAIL)); $userPassword = filter_input(INPUT_POST, 'Password', FILTER_UNSAFE_RAW); $errorMessage = ''; if ($userEmail) { $select = "SELECT Password FROM Users WHERE Email = ?"; $result = $db->execute_query($select, [$userEmail]); if ($result->field_count == 1) { $passwordHash = $result->fetch_assoc()['Password']; if (password_verify($userPassword, $passwordHash)) { $_SESSION['Email'] = $userEmail; $update = "UPDATE Users SET Last_Login = NOW(), Login_Times = Login_Times + 1 WHERE Email = ?"; $db->execute_query($Update, [$userEmail]); header('location:../home.php'); } else { $errorMessage = "This password is not correct. Please try again!"; } } else { if ($result->field_count > 1) { $errorMessage = "Multiple accounts are associated with this email address. Please contact us!"; } else { $errorMessage = "No account is associated with this email address. Please sign up!"; } } } else { $errorMessage = "This was not a valid email address. Please try again!"; } ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="../Styles/General.css"> <link rel="stylesheet" href="../Styles/Background.css"> <link rel="icon" href ="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> <title>Register & Login</title> </head> <body class="Blue-Black"> <h1 class="Center"> <?php if (empty($errorMessage)) { echo "Please wait, you will be automatically redirected to the login & registeration page."; } else { echo '<font color="white" size="50pt">' . $errorMessage . ' <a href="../login.php">Go to the login page</a>.</font>'; } ?> </h1> </body> </html>
{ "domain": "codereview.stackexchange", "id": 45081, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, mysql, database, mysqli, sql-injection", "url": null }
php, mysql, database, mysqli, sql-injection ?> </h1> </body> </html> Is this code perfect? No. But a lot of problems are resolved. There is still the problem that you ask people to sign up, but redirect them to the login page. Then there also still the other pieces of code to work on.
{ "domain": "codereview.stackexchange", "id": 45081, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, mysql, database, mysqli, sql-injection", "url": null }
javascript, datetime Title: Receiving a daily reward Question: I'm doing a daily reward system on my site. Users can pick up the reward only once a day. The next reward can be picked up the next day, also, only once. When a user visits the site to pick up a daily reward, I put a timestamp in the database (e.g. "2023-09-15 15:36") when the user picked it up. The number of consecutive rewards collected is totaled. Likewise, each time a reward is collected, I put in the database which consecutive day the user does it. I wrote a function checkRewardStatus(date) for this purpose. It should return: "you can claim your reward now" if it is the next day (after the last time the reward was taken). "time's up, you can't collect your reward." in case the user hasn't collected the reward for the whole next day after the last collected reward. "wait until tomorrow to pick up your reward." in case the user picked up the reward today and wants to pick it up again today (this is not allowed). I'm not convinced that my function is 100% correct. I would like to hear comments on my code: what are the drawbacks, what can be improved, modified. I will be glad to any answers, thanks! function checkRewardStatus(date) { let claimDate = new Date(date); const now = new Date(); const nextDayStart = new Date(claimDate); nextDayStart.setDate(claimDate.getDate() + 1); nextDayStart.setHours(0, 0, 0, 0);
{ "domain": "codereview.stackexchange", "id": 45082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime", "url": null }
javascript, datetime const nextDayEnd = new Date(claimDate); nextDayEnd.setDate(claimDate.getDate() + 1); nextDayEnd.setHours(23, 59, 59, 999); const claimDayStart = new Date(claimDate) claimDayStart.setDate(claimDate.getDate()); claimDayStart.setHours( claimDate.getHours(), claimDate.getMinutes(), claimDate.getSeconds(), claimDate.getMilliseconds() ); const claimDayEnd = new Date(claimDate); claimDayEnd.setDate(claimDate.getDate()); claimDayEnd.setHours(23, 59, 59, 999) if (now >= nextDayStart && now <= nextDayEnd) { return "you can claim your reward now" } else if (now > nextDayEnd) { return "time's up, you can't collect your reward." } else if (now >= claimDayStart && now <= claimDayEnd) { return "wait until tomorrow to pick up your reward." } } ``` Answer: Simplify by dropping unnecessary computations You only need the first line in this snippet, the rest of the lines set the same values the object already had: const claimDayStart = new Date(claimDate); claimDayStart.setDate(claimDate.getDate()); claimDayStart.setHours( claimDate.getHours(), claimDate.getMinutes(), claimDate.getSeconds(), claimDate.getMilliseconds() ); Simplify by using half-open intervals To check the end of an interval with <=, the code computes the last millisecond of days using .setHours(23, 59, 59, 999). By adopting half-open intervals, the end can be checked with < and a simpler .setDate(start.getDate() + 1). Simplify using a function to compute key day boundaries Computing "next day end" is a recurring operation in the code. It makes sense to create a function for it. By adopting the previous suggestion, you can use one function to replace 3 manually computed dates. Simplify using fewer variables When multiple variables store the same value, it can become difficult to keep track. If you rename the function parameter to claimDate, then you can eliminate date. Order terms in conditions to have increasing value Instead of:
{ "domain": "codereview.stackexchange", "id": 45082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime", "url": null }
javascript, datetime if (now >= nextDayStart && now <= nextDayEnd) { Consider the equivalent condition, with the terms reordered by increasing value: if (nextDayStart <= now && now <= nextDayEnd) { This way it's easier to see that now is in between values. Use terminating semi-colons consistently Most lines end with a ; but not all. Use terminating ; consistently everywhere or nowhere. Alternative implementation Putting the above suggestions together: function nextDate(date) { const copy = new Date(date); copy.setDate(copy.getDate() + 1); copy.setHours(0, 0, 0, 0); return copy; } function checkRewardStatus(claimDate) { const now = new Date(); const nextDayStart = nextDate(claimDate); const nextDayEnd = nextDate(nextDayStart); const claimDayStart = new Date(claimDate); const claimDayEnd = nextDate(claimDayStart); if (nextDayStart <= now && now < nextDayEnd) { return "you can claim your reward now"; } else if (nextDayEnd <= now) { return "time's up, you can't collect your reward."; } else if (claimDayStart <= now && now < claimDayEnd) { return "wait until tomorrow to pick up your reward."; } }
{ "domain": "codereview.stackexchange", "id": 45082, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, datetime", "url": null }
c++, mocks Title: C++ Mock Library: Part 1 Question: Parts C++ Mock Library: Part 1 C++ Mock Library: Part 2 C++ Mock Library: Part 3 C++ Mock Library: Part 4 C++ Mock Library: Part 5 C++ Mock Library: Part 6 Note: If you see an extra T on a macro ignore for now. I will get to this in a subsequent review. There is to much for one review so I will do in stages. Example: MOCK_FUNC() and MOCK_TFUNC() for now pretend these are the same. I just don't want to have to edit my code before pasting here. I will go over these oddities in a later review. Motivation So writing unit tests for my code! I use Google Test as the basic framework. But my unit tests files were 3947+ lines long (the code was only about 500 lines). A lot of this is repeated code and looked very ugly in the tests. So I though lets try and improve the framework a bit to reduce the repetitive nature of the unit tests. So this is the code for my mock framework (reduced the unit test files to 1713 and does more testing). Interface OK. So this is the part I like least. But I could not think of a better way. Any function that you want to mock must be wrapped in MOCK_FUNC(). In debug and release mode this simply does nothing and the function is just used like normal. In my code coverage build (which is where the unit tests are run). These functions are swapped out by a functor object. Example: Socket::Socket(std::string const& hostname, int port, Blocking blocking) : fd(-1) { fd = MOCK_FUNC(socket)(PF_INET, SOCK_STREAM, 0); if (fd == -1) { // STUFF removed } // STUFF removed HostEnt* serv = nullptr; while (true) { serv = MOCK_FUNC(gethostbyname)(hostname.c_str()); if (serv == nullptr && h_errno == TRY_AGAIN) { continue; } // STUFF removed } // STUFF removed
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks // STUFF removed if (MOCK_FUNC(connect)(fd, reinterpret_cast<SocketAddr*>(&serverAddr), sizeof(serverAddr)) != 0) { // STUFF removed } if (blocking == Blocking::No) { if (MOCK_TFUNC(fcntl)(fd, F_SETFL, O_NONBLOCK) == -1) { // STUFF removed } } } You will see several mocked functions: MOCK_FUNC(socket), MOCK_FUNC(gethostbyname), MOCK_FUNC(connect), MOCK_TFUNC(fcntl). So my build tools (make) will supply the macro -DMOCK_FUNC\(x\)=::x for debug and release builds, while for coverage builds it will add --include coverage/MockHeaders.h so that all files include this file automatically and have some more complex definitions (coming below). The idea here is there should be zero cost in release or debug builds. But for coverage builds we get some extra functionality. Generated files: It generates two other files `coverage/MockHeaders.h` and `coverage/MockHeaders.cpp` these files contain the majority of the code to review. Its a lot so I will split it over a couple of reviews. These files simply need to part of the build. The important part is that for every mocked out functions it generates a global functor variable.
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks The important part is that for every mocked out functions it generates a global functor variable. namespace ThorsAnvil::BuildTools::Mock { // Functor // For each mocked out function we have a functor. // This can hold an alternative version of the function, but by default it is // initialized by the variable it is supposed to override. // So if you want to use the normal function during the unit tests you don't // need to do anything and you get the normal function being called. // Alternatively there are objects provide to override this function with a lambda. // MockFunctionHolder<RemoveNoExcept<ThorsAnvil::BuildTools::Mock::FuncType_fcntl>> MOCK_BUILD_MOCK_SNAME(fcntl)("fcntl", ::fcntl); MockFunctionHolder<RemoveNoExcept<ThorsAnvil::BuildTools::Mock::FuncType_open>> MOCK_BUILD_MOCK_SNAME(open)("open", ::open); MockFunctionHolder<RemoveNoExcept<decltype(::close)>> MOCK_BUILD_MOCK_SNAME(close)("close", ::close); MockFunctionHolder<RemoveNoExcept<decltype(::connect)>> MOCK_BUILD_MOCK_SNAME(connect)("connect", ::connect); MockFunctionHolder<RemoveNoExcept<decltype(::gethostbyname)>> MOCK_BUILD_MOCK_SNAME(gethostbyname)("gethostbyname", ::gethostbyname); MockFunctionHolder<RemoveNoExcept<decltype(::pipe)>> MOCK_BUILD_MOCK_SNAME(pipe)("pipe", ::pipe); MockFunctionHolder<RemoveNoExcept<decltype(::read)>> MOCK_BUILD_MOCK_SNAME(read)("read", ::read); MockFunctionHolder<RemoveNoExcept<decltype(::shutdown)>> MOCK_BUILD_MOCK_SNAME(shutdown)("shutdown", ::shutdown); MockFunctionHolder<RemoveNoExcept<decltype(::socket)>> MOCK_BUILD_MOCK_SNAME(socket)("socket", ::socket); MockFunctionHolder<RemoveNoExcept<decltype(::write)>> MOCK_BUILD_MOCK_SNAME(write)("write", ::write);
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks Code Review OK. Finally to the part where you get to look at some code: Helper Macros: // Macros to expand a function name into the name of a global functor object. // MOCK_FUNC used in user code includes the full namespace prefix. // MOCK_BUILD_MOCK_SNAME used to name the object inside a namespace scope. // #define MOCK_BUILD_MOCK_NAME_EXPAND_(name) mock_ ## name #define MOCK_BUILD_MOCK_NAME_EXPAND(name) MOCK_BUILD_MOCK_NAME_EXPAND_(name) #define MOCK_BUILD_MOCK_NAME(name) ThorsAnvil::BuildTools::Mock:: MOCK_BUILD_MOCK_NAME_EXPAND(name) #define MOCK_BUILD_MOCK_SNAME(name) MOCK_BUILD_MOCK_NAME_EXPAND(name) #define MOCK_FUNC(name) MOCK_BUILD_MOCK_NAME(name) Helper Classes namespace ThorsAnvil::BuildTools { template <typename T> struct RemoveNoExceptExtractor { using Type = T; }; template <typename R, typename... Args> struct RemoveNoExceptExtractor<R(Args...) noexcept> { using Type = R(Args...); }; template <typename F> using RemoveNoExcept = typename RemoveNoExceptExtractor<F>::Type; } Functor Object namespace ThorsAnvil::BuildTools::Mock { template<typename Func> struct MockFunctionHolder { using Param = ParameterType<Func>; std::string name; std::function<Func> action; template<typename F> MockFunctionHolder(std::string const& name, F&& action); std::string const& getName() const; template<typename... Args> ReturnType<Func> operator()(Args&&... args); };
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks // ------------------------- // MockFunctionHolder // ------------------------- template<typename Func> template<typename F> MockFunctionHolder<Func>::MockFunctionHolder(std::string const& name, F&& action) : name(name) , action(std::move(action)) {} template<typename Func> std::string const& MockFunctionHolder<Func>::getName() const { return name; } template<typename Func> template<typename... Args> ReturnType<Func> MockFunctionHolder<Func>::operator()(Args&&... args) { return action(std::forward<Args>(args)...); } } Writing a unit test mocking out a function When writing a unit test to simply mock out a function you use the macro MOCK_SYS() that replaces a function with a macro: TEST(UniTestBloc, MyUnitTest) { MOCK_SYS(socket, [](int, int, int) {return 12;}); MOCK_SYS(connect, [](int, sockaddr const*, unsigned int) {return 0;}); MOCK_SYS(gethostbyname, [](char const*) { static char* addrList[] = {""}; static hostent result {.h_length=1, .h_addr_list=addrList}; return &result; }); auto action = [](){ ThorsSocket::Socket socket("www.google.com", 80); // Do tests }; ASSERT_NO_THROW(action()); } The definition of MOCK_SYS is: #define MOCK_SYS_EXPAND_(type, func, mocked, lambda) ThorsAnvil::BuildTools::Mock::MockOutFunction<type> mockOutFunction_ ## func(mocked, lambda) #define MOCK_SYS_EXPAND(type, func, mocked, lambda) MOCK_SYS_EXPAND_(type, func, mocked, lambda) #define MOCK_SYS(func, lambda) MOCK_SYS_EXPAND(ThorsAnvil::BuildTools::RemoveNoExcept<decltype(::func)>, func, MOCK_BUILD_MOCK_NAME(func), lambda)
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks And the object it creates is: namespace ThorsAnvil::BuildTools::Mock { template<typename Func> struct MockOutFunction { std::function<Func> old; MockFunctionHolder<Func>& orig; MockOutFunction(MockFunctionHolder<Func>& orig, std::function<Func>&& mock); ~MockOutFunction(); }; // ------------------------- // MockOutFunction // ------------------------- template<typename Func> MockOutFunction<Func>::MockOutFunction(MockFunctionHolder<Func>& orig, std::function<Func>&& mock) : old(std::move(mock)) , orig(orig) { swap(old, orig.action); } template<typename Func> MockOutFunction<Func>::~MockOutFunction() { swap(old, orig.action); } } Part 1 done OK. Thats the basics. This part simply is about haveing a function that can be repalced by a lambda during a UNIT TEST. This by itself is not earth shattering and does not save much code. The next question will expand on this. Answer: Macros are difficult Your code relies on macros, and macros are notoriously difficult to work with if you go beyond the simple #define CONSTANT and #ifdef FLAG. Let's just look at what happens if you don't enable mocking: So my build tools (make) will supply the macro -DMOCK_FUNC\(x\)=::x for debug and release builds, […] I immediately see two problems with this. The first is that this will only work correctly for functions in the global namespace. If you would write: using std::format; auto text = MOCK_FUNC(format)("Hello, {}!", "world"); Then this would fail in a release build. And the following would work in a release build, but would break a coverage build: auto text = MOCK_FUNC(std::format)("Hello, {}!", "world"); The second issue is that not everything that looks like a function is actually a function. Consider this: FD_SET fd_set; MOCK_FUNC(FD_CLR)(&fd_set);
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks FD_CLR() expands to something hygienic like do {…} while(0), but of course then ::FD_CLR() will not work correctly. While this is a rather obvious example, there might be more innocent looking functions that are actually implemented as macros, which also might depend on the platform you are on. So what to do about this? First, just use -DMOCK_FUNC(x)=x to fix release builds. Second, if you want to handle namespaces, perhaps the only way is to stringify the name of the functions, and use it as a lookup into a dictionary: #define MOCK_FUNC(func) MOCK_LOOKUP_FUNC(#func) Or perhaps even MOCK_LOOKUP_FUNC<#func> since C++20. With some effort, most if not all of the hashing can be done at compile-time. Since you are autogenerating files anyway, you can use perfect hashing (with a tool like gperf). Alternatives What's great about your code is that you can just write MOCK_SYS(function, replacement) in your tests. It's less great to have to find all instances of function in your code base and to wrap it in MOCK_FUNC(). The latter is very bad for maintenance: it's easy to forget to do this when making changes to your actual code. I would recommend finding a way to make it work without having to use MOCK_FUNC() at all. You have a preprocessing step anyway that finds MOCK_FUNC() calls and uses it to generate coverage/MockHeaders.*. Instead you can have that step look for MOCK_SYS() calls in your tests, and then generate code to replace the standard library functions with custom ones, like suggested in this StackOverflow answer. Other possibilities are using the compiler to wrap functions, just overriding library functions (but then you need some tricks to be able to call the original), and perhaps there are other possibilities as well.
{ "domain": "codereview.stackexchange", "id": 45083, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, bash, mocks Title: C++ Mock Library: Part 2 Question: Parts C++ Mock Library: Part 1 C++ Mock Library: Part 2 C++ Mock Library: Part 3 C++ Mock Library: Part 4 C++ Mock Library: Part 5 C++ Mock Library: Part 6 Removing redundant MOCK_SYS usage After writing a bunch of unit test we see a pattern emerge. The lambda's we are using don't actually do much and most of the time simply return the same value. We only need to specialize them when testing error cases (most of the time they return the same thing). So part two is about building an object that provides a default implementation for all the mocks. Building: test/MockHeaderInclude.h We build the following as part of the build files. test/MockHeaderInclude.h: .FORCE buildMockHeaderInclude Then the script that does the work: #!/bin/bash IFS='%' read -r -d '' -a fileTemplate <<PREFIX #ifndef THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #define THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #include <functional> // Please add includes for all mocked libraries here. // PART-1-Start % // PART-1-End namespace ThorsAnvil::BuildTools::Mock { // Please define all FuncType_<XXX> here // There should be one for each MOCK_TFUNC you use in the code. // The make files will provide the declaration but these need to be filled in by // the developer and committed to source control // PART-2-Start % // PART-2-End // This default implementation of overridden functions // Please provide a lambda for the implementation // When you add/remove a MOCK_FUNC or MOCK_TFUNC to the source // This list will be updated. } #include "coverage/MockHeaders.h" namespace ThorsAnvil::BuildTools::Mock { class MockAllDefaultFunctions { int version; // PART-3-Start % // PART-3-End public: MockAllDefaultFunctions() : version(2) // PART-4-Start % // PART-4-End {} }; } #endif PREFIX function copyPart { local fileName=$1 local section=$2
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks } #endif PREFIX function copyPart { local fileName=$1 local section=$2 cat ${fileName} | awk 'BEGIN {InSection=0;} /'PART-${section}'-Start/ {InSection=1;next;} /PART-'${section}'-End/ {InSection=0} {if (InSection == 1){print}}' } function getFunctions { perl -ne '/MOCK_(T?)FUNC\([ \t]*([^\) \t]*)/ and print "$2 $1\n"' * | sort | uniq } function buildFuncType { local fileName=$1 while read line; do split=(${line}) name=${split[0]} type=${split[1]} if [[ "${type}" == "T" ]]; then find=$(grep "using FuncType_${name}[ \t]*=" "${fileName}") if [[ "${find}" == "" ]]; then echo "using FuncType_${name} = /* Add function type info here */;" fi fi done < <(getFunctions) } function buildMEMBER { local fileName=$1 while read line; do split=(${line}) name=${split[0]} type=${split[1]} find=$(grep "MOCK_${type}MEMBER(${name});" "${fileName}") if [[ "${find}" == "" ]]; then echo " MOCK_${type}MEMBER(${name});" fi done < <(getFunctions) } function buildPARAM { local fileName=$1 while read line; do split=(${line}) name=${split[0]} find=$(grep " MOCK_PARAM(${name}," "${fileName}") if [[ "${find}" == "" ]]; then echo " , MOCK_PARAM(${name}, []( Add expected parameters here ){return Add default value here;})," fi done < <(getFunctions) } function createFile { local fileName=$1 echo "${fileTemplate[0]}" copyPart "${fileName}" 1 echo "${fileTemplate[1]}" copyPart "${fileName}" 2 buildFuncType ${fileName} echo "${fileTemplate[2]}" copyPart "${fileName}" 3 buildMEMBER ${fileName} echo "${fileTemplate[3]}" copyPart "${fileName}" 4 buildPARAM ${fileName} echo "${fileTemplate[4]}" } function buildFile { local fileName=$1
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks function buildFile { local fileName=$1 if [[ -e test ]]; then createFile ${fileName} > ${fileName}.tmp if [[ -e ${fileName} ]]; then diff ${fileName}.tmp ${fileName} if [[ $? == 1 ]]; then echo "ReBuilt: ${fileName}" mv ${fileName}.tmp ${fileName} else \ rm ${fileName}.tmp fi else \ echo "Built: ${fileName}" mv ${fileName}.tmp ${fileName} fi fi } buildFile test/MockHeaderInclude.h This then generates the following file: #ifndef THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #define THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #include <functional> // Please add includes for all mocked libraries here. // PART-1-Start // PART-1-End namespace ThorsAnvil::BuildTools::Mock { // Please define all FuncType_<XXX> here // There should be one for each MOCK_TFUNC you use in the code. // The make files will provide the declaration but these need to be filled in by // the developer and committed to source control // PART-2-Start // PART-2-End // This default implementation of overridden functions // Please provide a lambda for the implementation // When you add/remove a MOCK_FUNC or MOCK_TFUNC to the source // This list will be updated. } #include "coverage/MockHeaders.h" namespace ThorsAnvil::BuildTools::Mock { class MockAllDefaultFunctions { int version; // PART-3-Start MOCK_MEMBER(close); MOCK_MEMBER(connect); MOCK_TMEMBER(fcntl); MOCK_MEMBER(gethostbyname); MOCK_TMEMBER(open); MOCK_MEMBER(pipe); MOCK_MEMBER(read); MOCK_MEMBER(shutdown); MOCK_MEMBER(socket); MOCK_MEMBER(write); // PART-3-End
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks public: MockAllDefaultFunctions() : version(2) // PART-4-Start , MOCK_PARAM(close, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(connect, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(fcntl, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(gethostbyname, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(open, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(pipe, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(read, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(shutdown, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(socket, []( Add expected parameters here ){return Add default value here;}), , MOCK_PARAM(write, []( Add expected parameters here ){return Add default value here;}), // PART-4-End {} }; } #endif Which I then defined like this: #ifndef THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #define THORSANVIl_THORS_SOCKET_MOCK_HEADER_INCLUDE #include <functional> // Please add includes for all mocked libraries here. // PART-1-Start #include <fcntl.h> #include <netdb.h> #include "ThorsSocketConfig.h" // PART-1-End namespace ThorsAnvil::BuildTools::Mock { // Please define all FuncType_<XXX> here // There should be one for each MOCK_TFUNC you use in the code. // The make files will provide the declaration but these need to be filled in by // the developer and committed to source control // PART-2-Start using FuncType_open = int(const char*, int, unsigned short); using FuncType_fcntl = int(int, int, int);
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks // PART-2-End // This default implementation of overridden functions // Please provide a lambda for the implementation // When you add/remove a MOCK_FUNC or MOCK_TFUNC to the source // This list will be updated. } #include "coverage/MockHeaders.h" namespace ThorsAnvil::BuildTools::Mock { class MockAllDefaultFunctions { int version; // PART-3-Start std::function<hostent*(const char*)> getHostByNameMock =[] (char const*) { static char* addrList[] = {""}; static hostent result {.h_length=1, .h_addr_list=addrList}; return &result; }; MOCK_MEMBER(read); MOCK_MEMBER(write); MOCK_TMEMBER(open); MOCK_MEMBER(close); MOCK_TMEMBER(fcntl); MOCK_MEMBER(pipe); MOCK_MEMBER(socket); MOCK_MEMBER(gethostbyname); MOCK_MEMBER(connect); MOCK_MEMBER(shutdown); // PART-3-End
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks // PART-3-End public: MockAllDefaultFunctions() : version(2) // PART-4-Start , MOCK_PARAM(read, [ ](int, void*, ssize_t size) {return size;}) , MOCK_PARAM(write, [ ](int, void const*, ssize_t size) {return size;}) , MOCK_PARAM(open, [ ](char const*, int, int) {return 12;}) , MOCK_PARAM(close, [ ](int) {return 0;}) , MOCK_PARAM(fcntl, [ ](int, int, int) {return 0;}) , MOCK_PARAM(pipe, [ ](int* p) {p[0] = 12; p[1] =13;return 0;}) , MOCK_PARAM(socket, [ ](int, int, int) {return 12;}) , MOCK_PARAM(gethostbyname, std::move(getHostByNameMock)) , MOCK_PARAM(connect, [ ](int, sockaddr const*, unsigned int) {return 0;}) , MOCK_PARAM(shutdown, [ ](int, int) {return 0;}) // PART-4-End {} }; } #endif
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks } #endif Now subsequent calls never change this file (anything I have previously defined is left unchanged). So this file is checked into source control. If I had more MOCK_FUNC() macros to my source then these will of course be added to this file. Helper Macros #define MOCK_MEMBER_EXPAND(type, func) ThorsAnvil::BuildTools::Mock::MockOutFunction<type> mockOutFunction_ ## func #define MOCK_TMEMBER(func) MOCK_MEMBER_EXPAND(ThorsAnvil::BuildTools::Mock::FuncType_ ## func, func) #define MOCK_MEMBER(func) MOCK_MEMBER_EXPAND(decltype(::func), func) #define MOCK_PARAM_EXPAND(func, name, lambda) mockOutFunction_ ## func(name, lambda) #define MOCK_PARAM(func, lambda) MOCK_PARAM_EXPAND(func, MOCK_BUILD_MOCK_NAME(func), lambda) So basically each member declaration expands to (using socket as example): // MOCK_MEMBER(socket) ThorsAnvil::BuildTools::Mock::MockOutFunction<decltype(::socket)> mockOutFunction_socket; With the constructor initializing like this: // MOCK_PARAM(socket, [](int, int, int){return 12;}) , mockOutFunction_socket("socket", [](int, int, int){return 12;}) MockOutFunction This was previously defined in C++ Mock Library: Part 1 Usage in Tests TEST(UniTestBloc, MyUnitTest) { MockAllDefaultFunctions defaultMocks; auto action = [](){ ThorsSocket::Socket socket("www.google.com", 80); // Do tests }; ASSERT_NO_THROW(action()); }
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, bash, mocks Answer: Write it in C++ The script is something I would cobble together as well when I would start working out this problem. However, it is nice for rapid prototyping, but it's actually terrible. It's not just a script, it's specifically bash, and other shells might not be able to run that script. Furthermore, it relies on lots of external tools, most notably: awk, diff, grep, perl, sort, and uniq, some of which have to be called with tiny scripts in their own language. And useless use of cat for good measure. It's perfectly possible to write this in a platform-independent way in C++, especially using std::filesystem, std::format() and std::regex. Or alternatively, if you are depending on a heavy-handed tool like Perl anyway, rewrite it as a Perl script. Performance Apart from probably getting a big performance boost by rewriting it in C++ (probably even despite its poor regex implementation), one issue I noticed is that the script makes it look like it doesn't rebuild anything if nothing has changed, but it actually always rebuilds the output file, but then just diffs it against the old file to check if it was different. Consider instead checking if any of the input files have a newer timestamp than the output file. If not, then you don't have to do anything. Of course, that is something that make could already do for you. So consider changing the Makefile so that all the input files are part of the rule's dependency, and also pass those in as command line parameters.
{ "domain": "codereview.stackexchange", "id": 45084, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, bash, mocks", "url": null }
c++, mocks Title: C++ Mock Library: Part 3 Question: Parts C++ Mock Library: Part 1 C++ Mock Library: Part 2 C++ Mock Library: Part 3 C++ Mock Library: Part 4 C++ Mock Library: Part 5 C++ Mock Library: Part 6 Define normal use case patterns: The next part of this mocking exercise was to simplify the usage. So here I wanted to define objects that had the standard call pattern for constructors/destructors or normal code. So I came up with the pattern. Review The code review is important. But also pointers on the design of the interface would be appreciated. Expected Use: TEST(UniTestBloc, MyUnitTestBlocking) { TA_TestNoThrow([](){ // There is also a TA_TestThrow variant ThorsSocket::Socket socket("www.google.com", 80); }) .expectObject(Socket) // We have a socket class // There will be calls in the constructor // There will be calls in the destructor // Exceptions in the constructor means destructor not called. .run(); } In the above we have separately defined a Socket thing that defines what is being called in the constructor / destructor of a class object. The TA_TestNoThrow will validate that these calls are all done in the correct order. The main variation of this is that sometimes the expected calls change (because of input parameters) so we need to allow for simple variations. TEST(UniTestBloc, MyUnitTestNonBlocking) { TA_TestNoThrow([](){ ThorsSocket::Socket socket("www.google.com", 80, Blocking::No); }) .expectObjectTA(Socket) .expectCallTA(fcntl).toReturn(0) // Making the socket non blocking adds a call to fcntl .run(); }
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks The third variation is that we inject error conditions into what the mocked functions return thus resulting in different behavior. TEST(UniTestBloc, MyUnitTestBlockingWithConnectFailure) { TA_TestThrow([](){ ThorsSocket::Socket socket("www.google.com", 80, Blocking::No); }) .expectObjectTA(Socket) .expectCallTA(connect).inject().toReturn(-1) // Connect Fails // This causes an exception so no destructor is called. .expectCallTA(close) // But we still expect close to be called. .run(); } The expectCallTA() function can be chained with other expectCallTA() functions and with modified calls: .expectCallTA(<func>)[.inject()]?[.anyOrder()]?[.count(<n>)]?[.toReturn(<value>)]* // inject() => Removes any existing calls to <func> // anyOrder() => By default all expected calls are ordered. // If you use `anyOrder()` the order of the call is not looked at. // count(n) => The call will return the result `n` times. // toReturn(V)=> The value "V" will be returned "n" times if not specified the // an object constructed with `{}` of the correct type will be returned // toReturn() can be used multiple times to specify multiple calls. // // TODO: expectedInput(....); :-) Also the expectObjectTA() can be chained from other expectObjectTA() calls or after an expectCallTA() set up. A more complicated example: TEST(UniTestBloc, SecureSSLSocket) { TA_TestThrow([](){ ThorsSocket::SSLSocket socket("www.google.com", 443, Blocking::No); }) // Note: ThorsSocket::SSLSocket derived from ThorsSocket::Socket .expectObjectTA(Socket) .expectCallTA(fcntl).toReturn(0) .expectObjectTA(SSLSocket) .expectCallTA(SSL_connect).inject().toReturn(-1) .expectCallTA(SSL_shutdown) .expectCallTA(SSL_free) .run(); }
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks Interface Design The TA_TestNoThrow and TA_TestThrow are specializations of TA_Test. In this review I will show the parts that handle the setting up of the expected function calls (how this is all tied together during the running of the unit tests is for another review). Simplification with Macros Any method call that ends in TA is actually a macros. The convention is methodTA(F) will expand to method(MOCK2_BUILD_MOCK_NAME(F)) to simplify the usage. The user of the code simply needs to know the name of the function not the underlying implementaiton: #define expectInitTA(func) expectInit(MOCK2_BUILD_MOCK_NAME(func)) #define expectDestTA(func) expectDest(MOCK2_BUILD_MOCK_NAME(func)) #define expectCallTA(func) expectCall(MOCK2_BUILD_MOCK_NAME(func)) #define optionalTA(func) optional(MOCK2_BUILD_MOCK_NAME(func)) TA_Test class TA_Test { std::vector<TA_Object> codeBlocks; public: TA_Test& expectObject(TA_Object const& object); TA_Test& expectCode(TA_Object const& object); template<typename MockObject> TA_Code<MockObject> expectCall(MockObject& action); void run(); };
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks // ------------------------- // TA_Test // ------------------------- // The calls `expectObject()` and `expectCode()` are identical. // The way the underlying objects are created for code and objects // is slightly different but the object they create are the same // so the different functions are simply to help self documenting // the unit tests. TA_Test& TA_Test::expectObject(TA_Object const& object) { codeBlocks.emplace_back(object); return *this; } TA_Test& TA_Test::expectCode(TA_Object const& object) { codeBlocks.emplace_back(object); return *this; } template<typename MockObject> TA_Code<MockObject> TA_Test::expectCall(MockObject& action) { return TA_Code<MockObject>(*this, action, Insert::Append, Order::InOrder); } TA_Code // MockObject: This represents a mocked out function object. // This code will be presented in part 4 // But because each function has a unique interface this can // be a unique type. template<typename MockObject> class TA_Code { protected: TA_Test& parent; MockObject& action; std::size_t callCount; Insert insert; Order order; bool callSaved; public: using Ret = typename MockObject::Ret; TA_Code(TA_Test& parent, MockObject& action, Insert insert, Order order); TA_Code& toReturn(Ret&& result); TA_Code& inject(); TA_Code& anyOrder(); TA_Code& count(int newCount); template<typename NextMockObject> TA_Code<NextMockObject> expectCall(NextMockObject& nextAction);
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks TA_Test& expectObject(TA_Object const& object); TA_Test& expectCode(TA_Object const& object); void run(); private: void saveAction(Ret&& result); };
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks // ------------------------- // TA_Code // ------------------------- template<typename MockObject> TA_Code<MockObject>::TA_Code(TA_Test& parent, MockObject& action, Insert insert, Order order) : parent(parent) , action(action) , callCount(1) , insert(insert) , order(order) , callSaved(false) {} template<typename MockObject> void TA_Code<MockObject>::run() { if (!callSaved) { saveAction({}); } parent.run(); } template<typename MockObject> TA_Code<MockObject>& TA_Code<MockObject>::toReturn(Ret&& result) { saveAction(std::forward<Ret>(result)); return *this; } template<typename MockObject> TA_Code<MockObject>& TA_Code<MockObject>::inject() { insert = Insert::Inject; return *this; } template<typename MockObject> TA_Code<MockObject>& TA_Code<MockObject>::anyOrder() { order = Order::Any; return *this; } template<typename MockObject> TA_Code<MockObject>& TA_Code<MockObject>::count(int newCount) { callCount = newCount; return *this; } template<typename MockObject> TA_Test& TA_Code<MockObject>::expectObject(TA_Object const& object) { if (!callSaved) { saveAction({}); } return parent.expectObject(object); } template<typename MockObject> TA_Test& TA_Code<MockObject>::expectCode(TA_Object const& object) { if (!callSaved) { saveAction({}); } return parent.expectCode(object); } template<typename MockObject> template<typename NextMockObject> TA_Code<NextMockObject> TA_Code<MockObject>::expectCall(NextMockObject& nextAction) { if (!callSaved) { saveAction({}); }
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks { if (!callSaved) { saveAction({}); } return TA_Code<NextMockObject>(parent, nextAction, Insert::Append, Order::InOrder); } template<typename MockObject> void TA_Code<MockObject>::saveAction(Ret&& result) { if (parent.codeBlocks.empty()) { parent.codeBlocks.emplace_back(); } callSaved = true; parent.codeBlocks.back().expectCall(action, callCount, std::forward<Ret>(result), insert, order); }
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks TA_ObjectOption template<typename MockObject> class TA_ObjectOption { using ReturnType = typename MockObject::Ret; TA_Object& object; ActionStore& store; MockObject* mockObjectHolder; std::size_t callCount; ReturnType result; Required required; Order order; public: TA_ObjectOption(TA_Object& object, std::size_t callCount, ActionStore& store, MockObject& mockObjectHolder, Required required, Order order); operator TA_Object& (); TA_ObjectOption& toReturn(ReturnType&& ret); TA_ObjectOption& anyOrder(); TA_ObjectOption& count(int newCount); template<typename NextMockObject> TA_ObjectOption<NextMockObject> expectInit(NextMockObject& action); template<typename NextMockObject> TA_ObjectOption<NextMockObject> expectDest(NextMockObject& action); template<typename NextMockObject> TA_ObjectOption<NextMockObject> optional(NextMockObject& action); private: void saveAction(); };
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks // ------------------------- // TA_ObjectOption // ------------------------- template<typename MockObject> TA_ObjectOption<MockObject>::TA_ObjectOption(TA_Object& object, std::size_t callCount, ActionStore& store, MockObject& mockObjectHolder, Required required, Order order) : object(object) , store(store) , mockObjectHolder(&mockObjectHolder) , callCount(callCount) , result() , required(required) , order(order) {} template<typename MockObject> TA_ObjectOption<MockObject>::operator TA_Object& () { saveAction(); return object; } template<typename MockObject> TA_ObjectOption<MockObject>& TA_ObjectOption<MockObject>::toReturn(ReturnType&& ret) { result = std::move(ret); return *this; } template<typename MockObject> TA_ObjectOption<MockObject>& TA_ObjectOption<MockObject>::anyOrder() { order = Order::Any; return *this; } template<typename MockObject> TA_ObjectOption<MockObject>& TA_ObjectOption<MockObject>::count(int newCount) { callCount = newCount; return *this; } template<typename MockObject> template<typename NextMockObject> inline TA_ObjectOption<NextMockObject> TA_ObjectOption<MockObject>::expectInit(NextMockObject& action) { saveAction(); return TA_ObjectOption<NextMockObject>(object, 1, object.init, action, Required::Yes, Order::InOrder); } template<typename MockObject> template<typename NextMockObject> inline TA_ObjectOption<NextMockObject> TA_ObjectOption<MockObject>::expectDest(NextMockObject& action) { saveAction(); return TA_ObjectOption<NextMockObject>(object, 1, object.dest, action, Required::Yes, Order::InOrder); } template<typename MockObject> template<typename NextMockObject>
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks } template<typename MockObject> template<typename NextMockObject> inline TA_ObjectOption<NextMockObject> TA_ObjectOption<MockObject>::optional(NextMockObject& action) { saveAction(); return TA_ObjectOption<NextMockObject>(object, -1, object.opt, action, Required::No, Order::Any); } template<typename MockObject> inline void TA_ObjectOption<MockObject>::saveAction() { store.add(order, [mock = mockObjectHolder, r = std::move(result), c = callCount, re = required, o = order](Action action, std::size_t index, bool last) mutable { return mock->expectInit(action, index, c, last, std::move(r), re, o); }); }
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks TA_Object class TA_Object { private: template<typename MockObject, typename Result> void expectCall(MockObject& action, std::size_t callCount, Result&& result, Insert insert, Order order); // Code removed for part 4 }; // ------------------------- // TA_Object // ------------------------- template<typename MockObject, typename Result> void TA_Object::expectCall(MockObject& action, std::size_t callCount, Result&& result, Insert insert, Order order) { // Save expected function call into TA_Object (See part 4) } Answer: I can see how this can simplify some tests. The code looks also quite clean. However, I'm a bit worried about whether you should go this way. Here's why: About testing how a function is implemented I see this test as being problematic: TA_TestNoThrow([](){ ThorsSocket::Socket socket("www.google.com", 80, Blocking::No); }) .expectObjectTA(Socket) .expectCallTA(fcntl).toReturn(0) // Making the socket non blocking adds a call to fcntl .run(); Why are you testing specifically for how the constructor of Socket is making the socket non-blocking? There are various ways to do this, including: using fcntl() as you have implemented using SOCK_NONBLOCK in the call to ::socket() using MSG_DONTWAIT in calls to sendto() and recvfrom() on the socket
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
c++, mocks Furthermore, the test you wrote doesn't actually check that fcntl(fd, F_SETFL, O_NONBLOCK) is called, only that fcntl() is called at least once. And even if it sets O_NONBLOCK, it could have a second call to fcntl() that clears O_NONBLOCK. So this test can produce both false positives and false negatives, and if you change the code to use a different method, you break the test. Much better would be to not test the implementation specifics, but rather the observable effects of the class, although in this case that would be quite a bit more work. Nesting and ordering ambiguities In the following code snippet: .expectObjectTA(SSLSocket) .expectCallTA(SSL_connect).inject().toReturn(-1) .expectCallTA(SSL_shutdown) .expectCallTA(SSL_free) Do we expect SSLSocket's constructor to make three calls (to SSL_connect(), then SSL_shutdown(), and then SSL_free()), or do we expect SSL_connect() to call SSL_shutdown() which in turn is expected to call SSL_free()? Knowing OpenSSL and seeing the indentation you used I know what to expect here, but what if I did expect the latter? .expectObjectTA(Socket) … .expectObjectTA(SSLSocket) … Does this mean you expect a Socket object to be constructed first, then a SSLSocket? What if the order is reversed (for example, if SSLSocket had a Socket* member, and new Socket(…) was called inside SSLSocket's constructor's body)? Would the test fail or not? I see there are anyOrder() and count() member functions, but it's also unclear what they apply to: calls, objects or both? And will anyOrder() only allow previous things to be in any order, or only the following ones, or both?
{ "domain": "codereview.stackexchange", "id": 45085, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, mocks", "url": null }
parsing, rust, error-handling Title: A simple parser for bencoding format Question: I have been learning rust sporadically for a while now and decided to write some toy projects. While browsing https://github.com/codecrafters-io/build-your-own-x I came across some bittorrent client examples. As they contain many moving parts like parsing, networking and multithreading it seemed like a good idea for a mini toy project. I started with a decoder/parser for bencoding format since it is probably the simplest and most intuitive part. I initially implemented it using nom since I was familiar with it. Here is the implementation if you're curious: https://github.com/centaurwho/domenec/blob/prototype/domenec/src/bencode_nom.rs. Later I changed that since it was usually too slow and wanted to play with bytes. After implementing it with using the augmented BNF from https://hackage.haskell.org/package/bencoding-0.4.3.0/docs/Data-BEncode.html as reference, I now have a working implementation. Current parser has some basic error handling and many unit tests to confirm it works as intended. Since the official documentation of the format is not very good, I have assumed some details during implementation and later cross-checked using this python library's unit tests: https://github.com/fuzeman/bencode.py/tree/master/tests Here's the code: #[derive(Debug, Clone, Eq, PartialEq)] pub enum DecodingError { Err, MissingIdentifier(char), KeyWithoutValue(String), StringWithoutLength, NotANumber, EndOfFile, NegativeZero, } type Result<T> = std::result::Result<T, DecodingError>; #[derive(Debug, Eq, PartialEq)] pub enum BEncodingType { Integer(i64), String(String), List(Vec<BEncodingType>), Dictionary(LinkedHashMap<String, BEncodingType>), } pub struct BDecoder<'a> { bytes: &'a [u8], cursor: usize, } impl BDecoder<'_> { fn new(bytes: &[u8]) -> BDecoder { BDecoder { bytes, cursor: 0 } }
{ "domain": "codereview.stackexchange", "id": 45086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, error-handling", "url": null }
parsing, rust, error-handling fn decode(&mut self) -> Result<BEncodingType> { self.parse_type() } fn parse_str(&mut self) -> Result<String> { let len = self.read_num().or(Err(DecodingError::StringWithoutLength))?; self.expect_char(b':')?; let start = self.cursor; let end = start + len as usize; if end > self.bytes.len() { self.cursor = self.bytes.len(); return Err(DecodingError::EndOfFile); } self.cursor = end; Ok(String::from_utf8_lossy(&self.bytes[start..end]).to_string()) } fn parse_int(&mut self) -> Result<i64> { self.expect_char(b'i')?; let i = self.read_num()?; self.expect_char(b'e')?; Ok(i) } fn parse_list(&mut self) -> Result<Vec<BEncodingType>> { self.expect_char(b'l')?; let mut list = Vec::new(); while self.peek().filter(|&c| c != b'e').is_some() { list.push(self.parse_type()?); } self.expect_char(b'e')?; Ok(list) } fn parse_dict(&mut self) -> Result<LinkedHashMap<String, BEncodingType>> { self.expect_char(b'd')?; let mut dict = LinkedHashMap::new(); while self.peek().filter(|&c| c != b'e').is_some() { let key = self.parse_str()?; let value = self.parse_type() .map_err(|_| DecodingError::KeyWithoutValue(key.clone()))?; dict.insert(key, value); } self.expect_char(b'e')?; Ok(dict) } fn parse_type(&mut self) -> Result<BEncodingType> { match self.peek() { None => Err(DecodingError::Err), Some(b'i') => self.parse_int().map(BEncodingType::Integer), Some(b'l') => self.parse_list().map(BEncodingType::List), Some(b'd') => self.parse_dict().map(BEncodingType::Dictionary), Some(_) => self.parse_str().map(BEncodingType::String) } }
{ "domain": "codereview.stackexchange", "id": 45086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, error-handling", "url": null }
parsing, rust, error-handling fn read_num(&mut self) -> Result<i64> { let mut neg_const = 1; if self.peek() == Some(b'-') { neg_const = -1; self.cursor += 1; } // FIXME: Consider a cleaner early return here, not happy with the catchall match self.peek() { None => Err(DecodingError::EndOfFile), Some(chr) if !chr.is_ascii_digit() => Err(DecodingError::NotANumber), Some(chr) if neg_const == -1 && chr == b'0' => Err(DecodingError::NegativeZero), _ => Ok(()) }?; let mut acc = 0; while let Some(v) = self.peek() { if v.is_ascii_digit() { acc = acc * 10 + (v - b'0') as i64; self.cursor += 1; } else { break; } }; Ok(acc * neg_const) } fn expect_char(&mut self, expected: u8) -> Result<u8> { match self.peek() { None => Err(DecodingError::EndOfFile), Some(chr) if chr == expected => self.advance(), _ => Err(DecodingError::MissingIdentifier(expected as char)), } } fn peek(&mut self) -> Option<u8> { self.bytes.get(self.cursor).cloned() } fn advance(&mut self) -> Result<u8> { let v = self.bytes.get(self.cursor).cloned(); self.cursor += 1; v.ok_or(DecodingError::EndOfFile) } } pub fn decode(inp: &[u8]) -> Result<BEncodingType> { let mut parser = BDecoder::new(inp); parser.decode() } Code is pretty self explanatory, but if you have any question I can gladly help. I know this is too long and may not result in a lot of reviews but I didn't want to exclude any part for completeness sake. There are some points where I am not sure is good practice or idiomatic rust. Some irks I have:
{ "domain": "codereview.stackexchange", "id": 45086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, error-handling", "url": null }
parsing, rust, error-handling I am not a fan of classes with one public method in other languages. So I considered not having a struct at all and passing the bytes from function to function. I considered using a bytes iterator instead of having a bytes and cursor field. But not sure if it would improve the code at all. I am not sure if error handling is clean enough. Particularly, is the amount of custom error kinds in DecodingError necessary. I know for most languages custom errors are usually not recommended or having only 1 or 2 is enough. Also on error handling, in the function read_num I am using a match expression combined with ? to early return from the function. I don't like creating Ok(()) in the catchall arm and throwing it away in the next line. I feel like there should be a better way. These were just some questions I had while writing it and I probably missed some others. Would really appreciate a review. Answer: A short, more general review since I'm not too experienced with Rust: The contained type of BEncodingType::String should be changed from String to Vec<u8>. From the Bencode Wikipedia page, it's a byte string so it's a sequence of bytes, not necessarily characters, and "bencoded values often contain binary data". Example: a torrent file, where the pieces entry is a concatenation of the binary form of each piece's SHA-1 hash. So while your decoder works for byte slices that are valid UTF-8, it corrupts any data that doesn't cleanly convert to UTF-8. Example test case that demonstrates this: #[test] pub fn test_parse_byte_string() { let input: &[u8] = b"4:rDx\x8D"; let expected_decoded_bytes: &[u8] = b"rDx\x8D"; // &[114, 68, 120, 141] let mut decoder = BDecoder::new(input); if let Ok(s) = decoder.parse_str() { assert_eq!(s.as_bytes(), expected_decoded_bytes); } else { panic!("test case should not return a decoding error"); } }
{ "domain": "codereview.stackexchange", "id": 45086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, error-handling", "url": null }
parsing, rust, error-handling The above test yields the following output when run, where 239, 191, 189 corresponds to the U+FFFD replacement character �: ---- bdecode::test::test_parse_byte_string stdout ---- thread 'bdecode::test::test_parse_byte_string' panicked at 'assertion failed: `(left == right)` left: `[114, 68, 120, 239, 191, 189]`, right: `[114, 68, 120, 141]`', src/bdecode.rs:195:13 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace parse_str should bail early when it sees a negative length, but instead it tries to continue parsing invalid inputs like -3:abc which will lead to either a panic or incorrect parsing. As a replacement for the match statement you flagged, I don't think there's anything wrong with the following. It's straightforward and easy to understand. if let Some(chr) = self.peek() { if !chr.is_ascii_digit() { return Err(DecodingError::NotANumber); } else if neg_const == -1 && chr == b'0' { return Err(DecodingError::NegativeZero); } } else { return Err(DecodingError::EndOfFile); } The number of custom errors isn't an issue, but I'd highly recommend adding the byte offset (cursor location) as contextual information to all of the errors so you know exactly where in the input the decoder ran into a problem when an error is returned.
{ "domain": "codereview.stackexchange", "id": 45086, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "parsing, rust, error-handling", "url": null }
c++, serialization, type-safety Title: Type-safe number serialization-deserialization Question: I have written this code for serializing and deserializing integer and floating point numbers to/from vector/array of bytes. The aim of the code is to provide a simple interface to use, but make it as readable on the caller side as possible (e.g. not allow hiding type conversions). This code doesn't cover runtime validation on purpose. It is expected that the user will check that the stream has enough bytes to read and that the resulting values can be used safely (signaling NaN etc.), it can be done by wrapping calls to these functions into "safe" versions that do the runtime checks. I've included a short example at the end of how it can be used (wandbox link with this code). I'm interested in any suggestions or any kind of input (goals, readability, safety, performance, code style, etc.). // Serialization.h //#pragma once #include <array> #include <bit> #include <type_traits> #include <vector> #include <stdexcept> namespace Serialization { template<typename Num, typename NumArg> void AppendNumber(std::vector<std::byte>& inOutByteStream, NumArg number) { static_assert(std::is_same_v<typename std::decay<NumArg>::type, Num>, "We should provide argument of the same type that we want to write. If you want to make conversion, you can use WriteNumberNarrowCast or WriteNumberWideCast"); static_assert(std::is_arithmetic_v<Num>, "Type should be ariphmetic to be serialized with WriteNumber"); static_assert(sizeof(std::array<std::byte, sizeof(Num)>) == sizeof(Num), "Unexpected std::array layout"); static_assert(std::is_standard_layout_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array layout"); static_assert(std::is_trivially_constructible_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation"); static_assert(std::is_trivially_copyable_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation");
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety const auto* byteRepresentation = std::bit_cast<std::array<std::byte, sizeof(Num)>*>(&number); if constexpr (std::endian::native == std::endian::little) { inOutByteStream.insert( inOutByteStream.end(), std::begin(*byteRepresentation), std::end(*byteRepresentation) ); } else if constexpr (std::endian::native == std::endian::big) { inOutByteStream.insert( inOutByteStream.end(), std::rbegin(*byteRepresentation), std::rend(*byteRepresentation) ); } else { throw std::logic_error("Mixed entian is not supported"); } } template<typename Num, typename NumArg, typename ByteStream> void WriteNumber(ByteStream& inOutByteStream, NumArg number, size_t& cursorPos) { static_assert(std::is_same_v<typename std::decay<NumArg>::type, Num>, "We should provide argument of the same type that we want to write. If you want to make conversion, you can use WriteNumberNarrowCast or WriteNumberWideCast"); static_assert(std::is_arithmetic_v<Num>, "Type should be ariphmetic to be serialized with WriteNumber"); static_assert(sizeof(std::array<std::byte, sizeof(Num)>) == sizeof(Num), "Unexpected std::array layout"); static_assert(std::is_standard_layout_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array layout"); static_assert(std::is_trivially_constructible_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation"); static_assert(std::is_trivially_copyable_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation"); const auto* byteRepresentation = std::bit_cast<std::array<std::byte, sizeof(Num)>*>(&number);
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety if constexpr (std::endian::native == std::endian::little) { std::copy( std::begin(*byteRepresentation), std::end(*byteRepresentation), std::begin(inOutByteStream) + cursorPos ); } else if constexpr (std::endian::native == std::endian::big) { std::copy( std::rbegin(*byteRepresentation), std::rend(*byteRepresentation), std::begin(inOutByteStream) + cursorPos ); } else { throw std::logic_error("Mixed entian is not supported"); } cursorPos += sizeof(Num); } template<typename Num, typename NumArg> void AppendNumberNarrowCast(std::vector<std::byte>& inOutByteStream, NumArg number) { static_assert(std::is_convertible_v<NumArg, Num>, "Argument type should be convertible to the data type"); static_assert(sizeof(NumArg) >= sizeof(Num), "WriteNumberNarrowCast called with a value of smaller type, that may be a sign of a logical error or inefficient use of the stream space"); static_assert(std::is_signed_v<NumArg> == std::is_signed_v<Num>, "The provided type has different signess"); AppendNumber<Num>(inOutByteStream, static_cast<Num>(number)); } template<typename Num, typename NumArg> void AppendNumberWideCast(std::vector<std::byte>& inOutByteStream, NumArg number) { static_assert(std::is_convertible_v<NumArg, Num>, "Argument type should be convertible to the data type"); static_assert(sizeof(NumArg) <= sizeof(Num), "WriteNumberWideCast called with a value of bigger type, that may be a sign of a logical error or potential data loss"); static_assert(std::is_signed_v<NumArg> == std::is_signed_v<Num>, "The provided type has different signess"); AppendNumber<Num>(inOutByteStream, static_cast<Num>(number)); }
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety AppendNumber<Num>(inOutByteStream, static_cast<Num>(number)); } template<typename Num, typename NumArg, typename ByteStream> void WriteNumberNarrowCast(std::vector<std::byte>& inOutByteStream, NumArg number, size_t& cursorPos) { static_assert(std::is_convertible_v<NumArg, Num>, "Argument type should be convertible to the data type"); static_assert(sizeof(NumArg) >= sizeof(Num), "WriteNumberNarrowCast called with a value of smaller type, that may be a sign of a logical error or inefficient use of the stream space"); static_assert(std::is_signed_v<NumArg> == std::is_signed_v<Num>, "The provided type has different signess"); WriteNumber<Num>(inOutByteStream, static_cast<Num>(number), cursorPos); } template<typename Num, typename NumArg, typename ByteStream> void WriteNumberWideCast(std::vector<std::byte>& inOutByteStream, NumArg number, size_t& cursorPos) { static_assert(std::is_convertible_v<NumArg, Num>, "Argument type should be convertible to the data type"); static_assert(sizeof(NumArg) <= sizeof(Num), "WriteNumberWideCast called with a value of bigger type, that may be a sign of a logical error or potential data loss"); static_assert(std::is_signed_v<NumArg> == std::is_signed_v<Num>, "The provided type has different signess"); WriteNumber<Num>(inOutByteStream, static_cast<Num>(number), cursorPos); }
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety WriteNumber<Num>(inOutByteStream, static_cast<Num>(number), cursorPos); } template<typename Num, typename ByteStream> Num ReadNumber(const ByteStream& inOutByteStream, size_t& cursorPos) { static_assert(std::is_arithmetic_v<Num>, "Type should be ariphmetic to be deserialized with ReadNumber"); static_assert(sizeof(std::array<std::byte, sizeof(Num)>) == sizeof(Num), "Unexpected std::array layout"); static_assert(std::is_standard_layout_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array layout"); static_assert(std::is_trivially_constructible_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation"); static_assert(std::is_trivially_copyable_v<std::array<std::byte, sizeof(Num)>>, "Unexpected std::array implementation"); Num number; auto* byteRepresentation = std::bit_cast<std::array<std::byte, sizeof(Num)>*>(&number); const size_t lastCursorPos = cursorPos; if constexpr (std::endian::native == std::endian::little) { std::copy( inOutByteStream.begin() + lastCursorPos, inOutByteStream.begin() + (lastCursorPos + sizeof(Num)), byteRepresentation->begin() ); } else if constexpr (std::endian::native == std::endian::big) { std::copy( inOutByteStream.rbegin() + (inOutByteStream.size() - lastCursorPos - sizeof(Num)), inOutByteStream.rbegin() + (inOutByteStream.size() - lastCursorPos), byteRepresentation->begin() ); } else { throw std::logic_error("Mixed endian is not supported"); } cursorPos += sizeof(Num); return number; } } // example_main.cpp #include <cstdint> #include <vector> #include <iostream> //#include "Serialization.h" using u8 = uint8_t; using f32 = float; using f64 = double;
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety //#include "Serialization.h" using u8 = uint8_t; using f32 = float; using f64 = double; int main() { std::vector<std::byte> byteStream; const size_t expectedBytesToRead = 5; byteStream.reserve(expectedBytesToRead); // serialization side const int someValue1 = 42; //Serialization::AppendNumber<u8>(byteStream, someValue1); // fails to compile, implicit narrow cast //Serialization::AppendNumberNarrowCast<u8>(byteStream, someValue1); // fails to compile, different signess Serialization::AppendNumber<u8>(byteStream, static_cast<u8>(someValue1)); // good const f64 someValue2 = 0.25; // some test value that can be exactly represented as f32 //Serialization::AppendNumber<f32>(byteStream, someValue2); // fails to compile, implicit narrow cast Serialization::AppendNumberNarrowCast<f32>(byteStream, someValue2); // good // deserialization side size_t cursor = 0; const int someResultValue1 = Serialization::ReadNumber<u8>(byteStream, cursor); const f32 someResultValue2 = Serialization::ReadNumber<f32>(byteStream, cursor); // validate the result std::cout << ((someResultValue1 == someValue1 && someResultValue2 == someValue2 && cursor == expectedBytesToRead) ? "passed" : "failed"); }
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety Answer: Reduce responsibilities Your AppendNumber() family of functions do too much; they not only take care of serialization, but also deal with conversions and offsets into the output container. This complicates these functions, and at the same time makes them less general. Consider having only one AppendNumber() function that converts given value to binary form, and then passes it to an output iterator that will take care of storing the binary data. The caller can do the conversion and pass whatever iterator is necessary so the data ends up in the right place. You can still make helper functions to do these things if it is not already trivial to do. For example: template<typename T, typename OutputIt> OutputIt AppendNumber(OutputIt output, T value) { … const auto* bytes = std::bit_cast<…>(…); if constexpr (std::endian::native == std::endian::little) { std::copy(std::begin(bytes), std::end(bytes), output); } … return output; } Now you can write: std::vector<std::byte> bytes(5); auto cursor = std::begin(bytes); // you can just add an offset here cursor = AppendNumber<std::uint8_t>(cursor, 42); cursor = AppendNumber<float>(cursor, 0.25); I've used the same interface as std::copy() and many other STL algorithms use: they take iterators by value, and possibly return the value of the iterator after they are done. Note that now you are also no longer required to serialize to a std::vector<byte>, you can serialize to anything that supports iterators. You can even serialize directly to a file: std::ofstream file("serialized.bin"); auto cursor = std::ostreambuf_iterator(file); cursor = AppendNumber<std::uint8_t>(cursor, 42); …
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety If it is more suitable for your application, you could of course decide to pass the iterator by reference, so you don't need to look at the return value. As for conversions: the above will use implicit casting. When combined with compiler warnings about unsafe casts (using -Wconversion for example), I would consider this fine. It will deduce T here, so you could also use the convention in your code that you always have to write something like: double someValue2 = 0.25; cursor = AppendNumber(cursor, NarrowCast<float>(someValue2)); Where NarrowCast() is now a utility function whose sole responsibility is narrow casting of values. Note how you can now add different ways to cast, without having to add new AppendNumber*() functions. You can also consider enforcing that an explicit cast operation has to be used, by making the cast functions actually be classes that hold their cast value: class ExplicitCast {}; template<typename T> class NarrowCast: ExplicitCast { T value; public: template<typename Arg> NarrowCast(Arg number): value(number) { static_assert(…); } T get() const { return value; } } template<typename T, typename OutputIt> OutputIt AppendNumber(OutputIt output, T value) { static_assert(std::is_base_of_v<ExplicitCast, T>, "value must be explicitly cast with a safe cast operation"); … const auto* bytes = std::bit_cast<…>(&value.get()); … }
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
c++, serialization, type-safety reserve() does not do what you want I see in your example that you use reserve() to add space to a vector. However, this is just changes the capacity, not the size. It will only ensure that calling push_back() will not require reallocations until the capacity is reached, but after calling AppendNumber() as in your example, byteStream.size() will still be zero. The correct way is to use resize(), or use an iterator that will call push_back() for you, for example by using std::back_inserter(): std::vector<std::byte> bytes; auto cursor = std::back_inserter(bytes); AppendNumber<std::uint8_t>(cursor, 42); AppendNumber<float>(cursor, 0.25); Alternatives Instead of using output iterators, you could pass in an output stream. This makes it easier to serialize directly to a stream object like a file. And if you want to serialize to a std::vector, then since C++23 you could use std::spanstream as an adapter, although typically you would then use a std::basic_stringstream<std::byte> as a container instead. You could then also make SerializeNumber() a class instead of a function, and add overloads for std::operator<<(std::ostream&), so you can write something like: std::ofstream file("serialized.bin"); file << SerializeNumber(NarrowCast<float>(0.25));
{ "domain": "codereview.stackexchange", "id": 45087, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, serialization, type-safety", "url": null }
python, playing-cards Title: Combo Matching in a digital implementation of Reiner Knizia's 'Schotten Totten' Question: I'm implementing Reiner Knizia's card game 'Schotten Totten' in Python. It's a card game for two players, where you compete to claim boundary stones between you and your opponent by forming poker-like combinations of three cards on each side of the stone. My goal is to make the implementation easily moddable, so that users can implement their own rule variations (for example, change the distribution of the cards, the amount of boundary stones, the amount of cards required to complete a combo, etc.) and that the user can also add their own combo types to the game. I'm in the process of implementing the combo matching code. In the original game, there are five combo types, in order of rank: Equal color and consecutive values Equal values Equal color Consecutive values Anything else A higher ranked combination always beats a lower ranked combinaton, regardless of card value. When two sets of cards have the same rank, then the highest combined card value wins. There are two relevant questions for any set of cards that my code is trying to answer: if the set is complete, what's the best matching combo? if the set is incomplete, what's the best possible completion based on the cards that aren't in play yet? (Players may claim a stone early if their complete combo beats out any possible completion of an opponent's incomplete set of cards). I'm wondering if my code is readable, easily extensible, and if the structure makes sense. Any other feedback is also welcome. #card.py from dataclasses import dataclass, field
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards from dataclasses import dataclass, field def _card_id_generator(): """ This generator function yields a unique card ID each time it's invoked. This is to ensure that the distinct identity of each card is maintained in set operations when there are multiple copies of the same card in a user-defined game variant. """ card_id = 0 while True: yield card_id card_id += 1 _card_ids = _card_id_generator() @dataclass(frozen=True) class Card: """ Represents a playing card with a color, value, and unique ID. """ color: str value: int id: int = field(default_factory=lambda: next(_card_ids)) def __lt__(self, other): return self.value < other.value def __add__(self, other): return self.value + other.value def __repr__(self): return f'Card(color={self.color!r}, value={self.value})' #available_combos.py from collections import defaultdict from collections.abc import Iterator, Sequence from itertools import chain from typing import Protocol from card import Card class Combo(Protocol): name: str rank: int n_cards_complete_combo: int def is_match(self, cards: Sequence[Card]) -> bool: ... def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: ... class HelperStepSize: """ A helper class to handle operations related to the step size in a combo. Args: n_cards_complete_combo (int): The number of cards required to complete the combo. Must be larger than 0. step_size (int): The required step size of the values of the cards that make up the combo. Must be larger than 0. """ def __init__(self, n_cards_complete_combo: int, step_size: int): self._n_cards_complete_combo = n_cards_complete_combo self._step_size = step_size
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def is_match(self, cards: Sequence[Card]) -> bool: """ Checks if the given cards match the combo criteria. 'cards' may be an empty Sequence. """ return len(cards) == self._n_cards_complete_combo and self._cards_have_correct_step_size(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: """ Finds the best completion for the given cards using the available cards. Both 'cards_to_complete' and 'available_cards' may be an empty Sequence. If no valid completion is found, returns an empty list. """ card_samples = self._select_one_card_per_value(cards_to_complete, available_cards) highest_value, lowest_value = max(card_samples.keys(), default=0), min(card_samples.keys(), default=0) for values_to_test in self._generate_values_to_test(highest_value, lowest_value): cards_to_test = self._select_cards_to_test(card_samples, values_to_test) if self._are_cards_to_test_valid(cards_to_test, cards_to_complete): return cards_to_test return [] def _cards_have_correct_step_size(self, cards: Sequence[Card]) -> bool: """ Checks if the sorted values of 'cards' all have a step size that equals 'self._step_size'. """ cards = sorted(cards) for i in range(1, len(cards)): if cards[i].value - cards[i - 1].value != self._step_size: return False return True
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards @staticmethod def _select_one_card_per_value(cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> dict[int, Card]: """ Selects one card per value from the given 'cards_to_complete' and 'available_cards'. Gives priority to cards from 'cards_to_complete' if both 'cards_to_complete' and 'available_cards' contain a valid sample. """ card_samples = {card.value: card for card in available_cards} card_samples.update({card.value: card for card in cards_to_complete}) return card_samples def _generate_values_to_test(self, highest_value: int, lowest_value: int) -> Iterator[list[int]]: """ Returns sequences of values in descending order, each containing 'self._n_cards_complete_combo' values, and all values having a step size equal to 'self._step_size'. The highest possible value of a sequence is 'highest_value', and the lowest possible value is 'lowest_value'. For example, when highest_value=8, lowest_value=2, self._step_size=2 and self._n_cards_complete_combo=3, this will yield: [8, 6, 4], [7, 5, 3], [6, 4, 2]. """ min_value_spread = self._step_size * (self._n_cards_complete_combo - 1) while highest_value - lowest_value >= min_value_spread: valid_range = range(highest_value, lowest_value - 1, -self._step_size) yield list(valid_range[:self._n_cards_complete_combo]) highest_value -= 1 @staticmethod def _select_cards_to_test(card_samples: dict[int, Card], values_to_test: list[int]) -> list[Card]: """ Selects cards from the 'card_samples' dictionary based on the values in 'values_to_test'. """ cards_to_test = [] for value in values_to_test: if card := card_samples.get(value): cards_to_test.append(card) return cards_to_test
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def _are_cards_to_test_valid(self, cards_to_test: list[Card], cards_to_complete: Sequence[Card]) -> bool: """ Checks if the selected cards to test are valid: all cards in 'cards_to_complete' must appear in 'cards_to_test', and 'cards_to_test' must pass the criteria of 'self.is_match'. """ return all(card in cards_to_test for card in cards_to_complete) and self.is_match(cards_to_test) class HelperEqualAttribute: """ A helper class to handle operations related to equal attributes in a combo. Args: n_cards_complete_combo (int): The number of cards required to complete the combo. Must be larger than 0. attr_to_test (str): The attribute of the card that needs to be equal for all cards in the combo. Supported attributes: 'value' or 'color'. """ def __init__(self, n_cards_complete_combo: int, attr_to_test: str): self._n_cards_complete_combo = n_cards_complete_combo self._attr_to_test = attr_to_test def is_match(self, cards: Sequence[Card]): """ Checks if the given cards match the combo criteria. 'cards' may be an empty Sequence. """ return len(cards) == self._n_cards_complete_combo and self._cards_have_eq_attr(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: """ Finds the best completion for the given cards using the available cards. Both 'cards_to_complete' and 'available_cards' may be an empty Sequence. If no valid completion is found, returns an empty list. """ completions = [] for cards_to_test in self._prepare_cards_to_test(cards_to_complete, available_cards): if self._are_cards_to_test_valid(cards_to_test, cards_to_complete): completions.append(cards_to_test) return max(completions, default=[])
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def _eq_attr(self, card: Card): """Shorthand for 'getattr(card, self._attr_to_test)'.""" return getattr(card, self._attr_to_test) def _cards_have_eq_attr(self, cards: Sequence[Card]): """Checks if 'self._attr_to_test' matches for all cards.""" return len({self._eq_attr(card) for card in cards}) == 1 def _prepare_cards_to_test(self, cards_to_complete: Sequence[Card], available_cards: Sequence) -> Iterator[list[Card]]: """Organizes cards for testing, grouping them by attribute value. - If the number of cards required to complete the combo is less than or equal to `self._n_cards_complete_combo`, all cards from `cards_to_complete` are included. - If additional cards are needed to meet `self._n_cards_complete_combo`, the method adds the highest-valued cards from `available_cards`. """ ac_by_value = sorted(available_cards, reverse=True) cards_by_attr = defaultdict(list) for card in chain(cards_to_complete, ac_by_value): if len(cards_by_attr[self._eq_attr(card)]) < self._n_cards_complete_combo: cards_by_attr[self._eq_attr(card)].append(card) for cards_to_test in cards_by_attr.values(): yield cards_to_test def _are_cards_to_test_valid(self, cards_to_test: Sequence[Card], cards_to_complete: Sequence[Card]): """ Checks if the selected cards to test are valid: all cards in 'cards_to_complete' must appear in 'cards_to_test', and 'cards_to_test' must pass the criteria in 'self.is_match'. """ return all(card in cards_to_test for card in cards_to_complete) and self.is_match(cards_to_test) class ComboAnyCards: """ All cards allowed. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int): self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def is_match(self, cards: Sequence[Card]) -> bool: if len(cards) == self.n_cards_complete_combo: return True def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: cards_to_add = self._select_highest_cards_to_add(cards_to_complete, available_cards) cards_to_test = [*cards_to_complete, *cards_to_add] return cards_to_test if self.is_match(cards_to_test) else [] def _select_highest_cards_to_add(self, cards_to_complete, available_cards): n_cards_to_add = self.n_cards_complete_combo - len(cards_to_complete) return sorted(available_cards, reverse=True)[:n_cards_to_add] def __repr__(self): return f'{self.__class__.__name__}(name={self.name!r}, rank={self.rank}, n_cards_complete_combo={self.n_cards_complete_combo})' class ComboStepSizeOne: """ Cards must have consecutive values. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int): self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_step_size = HelperStepSize(self.n_cards_complete_combo, step_size=1) def is_match(self, cards: Sequence[Card]) -> bool: return self._helper_step_size.is_match(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: return self._helper_step_size.best_completion(cards_to_complete, available_cards) def __repr__(self): return f'{self.__class__.__name__}(name={self.name!r}, rank={self.rank}, n_cards_complete_combo={self.n_cards_complete_combo})'
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards class ComboEqualColors: """ Cards must have equal colors. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int): self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_equal_colors = HelperEqualAttribute(self.n_cards_complete_combo, attr_to_test='color') def is_match(self, cards: Sequence[Card]) -> bool: return self._helper_equal_colors.is_match(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: return self._helper_equal_colors.best_completion(cards_to_complete, available_cards) def __repr__(self): return f'{self.__class__.__name__}(name={self.name!r}, rank={self.rank}, n_cards_complete_combo={self.n_cards_complete_combo})' class ComboEqualValues: """ Cards must have equal values. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int): self.name = name self.rank = rank self.n_cards_complete_combo: int = n_cards_complete_combo self._helper_equal_colors = HelperEqualAttribute(self.n_cards_complete_combo, attr_to_test='value') def is_match(self, cards: Sequence[Card]) -> bool: return self._helper_equal_colors.is_match(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: return self._helper_equal_colors.best_completion(cards_to_complete, available_cards) def __repr__(self): return f'{self.__class__.__name__}(name={self.name!r}, rank={self.rank}, n_cards_complete_combo={self.n_cards_complete_combo})'
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards class ComboEqualColorsStepSizeOne: """ Cards must have both equal colors and consecutive values. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int): self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_equal_colors = HelperEqualAttribute(self.n_cards_complete_combo, attr_to_test='color') self._helper_step_size = HelperStepSize(self.n_cards_complete_combo, step_size=1) def is_match(self, cards: Sequence[Card]) -> bool: return self._helper_equal_colors.is_match(cards) and self._helper_step_size.is_match(cards) def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> list[Card]: completions = [] for available_cards_to_test in self._prepare_available_cards_to_test(available_cards): completion = self._helper_step_size.best_completion(cards_to_complete, available_cards_to_test) if self.is_match(completion): completions.append(completion) return max(completions, default=[]) @staticmethod def _prepare_available_cards_to_test(available_cards: Sequence[Card]) -> Iterator[list[Card]]: """ Prepares available cards for testing by grouping them by color. """ cards_by_color = defaultdict(list) for card in available_cards: cards_by_color[card.color].append(card) for available_cards_to_test in cards_by_color.values(): yield available_cards_to_test def __repr__(self): return f'{self.__class__.__name__}(name={self.name!r}, rank={self.rank}, n_cards_complete_combo={self.n_cards_complete_combo})' #active_combos.py from collections.abc import Iterable, Sequence from available_combos import Combo from card import Card
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards class ActiveCombos: def __init__(self, active_combos: Iterable[Combo]): self.active_combos: list[Combo] = sorted(active_combos, key=lambda combo: combo.rank) def best_match(self, cards: Sequence[Card]) -> Combo | None: """ Matches 'cards' with the best possible combo type in 'active_combos'. """ for combo in self.active_combos: if combo.is_match(cards): return combo def best_completion(self, cards_to_complete: Sequence[Card], available_cards: Sequence[Card]) -> tuple[Combo, list[Card]] | None: """ Finds the best completion for the given cards to complete a combo among the active combos. """ for combo in self.active_combos: if completion := combo.best_completion(cards_to_complete, available_cards): return combo, completion #settings.py from collections.abc import Iterable from dataclasses import dataclass from available_combos import Combo, ComboAnyCards, ComboStepSizeOne, ComboEqualColors, ComboEqualValues, ComboEqualColorsStepSizeOne @dataclass class GameSettings: card_colors: Iterable[str] card_values: Iterable[int] hand_size: int n_targets: int target_name: str max_n_cards_complete_combo: int active_combos: Iterable[Combo] schotten_totten_settings = GameSettings( card_colors=('red', 'green', 'blue', 'yellow', 'brown', 'purple'), card_values=(1, 2, 3, 4, 5, 6, 7, 8, 9), hand_size=6, n_targets=9, target_name='stone', max_n_cards_complete_combo=3, active_combos=( ComboEqualColorsStepSizeOne(name='COLOR-RUN', rank=1, n_cards_complete_combo=3), ComboEqualValues(name='THREE OF A KIND', rank=2, n_cards_complete_combo=3), ComboEqualColors(name='COLOR', rank=3, n_cards_complete_combo=3), ComboStepSizeOne(name='RUN', rank=4, n_cards_complete_combo=3), ComboAnyCards(name='SUM', rank=5, n_cards_complete_combo=3) ) )
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards # User can add custom settings if they wish. # main.py # Intended to show functionality of the combo matching. from card import Card from active_combos import ActiveCombos from settings import schotten_totten_settings s = schotten_totten_settings combos = ActiveCombos(s.active_combos) cards_to_test = [ [Card('blue', 1), Card('blue', 3), Card('blue', 2)], [Card('blue', 3), Card('red', 2)], [Card('green', 5)], [] ] available_cards = [Card('green', 4), Card('blue', 5), Card('red', 5), Card('green', 3)] for cards in cards_to_test: print(f'Cards to test: {cards}') print(f'Match: {combos.best_match(cards)}') print(f'Best Completion: {combos.best_completion(cards, available_cards)}') print("") Answer: Overall it's pretty sane. I'll call out an assorted laundry list of suggestions - _card_id_generator is really just an itertools.count, and you don't even care about the iterator itself, just its __next__; so: import itertools """ This generator function yields a unique card ID each time it's invoked. This is to ensure that the distinct identity of each card is maintained in set operations when there are multiple copies of the same card in a user-defined game variant. """ _get_card_id = itertools.count().__next__ @dataclass(frozen=True) class Card: """ Represents a playing card with a color, value, and unique ID. """ id: int = field(default_factory=_get_card_id)
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards An alternative way of writing the above would be making a nested function that increments and returns a non-local, but I don't consider that a particularly better idea. You're missing various typehints. __lt__(self, other: 'Card') -> bool for one. __init__ always returns -> None. _select_highest_cards_to_add needs typehints. I strongly recommend running mypy; when I was refactoring it caught a bunch of real issues. You use Sequence in various places for your card hand, but since the order of the hand does not matter, you should generalise to Collection. __add__ is typically assumed to return a new instance of Card and not a bare integer. This reveals a design problem in your API: how do you easily get the Card with a given value? You can't use your current constructor because it will assign a new monotonic ID, which doesn't represent reality. Probably you should scrap the ID altogether, which would make constructing equivalent Card instances easy. At the same time you can simplify from @dataclass to NamedTuple; this will allow set and sort operations and is naturally immutable. You don't even use __add__ it seems. What you would use is __sub__ between two card values, which would return an int. You use list in a lot of places where you should be using tuple, as the latter is immutable. In some cases list is inescapable like when you incrementally build lists on the inside of a default dictionary. I don't find it helpful that Combo is a Protocol. Protocols are most useful in declaring callables with well-defined parameter names and types, etc. Here, Combo is basically an abstract class from which your other combinations should inherit. You can use abc if you want, but usually I just declare abstract methods as throwing NotImplementedError. This is not a good iteration model: while highest_value - lowest_value >= min_value_spread: highest_value -= 1
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards Instead you should be running through a range. _generate_values_to_test can simply yield integer ranges rather than lists. Args documentation in HelperStepSize is in the incorrect place; it should be documented on the constructor. best_completion may be rewritten as a generator on which you call next(best_completion, []). _cards_have_correct_step_size may be rewritten as a call to all() on a generator. The dictionary update call in _select_one_card_per_value may be rewritten as the | union of two dictionary comprehensions; or one dictionary comprehension of the form return { card.value: card for card in chain(available_cards, cards_to_complete) } _select_cards_to_test may be rewritten as a call to filter on a generator (not a list comprehension). best_completion may be rewritten so that max is called on a generator and not an incrementally-constructed list. This: all(card in cards_to_test for card in cards_to_complete) and self.is_match(cards_to_test) is effectively just a subset containment predicate: set(cards_to_complete) <= set(cards_to_test) _eq_attr is a smell. There's no way to make that code type-safe. This should be re-worked so that there are no arbitrary attributes. The easy way is to accept a transformation callable that produces a member from a class instance, and uses the member type as a Generic type variable. _prepare_cards_to_test uses expression cards_by_attr[self._eq_attr(card)] that should be assigned to a temporary variable for reuse. This loop: for cards_to_test in cards_by_attr.values(): yield cards_to_test
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards should not exist; simply return cards_by_attr.values(). cards_to_test = [*cards_to_complete, *cards_to_add], assuming that both variables are lists, can just use + concatenation instead of unpack-and-list-literal. print("") is just print(). Your __repr__ definitions are not used, so I would just delete them. Convert your rule demonstration code into unit tests. I did this to verify that my refactoring produces output the same as that of the original code. Suggested Covering most of the above, from collections import defaultdict from collections.abc import Iterable, Iterator from itertools import chain from typing import NamedTuple, Collection, TypeVar, Generic, Callable, DefaultDict class Card(NamedTuple): """ Represents a playing card with a color and value """ color: str value: int def __lt__(self, other: 'Card') -> bool: return self.value < other.value def __add__(self, diff: int) -> 'Card': return Card(color=self.color, value=self.value + diff) def __sub__(self, other: 'Card') -> int: return self.value - other.value # Convenience methods for helper transformation def get_color(self) -> str: return self.color def get_value(self) -> int: return self.value class Combo: name: str rank: int n_cards_complete_combo: int def is_match(self, cards: Collection[Card]) -> bool: raise NotImplementedError() def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: raise NotImplementedError() class HelperStepSize: """ A helper class to handle operations related to the step size in a combo. """
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def __init__(self, n_cards_complete_combo: int, step_size: int) -> None: """ Args: n_cards_complete_combo: The number of cards required to complete the combo. Must be larger than 0. step_size: The required step size of the values of the cards that make up the combo. Must be larger than 0. """ self._n_cards_complete_combo = n_cards_complete_combo self._step_size = step_size def is_match(self, cards: Collection[Card]) -> bool: """ Checks if the given cards match the combo criteria. 'cards' may be an empty Collection. """ return len(cards) == self._n_cards_complete_combo and self._cards_have_correct_step_size(cards) def all_completions( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> Iterator[tuple[Card, ...]]: card_samples = self._select_one_card_per_value(cards_to_complete, available_cards) highest_value = max(card_samples.keys(), default=0) lowest_value = min(card_samples.keys(), default=0) for values_to_test in self._generate_values_to_test(highest_value, lowest_value): cards_to_test = tuple(self._select_cards_to_test(card_samples, values_to_test)) if self._are_cards_to_test_valid(cards_to_test, cards_to_complete): yield cards_to_test def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: """ Finds the best completion for the given cards using the available cards. Both 'cards_to_complete' and 'available_cards' may be an empty Collection. If no valid completion is found, returns an empty tuple. """ return next(self.all_completions(cards_to_complete, available_cards), ())
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards @staticmethod def _hand_steps(hand: Collection[Card]) -> Iterator[int]: card_seq = sorted(hand) for this_card, next_card in zip(card_seq[:-1], card_seq[1:]): yield next_card - this_card def _cards_have_correct_step_size(self, cards: Collection[Card]) -> bool: """ Checks if the sorted values of 'cards' all have a step size that equals 'self._step_size'. """ return all(step == self._step_size for step in self._hand_steps(cards)) @staticmethod def _select_one_card_per_value( cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> dict[int, Card]: """ Selects one card per value from the given 'cards_to_complete' and 'available_cards'. Gives priority to cards from 'cards_to_complete' if both 'cards_to_complete' and 'available_cards' contain a valid sample. """ return { card.value: card for card in chain(available_cards, cards_to_complete) } def _generate_values_to_test( self, highest_value: int, lowest_value: int, ) -> Iterator[range]: """ Returns Collections of values in descending order, each containing 'self._n_cards_complete_combo' values, and all values having a step size equal to 'self._step_size'. The highest possible value of a sequence is 'highest_value', and the lowest possible value is 'lowest_value'. For example, when highest_value=8, lowest_value=2, self._step_size=2 and self._n_cards_complete_combo=3, this will yield: [8, 6, 4], [7, 5, 3], [6, 4, 2]. """ min_value_spread = self._step_size * (self._n_cards_complete_combo - 1) for upper_value in range(highest_value, lowest_value + min_value_spread - 1, -1): valid_range = range(upper_value, lowest_value - 1, -self._step_size) yield valid_range[:self._n_cards_complete_combo]
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards @staticmethod def _select_cards_to_test( card_samples: dict[int, Card], values_to_test: Iterable[int], ) -> Iterator[Card]: """ Selects cards from the 'card_samples' dictionary based on the values in 'values_to_test'. """ for value in values_to_test: card = card_samples.get(value) if card is not None: yield card def _are_cards_to_test_valid( self, cards_to_test: Collection[Card], cards_to_complete: Collection[Card], ) -> bool: """ Checks if the selected cards to test are valid: all cards in 'cards_to_complete' must appear in 'cards_to_test', and 'cards_to_test' must pass the criteria of 'self.is_match'. """ return set(cards_to_complete) <= set(cards_to_test) and self.is_match(cards_to_test) EqualAttr = TypeVar('EqualAttr') class HelperEqualAttribute(Generic[EqualAttr]): """ A helper class to handle operations related to equal attributes in a combo. """ def __init__( self, n_cards_complete_combo: int, attr_transform: Callable[[Card], EqualAttr], ) -> None: """ Args: n_cards_complete_combo: The number of cards required to complete the combo. Must be larger than 0. """ self._n_cards_complete_combo = n_cards_complete_combo self._eq_attr = attr_transform def is_match(self, cards: Collection[Card]) -> bool: """ Checks if the given cards match the combo criteria. 'cards' may be an empty Collection. """ return len(cards) == self._n_cards_complete_combo and self._cards_have_eq_attr(cards)
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def _all_completions( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> Iterator[tuple[Card, ...]]: for cards_to_test in self._prepare_cards_to_test(cards_to_complete, available_cards): if self._are_cards_to_test_valid(cards_to_test, cards_to_complete): yield tuple(cards_to_test) def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: """ Finds the best completion for the given cards using the available cards. Both 'cards_to_complete' and 'available_cards' may be an empty Collection. If no valid completion is found, returns an empty list. """ return max(self._all_completions(cards_to_complete, available_cards), default=()) def _cards_have_eq_attr(self, cards: Collection[Card]) -> bool: """Checks if 'self._attr_to_test' matches for all cards.""" return len({self._eq_attr(card) for card in cards}) == 1 def _prepare_cards_to_test( self, cards_to_complete: Collection[Card], available_cards: Collection, ) -> Collection[list[Card]]: """Organizes cards for testing, grouping them by attribute value. - If the number of cards required to complete the combo is less than or equal to `self._n_cards_complete_combo`, all cards from `cards_to_complete` are included. - If additional cards are needed to meet `self._n_cards_complete_combo`, the method adds the highest-valued cards from `available_cards`. """ ac_by_value = sorted(available_cards, reverse=True) cards_by_attr: DefaultDict[EqualAttr, list[Card]] = defaultdict(list) for card in chain(cards_to_complete, ac_by_value): cards_for_attr = cards_by_attr[self._eq_attr(card)] if len(cards_for_attr) < self._n_cards_complete_combo: cards_for_attr.append(card)
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards return cards_by_attr.values() def _are_cards_to_test_valid( self, cards_to_test: Collection[Card], cards_to_complete: Collection[Card], ) -> bool: """ Checks if the selected cards to test are valid: all cards in 'cards_to_complete' must appear in 'cards_to_test', and 'cards_to_test' must pass the criteria in 'self.is_match'. """ return all( card in cards_to_test for card in cards_to_complete ) and self.is_match(cards_to_test) class ComboAnyCards(Combo): """ All cards allowed. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int) -> None: self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo def is_match(self, cards: Collection[Card]) -> bool: return len(cards) == self.n_cards_complete_combo def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: cards_to_add = self._select_highest_cards_to_add(cards_to_complete, available_cards) cards_to_test = tuple(cards_to_complete) + tuple(cards_to_add) return cards_to_test if self.is_match(cards_to_test) else () def _select_highest_cards_to_add( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> list[Card]: n_cards_to_add = self.n_cards_complete_combo - len(cards_to_complete) return sorted(available_cards, reverse=True)[:n_cards_to_add] class ComboStepSizeOne(Combo): """ Cards must have consecutive values. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int) -> None: self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_step_size = HelperStepSize(self.n_cards_complete_combo, step_size=1)
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def is_match(self, cards: Collection[Card]) -> bool: return self._helper_step_size.is_match(cards) def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: return self._helper_step_size.best_completion(cards_to_complete, available_cards) class ComboEqualColors(Combo): """ Cards must have equal colors. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int) -> None: self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_equal_colors = HelperEqualAttribute(self.n_cards_complete_combo, Card.get_color) def is_match(self, cards: Collection[Card]) -> bool: return self._helper_equal_colors.is_match(cards) def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: return self._helper_equal_colors.best_completion(cards_to_complete, available_cards) class ComboEqualValues(Combo): """ Cards must have equal values. """ def __init__(self, name: str, rank: int, n_cards_complete_combo: int) -> None: self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_equal_values = HelperEqualAttribute(self.n_cards_complete_combo, Card.get_value) def is_match(self, cards: Collection[Card]) -> bool: return self._helper_equal_values.is_match(cards) def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: return self._helper_equal_values.best_completion(cards_to_complete, available_cards) class ComboEqualColorsStepSizeOne(Combo): """ Cards must have both equal colors and consecutive values. """
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def __init__(self, name: str, rank: int, n_cards_complete_combo: int) -> None: self.name = name self.rank = rank self.n_cards_complete_combo = n_cards_complete_combo self._helper_equal_colors = HelperEqualAttribute(self.n_cards_complete_combo, Card.get_color) self._helper_step_size = HelperStepSize(self.n_cards_complete_combo, step_size=1) def is_match(self, cards: Collection[Card]) -> bool: return self._helper_equal_colors.is_match(cards) and self._helper_step_size.is_match(cards) def _all_completions( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> Iterator[tuple[Card, ...]]: for available_cards_to_test in self._prepare_available_cards_to_test(available_cards): completion = self._helper_step_size.best_completion(cards_to_complete, available_cards_to_test) if self.is_match(completion): yield completion def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Card, ...]: return max(self._all_completions(cards_to_complete, available_cards), default=()) @staticmethod def _prepare_available_cards_to_test(available_cards: Collection[Card]) -> Iterator[list[Card]]: """ Prepares available cards for testing by grouping them by color. """ cards_by_color = defaultdict(list) for card in available_cards: cards_by_color[card.color].append(card) for available_cards_to_test in cards_by_color.values(): yield available_cards_to_test class ActiveCombos: def __init__(self, active_combos: Iterable[Combo]) -> None: self.active_combos: list[Combo] = sorted(active_combos, key=lambda combo: combo.rank)
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards def best_match(self, cards: Collection[Card]) -> Combo | None: """ Matches 'cards' with the best possible combo type in 'active_combos'. """ for combo in self.active_combos: if combo.is_match(cards): return combo return None def best_completion( self, cards_to_complete: Collection[Card], available_cards: Collection[Card], ) -> tuple[Combo | None, tuple[Card, ...]]: """ Finds the best completion for the given cards to complete a combo among the active combos. """ for combo in self.active_combos: completion = combo.best_completion(cards_to_complete, available_cards) if completion: return combo, completion return None, () class GameSettings(NamedTuple): card_colors: tuple[str, ...] card_values: tuple[int, ...] | range hand_size: int n_targets: int target_name: str max_n_cards_complete_combo: int active_combos: tuple[Combo, ...] SCHOTTEN_TOTTEN = GameSettings( card_colors=('red', 'green', 'blue', 'yellow', 'brown', 'purple'), card_values=range(1, 10), hand_size=6, n_targets=9, target_name='stone', max_n_cards_complete_combo=3, active_combos=( ComboEqualColorsStepSizeOne(name='COLOR-RUN', rank=1, n_cards_complete_combo=3), ComboEqualValues(name='THREE OF A KIND', rank=2, n_cards_complete_combo=3), ComboEqualColors(name='COLOR', rank=3, n_cards_complete_combo=3), ComboStepSizeOne(name='RUN', rank=4, n_cards_complete_combo=3), ComboAnyCards(name='SUM', rank=5, n_cards_complete_combo=3), ), ) def test() -> None: combos = ActiveCombos(SCHOTTEN_TOTTEN.active_combos) available_cards = (Card('green', 4), Card('blue', 5), Card('red', 5), Card('green', 3))
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
python, playing-cards cards_to_test: tuple[Card, ...] = Card('blue', 1), Card('blue', 3), Card('blue', 2) match = combos.best_match(cards_to_test) assert match.name == 'COLOR-RUN' assert match.rank == 1 assert match.n_cards_complete_combo == 3 combo, cards = combos.best_completion(cards_to_test, available_cards) assert combo is match assert cards == (Card('blue', 3), Card('blue', 2), Card('blue', 1)) cards_to_test = Card('blue', 3), Card('red', 2) assert combos.best_match(cards_to_test) is None combo, cards = combos.best_completion(cards_to_test, available_cards) assert combo.name == 'RUN' assert combo.rank == 4 assert combo.n_cards_complete_combo == 3 assert cards == (Card('green', 4), Card('blue', 3), Card('red', 2)) cards_to_test = Card('green', 5), assert combos.best_match(cards_to_test) is None combo, cards = combos.best_completion(cards_to_test, available_cards) assert combo.name == 'COLOR-RUN' assert combo.rank == 1 assert combo.n_cards_complete_combo == 3 assert cards == (Card('green', 5), Card('green', 4), Card('green', 3)) cards_to_test = () assert combos.best_match(cards_to_test) is None combo, cards = combos.best_completion(cards_to_test, available_cards) assert combo.name == 'RUN' assert combo.rank == 4 assert combo.n_cards_complete_combo == 3 assert cards == (Card('red', 5), Card('green', 4), Card('green', 3)) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 45088, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, playing-cards", "url": null }
go, mongodb Title: I have use this approch in my golang mongo REST APIs' DAO layer, need to clarify this is a good way or not Question: I have used this approach in my Golang MongoDB REST APIs' DAO layer, I need to clarify whether this is a good way or not, code is as follows, func CreateUser(user *models.User) *commons.RequestError { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() DB := connections.Connect() rst, err := DB.Collection("user").InsertOne(ctx, *user) if err != nil { commons.ErrorLogger.Println(err.Error()) connections.Disconnect(DB) return &commons.RequestError{StatusCode: http.StatusBadRequest, ErrorOccurredIn: "user_dao CreateUser", Err: err.Error()} } user.Id = rst.InsertedID.(primitive.ObjectID) connections.Disconnect(DB) return nil } Answer: Right, so there's quite a number of things that I would consider questionable here. Let's go through the code line by line and see what could be done differently: func CreateUser(user *models.User) *commons.RequestError {
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
go, mongodb Seeing as you stated that this is a function that is part of a REST API, the common approach here would be to pass in the request context. If for whatever reason the request context is cancelled, you want that cancellation to be propagated throughout. This includes using a context.WithCancel(context.Background()) in your main function, BTW. You're returning a pointer to some *commons.RequestError here, too. That's bad separation of concern. This function is concerned with taking DTO/entities and storing/fetching them from an underlying datastore. A RequestError suggests that the function is there to handle requests, which is the handler's job. I also don't see why you'd return an explicit type as an error. Implement the Error() string function on the commons.RequestError type, and you can simply use it as an error type. All in all, the function should look something more like this: func CreateUser(ctx context.Context, user *models.User) error { Now you used to create a context with timeout, which you can still do no problem, but instead of wrapping the context.Background(), you'd wrap the argument passed in, so: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() Becomes tCtx, cancel := context.WithTimeout(ctx, 10* time.Second) defer cancel() But if you pass in the context from a request, wrapping things in a timeout isn't that big of a requirement, because with a request context, if the connection times out, so does the context, and thus the cancellation of the context will be propagated. Leave the explicit timeout in or not, both are fine DB := connections.Connect() rst, err := DB.Collection("user").InsertOne(ctx, *user) if err != nil { commons.ErrorLogger.Println(err.Error()) connections.Disconnect(DB) return &commons.RequestError{StatusCode: http.StatusBadRequest, ErrorOccurredIn: "user_dao CreateUser", Err: err.Error()} }
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
go, mongodb This is the biggest issue with the code you've presented here. Worst case scenario, this means that every request that calls CreateUser will open a new connection to the underlying database, get a hard-coded collection (which probably underneath calls getConnectionInfos on mongoDB), just to insert a new document. What would make a lot more sense is to move this function to a type that has access to the collection ready to go: package repository type User struct { db *mongo.Collection } // optionally pass in config, options, etc... func NewUser(conn *mongo.Database) *User { return &User{ db: conn.Collection("user"), } } func (u *User) Create(ctx context.Context, user *models.User) error { rst, err := u.db.InsertOne(ctx, user) if err != nil { return err // or some local error/wrapped error. It's up to the handler to return a request error } user.Id = rst.InsertedID.(primitive.ObjectID) return nil } With that implemented, we don't need to rely on the connections(DB) call at the end, which I do hope is a connection pool, rather than a function that just spits out new connections every time this gets called. These are some of the things I'd look in to/reconsider based on a preliminary review. In addition to these things, I do have some other little nit-picks and comments that are more stylistic in nature, but mostly are based on the code review comments from the official golang repo, and are all widely accepted as good practice to follow, to the point where we might as well refer to it as being the ground-rules of idiomatic golang:
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
go, mongodb DB := ...: As a variable name, prefer db. connections.Foo(): implies either a global variable (which is almost always wrong) or a package called connections. If it's a package name, it's not very descriptive. Connections to what? All connections? net/http deals with connections, RPC calls do, too. If you go for the repository approach, DB connections usually are confined to an adaptor, which is probably a better name for this package commons: this is a package name that is strongly advised against, as once again it communicates very little in the way of what can be found here. What's more, having a commons package that is imported everywhere actively encourages bad practices (as exemplified here by the function responsible for storing data returning request errors). Read up on the SOLID principles, most of which are associated with OOP, but they still hold as very sensible concepts to adhere to. Specifically the SRP (Single Responsibility Principle), and apply it to a package: A package should do just one job, and do it well. It should focus solely on doing that one task, have a clear interface through which users can accomplish this task, and that interface should return clear indicators of success/failure. Using commons packages as part of your interface is by definition making the communication between callers more vague/broad/nebulous. Compare the following: Non-SRP version: package foo type Dependency interface { Some() error Complicated(ctx context.Context, data any, opts ...func()) (any, error) Interface() (*SomeType, error) } type T struct { f Dependency } func New(d Dependency) *T { return &T{ f: d, } }
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
go, mongodb type T struct { f Dependency } func New(d Dependency) *T { return &T{ f: d, } } func (t *T) DoSome(ctx context.Context, data *types.Data, opts ...func()) error { if len(opts) == 0 { if _, err := t.f.Complicated(ctx, data); err != nil { return &commons.ErrGenericFault{ Message: "foo.DoSome failed, no options given", Args: []any{*data}, Err: err, // note, this can be a problem } } return nil } // let's say passing in opts means we have to check other errors: r, err := t.f.Complicated(ctx, data, opts) if err != nil { // same as above, but append opts to args } // maybe depending on return value we need to check other errors // e.g. the opts specify the call can be performed asynchronously // when bulk-inserting or something, at the end we call `t.f.Some` to wait // for confirmation everything went well if err := t.f.Some(); err != nil { return &commons.ErrGenericFault{ Message: "batch operation failed at some point", Args: []any{*data}, // add opts Err: err, } } return nil }
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
go, mongodb Now the caller cannot easily differentiate between faults. They all return the same error type. The only way to really differentiate between any and all errors is by looking at the message itself, which means the caller has to know the internals of the function it is calling, it has to be aware of implementation details in order to accurately determine whether or not the error can/should be handled and how. What's more, I noted in the comment that including the error is risky here, because all errors are pointers to some common.ErrType. What if the Dependency here returns an error from the same commons package? What do I do with the potential multiple layers of custom errors, all packaged up in the same type? How to I extract the information that I really need, and to what extent is the caller served by this information? Does the caller to the above DoSome function need to know about the internal message strings of the foo package as well as all possible error strings associated with the dependencies of foo? That would be atrocious. Compare this to the same time, but with some added variables like this: var ( ErrNoOptionsSomeError = errors.New("failed DoSome, no options") ErrOptionsSomeError = errors.New("failed DoSome with options") ) And instead of the commons errors, you just return these error variables. They're exported, and are part of the contract. This is how this package indicates various specific errors, so it's trivial for the caller to differentiate by checking if the returned error is err == foo.ErrOptionsSomeError, or if you want to include more details: errors.Is(err, foo.ErrOptionsSomeError). To include more information, you'd return an error like so: if _, err := t.f.Complicated(ctx, data); err != nil { return fmt.Errorf("%s: %w", err, ErrNoOptionsSomeError) } Where %s prints out the underlying error as a string, and %w wraps the specific error.
{ "domain": "codereview.stackexchange", "id": 45089, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, mongodb", "url": null }
performance, algorithm, go, finance, memory-optimization Title: Aggregate transactions in slips Question: I wrote code to aggregate transactions in slips. I'm concerned with the performance of my code because it uses 3 loops that are nested so the time complexity will be cubic. This code won't scale well because if the number of slips or transactions are very large then it will take a long time to run. How can I improve my code in terms of performance and scalability? It would also help if you described your methodology for solving this problem. package main import ( "fmt" "strconv" ) type Slip struct { TransactionIDs []int } type Transaction struct { ID int Amount float64 Payout bool } type AggregatedSlipData struct { // Number of transactions per slip TransactionCount int // The sum of the transaction amounts of this slip // (a payout must be subtracted instead of added!) TotalAmount float64 } func main() { // Assume you have two distributed data sources. Your task is to // collect all data from these sources and return an aggregated result. slips := map[string]Slip{ "slip_23": Slip{ TransactionIDs: []int{123, 456}, }, "slip_42": Slip{ TransactionIDs: []int{789}, }, } transactions := []Transaction{ { ID: 123, Amount: 10.01, Payout: false, }, { ID: 456, Amount: 5.01, Payout: true, }, { ID: 789, Amount: 20.1, Payout: false, }, }
{ "domain": "codereview.stackexchange", "id": 45090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, go, finance, memory-optimization", "url": null }
performance, algorithm, go, finance, memory-optimization slipsWithTransactions := make(map[string][]Transaction) for k, v1 := range slips { slipsWithTransactions[(k[5:])] = make([]Transaction, 0, len(slips)) for _, v2 := range v1.TransactionIDs { for _, v3 := range transactions { if v3.ID ==v2 { transaction := Transaction{ ID: v3.ID, Amount: v3.Amount, Payout: v3.Payout, } slipsWithTransactions[(k[5:])] = append(slipsWithTransactions[k[5:]], transaction) } } } } fmt.Println("slipsWithTransactions: ", slipsWithTransactions) fmt.Println("") _ = slips _ = transactions aggregatedSlips := make(map[int]AggregatedSlipData) for k, v1 := range slipsWithTransactions { var sum float64 = 0 for _, v2 := range v1 { if v2.Payout == false { sum += v2.Amount } else { sum -= v2.Amount } } n, err := strconv.Atoi(k) if err != nil { panic(err) } aggregatedSlips[n] = AggregatedSlipData{ TransactionCount: len(v1), TotalAmount: sum, } } fmt.Printf("aggregatedSlips: %+v\n", aggregatedSlips) // Task: Use the two data sources above and create the following result: result := map[int]AggregatedSlipData{ 23: AggregatedSlipData{ TransactionCount: 2, // Number of transactions per slip TotalAmount: 5.0, // The sum of the transaction amounts of this slip (a payout must be subtracted instead of added!) }, 42: AggregatedSlipData{ TransactionCount: 1, TotalAmount: 20.1, }, } fmt.Printf("%+v\n", result) } Answer: How can I improve ... performance and scalability?
{ "domain": "codereview.stackexchange", "id": 45090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, go, finance, memory-optimization", "url": null }
performance, algorithm, go, finance, memory-optimization fmt.Printf("%+v\n", result) } Answer: How can I improve ... performance and scalability? use an appropriate data structure The inner loop makes a O(N) linear scan over the array of all transactions, for each slip transaction. There are two ways out of that. hash Preprocess all transactions to turn the in-memory array into a hash map. So we visit each transaction once to add it to the map, and visit it a second time when we loop over slip transaction IDs, with total of O(1) constant time complexity per slip transaction. If we naïvely copy array entries we wind up with about double the RAM usage. sort Perhaps we have a large number of transactions, which won't fit conveniently into RAM. Preprocess all transactions to turn them into a sorted list of transactions which we serialize to RDBMS or to a file. Similarly preprocess all slips so we have slip info sorted by transaction ID. Now do 2-way merge to consume those sorted lists. That makes it easy to match up transaction IDs within a constant memory footprint. Total time complexity is O(N log N) due to sorting. Memory complexity is whatever you allocated to achieve a rapid sort, for example /usr/bin/sort makes it easy to trade I/O cost against limited memory use. Consider computing the aggregate amount sum as you're looping, without waiting to post-process the result. Consider deleting the payout boolean, in favor of just using +/- sign of amount. break out a helper slipsWithTransactions[(k[5:])] = make( ... ) ... slipsWithTransactions[(k[5:])] = append( ... ) Remove that magic number 5 by defining a getSlipId() helper. While you're at it, break out the occasional helper so the overly long main() function will fit in a single screenful of code.
{ "domain": "codereview.stackexchange", "id": 45090, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, algorithm, go, finance, memory-optimization", "url": null }
c++, reinventing-the-wheel, c++20, optional Title: C++ std::optional implementation Question: Took a shot at implementing a subset of std::optional functionality. A lot of core features are there but some things like converting constructors, etc are missing as I just wanted to focus on the basic ideas. The implementation: #include <compare> #include <typeinfo> #include <utility> struct BadOptionalAccess : std::exception { const char* what() const noexcept override { return "Tried to access an Optional()'s value, but no value exists!"; } }; template<typename T> class Optional { public: Optional() noexcept { std::memset(m_data, 0, sizeof(T)); } Optional(const T& value) : m_has_value{true} { new (m_data) T(value); } template<typename... Args> Optional(std::in_place_t, Args&&... args) { emplace(std::forward<Args>(args)...); } Optional(const Optional& other) : m_has_value{other.m_has_value} { if (other.m_has_value) { new(m_data) T(other.value()); } } Optional(Optional&& other) noexcept : m_has_value{other.m_has_value} { if (other.has_value()) { new(m_data) T(std::move(other.value())); other.m_has_value = false; } } Optional& operator=(const Optional& other) { Optional temp {other}; temp.swap(*this); return *this; } Optional& operator=(Optional&& other) noexcept { Optional temp {std::move(other)}; temp.swap(*this); return *this; }
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
c++, reinventing-the-wheel, c++20, optional auto operator<=>(const Optional& other) const noexcept { if (!has_value() && !other.has_value()) { return std::strong_ordering::equal; } else if (!has_value() && other.has_value()) { return std::strong_ordering::less; } else if (has_value() && !other.has_value()) { return std::strong_ordering::greater; } else { return value() <=> other.value(); } } bool operator==(const Optional& other) const noexcept { return (*this <=> other) == std::strong_ordering::equal; } bool operator!=(const Optional& other) const noexcept { return !(*this == other); } explicit operator bool() const noexcept { return has_value(); } template<typename... Args> void emplace(Args&&... args) { reset(); new (m_data) T(std::forward<Args>(args)...); m_has_value = true; } template<typename U> T value_or(U&& default_value) { return has_value() ? std::move(**this) : static_cast<T>(std::forward<U>(default_value)); } void reset() { if (m_has_value) { T* val = reinterpret_cast<T*>(m_data); val->~T(); m_has_value = false; } } void swap(Optional& other) noexcept { // Do I need to do this? My first instinct was to do // an ordinary swap of the m_data's, but it seemed wrong // to do in case the types weren't trivially copyable/movable. // Maybe I should special case in those situations? if (other.has_value() && has_value()) { std::swap(*reinterpret_cast<T*>(m_data), *reinterpret_cast<T*>(other.m_data)); } else if (other.has_value()) { new (m_data) T(std::move(other.value())); } else if (has_value()) { new(other.m_data) T(std::move(value())); } std::swap(m_has_value, other.m_has_value); }
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
c++, reinventing-the-wheel, c++20, optional bool has_value() const noexcept { return m_has_value; } const T& value() const { return *ptr(); } const T& operator*() const& { return value(); } const T* operator->() const { return ptr(); } T& value() { return *ptr(); } T& operator*() & { return value(); } T&& operator*() && noexcept { return std::move(value()); } const T&& operator*() const&& noexcept { // not 100% sure how to use/test this overload. Why would an rvalue be const? return std::move(**this); } T* operator->() { return ptr(); } ~Optional() { reset(); } private: alignas(T) unsigned char m_data[sizeof(T)]; bool m_has_value = false; const T* ptr() const { if (!m_has_value) { throw BadOptionalAccess(); } return (reinterpret_cast<const T*>(m_data)); } T* ptr() { if (!m_has_value) { throw BadOptionalAccess(); } return (reinterpret_cast<T*>(m_data)); } }; template<typename T, typename... Args> Optional<T> makeOptional(Args&&... args) { return Optional<T>(std::in_place, std::forward<Args>(args)...); } Some tests: #define BOOST_TEST_MODULE optionaltest #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif // BOOST_TEST_DYN_LINK #include <boost/test/data/monomorphic.hpp> #include <boost/test/data/test_case.hpp> #include "Optional.h" #include <string> BOOST_AUTO_TEST_CASE(default_constructor_test) { Optional<int> o; } BOOST_AUTO_TEST_CASE(basic_constructors_test) { Optional<int> o1; Optional<int> o2 = 1; Optional<int> o3 = o2; // calls std::string( size_type count, CharT ch ) constructor Optional<std::string> o4(std::in_place, 3, 'A'); Optional<std::string> o5 = makeOptional<std::string>(3, 'A');
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
c++, reinventing-the-wheel, c++20, optional BOOST_CHECK(o4==o5); // Move-constructed from std::string using deduction guide to pick the type Optional o6(std::string{"deduction very long type"}); } BOOST_AUTO_TEST_CASE(access_operator_test) { using namespace std::string_literals; Optional<int> opt1 = 1; BOOST_CHECK_EQUAL(*opt1, 1); *opt1 = 2; BOOST_CHECK_EQUAL(*opt1, 2); Optional<std::string> opt2 = "abc"s; BOOST_CHECK_EQUAL(*opt2, "abc"s); BOOST_CHECK_EQUAL(opt2->size(), 3); Optional<std::string> taken = std::move(opt2); BOOST_CHECK_EQUAL(*taken, "abc"s); BOOST_CHECK_EQUAL(taken->size(), 3); BOOST_CHECK(!opt2.has_value()); } BOOST_AUTO_TEST_CASE(value_check_test) { Optional<int> opt; BOOST_CHECK(!opt.has_value()); opt = 43; BOOST_CHECK(opt.has_value()); if (opt) { BOOST_CHECK(true); } else { BOOST_CHECK(false); } opt.reset(); BOOST_CHECK(!opt.has_value()); } BOOST_AUTO_TEST_CASE(get_value_test) { Optional<int> opt = {}; BOOST_CHECK_THROW(opt.value(), BadOptionalAccess); BOOST_CHECK_THROW(opt.value() = 42, BadOptionalAccess); opt = 43; BOOST_CHECK_EQUAL(*opt, 43); BOOST_CHECK_EQUAL(opt.value(), 43); opt.value() = 44; BOOST_CHECK_EQUAL(*opt, 44); BOOST_CHECK_EQUAL(opt.value(), 44); } BOOST_AUTO_TEST_CASE(ValueOrTest) { // Test with existing value Optional<int> opt1(5); BOOST_CHECK_EQUAL(opt1.value_or(10), 5); // Test without an existing value Optional<int> opt2; // Empty optional BOOST_CHECK_EQUAL(opt2.value_or(10), 10); // Test with a different type Optional<double> opt3; // Empty optional BOOST_CHECK_CLOSE(opt3.value_or(10), 10.0, 0.0001); // BOOST_CHECK_CLOSE for floating point comparison // Test with rvalue when Optional has a value Optional<std::string> opt4("Hello"); BOOST_CHECK_EQUAL(opt4.value_or(std::string("World")), "Hello");
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
c++, reinventing-the-wheel, c++20, optional // Test with rvalue when Optional does not have a value Optional<std::string> opt5; // Empty optional BOOST_CHECK_EQUAL(opt5.value_or(std::string("World")), "World"); } BOOST_AUTO_TEST_CASE(swap_test) { Optional<std::string> opt1("Lorem ipsum dolor sit amet, consectetur tincidunt."); Optional<std::string> opt2("Some other lorem ipsum"); opt1.swap(opt2); BOOST_CHECK_EQUAL(*opt2, "Lorem ipsum dolor sit amet, consectetur tincidunt."); BOOST_CHECK_EQUAL(*opt1, "Some other lorem ipsum"); opt1.reset(); opt1.swap(opt2); BOOST_CHECK_EQUAL(*opt1, "Lorem ipsum dolor sit amet, consectetur tincidunt."); BOOST_CHECK(!opt2.has_value()); } BOOST_AUTO_TEST_CASE(comparison_test) { Optional<int> o1, o2; BOOST_CHECK(o1 == o2); o2.emplace(10); BOOST_CHECK(o1 < o2); BOOST_CHECK(o2 > o1); BOOST_CHECK(o2 != o1); o1.emplace(10); BOOST_CHECK(o1 == o2); BOOST_CHECK(o1 <= o2); BOOST_CHECK(o1 >= o2); } ``` Answer: Missing #includes You are missing #include <cstring> for std::memset(), and #include <new> for the placement new operator. The converting constructors are a core feature You have a non-converting constructor, but that does not even exist in std::optional. I would say that this is a core feature. Without it, you will get apparently inconsistent and surprising behavior. Consider: Optional<int> foo = 3.1415; // works Optional<float> bar = 42; // works Optional<std::string> baz = "Hello, world!"; // fails to compile The first two statements will happily cause conversions to happen. Fixing this so the third statement also compiles is trivial: Optional(const auto& value) : m_has_value{true} { new (m_data) T(value); }
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
c++, reinventing-the-wheel, c++20, optional I am very surprised by the choice of "basic features"; you have implemented operator<=>(), but I have never seen any code using the relational operators on std::optionals. Unnecessary zeroing of memory in the default constructor The default constructor does not need to zero m_data[], it's just going to cost you performance. The move constructor should not unset other.m_has_value In the move constructor, you set other.m_has_value to false, but you don't call the destructor of the other's value. And since the destructor of other will then not destruct its m_has_value, you will have created an object which will never be destructed propery. You must leave other in a state such that everything will eventually be correctly destructed. However, as Igor G mentioned, std::optional's specification says that after a move construction, other.has_value() should not return a different value than before the move construction. So the best thing to do is to just not set other.m_has_value = false at all. Incorrect behavior of swap() Related to the above: you have a similar problem in swap(), in case you swap an optional which has a value with one which hasn't. Here you have to explicitly call reset() on the side which will no longer have a value after the swap. About swapping // Do I need to do this? My first instinct was to do // an ordinary swap of the m_data's, but it seemed wrong // to do in case the types weren't trivially copyable/movable. // Maybe I should special case in those situations? You did the right thing in the code. You can't just swap the m_datas, that would just swap bytes without checking if that is legal, and would also bypass any specializations of std::swap for T. And in case T is trivially copyable/movable, then std::swap<T> would do exactly the same as std::swap<decltype<m_data>>, so there is no need to make this a special case.
{ "domain": "codereview.stackexchange", "id": 45091, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, reinventing-the-wheel, c++20, optional", "url": null }
java, mysql, rest, spring Title: blog RESTFUL api with posts and comments Question: I built RESTFUL api for a blog using java and spring boot(without a frontend). What it does the code manages all the http methods on a post inside the blog and comments on that post. the post consists of an id, name of the creator, title, body, amount of likes and dislikes, the comments are very similar they consist of an id, id of the post it was left on, username of the comment poster, its body, likes and dislikes. I have a mysql database for the posts and comments which columns are the same as the model. for the posts and comments there is a controller that manages all the HTTP methods with a repository object that extends CrudRepository. this is basically it I have a .http file to run the HTTP methods but it can be achieved through other means and services. Post and Comment Model package dev.ellie.blogcontentmanagmentsystem.models; import org.springframework.data.annotation.Id; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; public record Post( @Id Integer id, @NotBlank(message = "name should not be blank") String creatorName, @NotBlank(message = "post name should not be blank") String postName, @NotBlank(message = "content should not be blank") @Size(min=20,max=1000, message = "content should be between 20 to 1000 characters long") String content, int likes, int dislikes ) { } package dev.ellie.blogcontentmanagmentsystem.models; import org.springframework.data.annotation.Id; import org.springframework.data.relational.core.mapping.Column; import org.springframework.data.relational.core.mapping.Table; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size;
{ "domain": "codereview.stackexchange", "id": 45092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mysql, rest, spring", "url": null }
java, mysql, rest, spring import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; @Table(name="comment", schema = "blog-content-manager") public record Comment( @Id @Column("id") int id, @Column("postId") int postId, @NotBlank(message = "username must not be blank") @Column("commentUsername") String commentUsername, @Column("content") @NotBlank(message = "content must not be blank") @Size(min = 10, max = 200, message = "content must contain between 10 and 200 characters") String content, @Column("likes") int likes, @Column("dislikes") int dislikes ) { } Post and Comment Controllers package dev.ellie.blogcontentmanagmentsystem.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import dev.ellie.blogcontentmanagmentsystem.models.Post; import dev.ellie.blogcontentmanagmentsystem.repository.AccessingPostDataMySql; @RestController @RequestMapping("/api/posts") public class PostController { //private final PostRepository repository; private final AccessingPostDataMySql repository; @Autowired public PostController(AccessingPostDataMySql repository) { this.repository = repository; } @GetMapping public List<Post> findAll() { return (List<Post>) repository.findAll(); } @GetMapping("/{id}") public Iterable<Post> findById(@PathVariable Iterable<Integer> id) { return repository.findAllById(id); }
{ "domain": "codereview.stackexchange", "id": 45092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mysql, rest, spring", "url": null }
java, mysql, rest, spring @PostMapping public void insertPost(@RequestBody Post post) { System.out.println(post.postName()); repository.save(post); } @PutMapping("{id}/likes") public int addLike(@PathVariable Integer id) throws Exception { repository.addLike(id); return 1; } @PutMapping("{id}/dislikes") public int addDislike(@PathVariable Integer id) throws Exception { repository.addDislike(id); return 1; } } package dev.ellie.blogcontentmanagmentsystem.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import dev.ellie.blogcontentmanagmentsystem.models.Comment; import dev.ellie.blogcontentmanagmentsystem.repository.AccessingCommentDataMySql; @RestController @RequestMapping("/api/comments") public class CommentController { private final AccessingCommentDataMySql repository; @Autowired public CommentController(AccessingCommentDataMySql repository) { this.repository = repository; } @GetMapping("{postId}") public List<Comment> findAllByPostId(@PathVariable int postId) { return (List<Comment>) repository.findAllByPostId(postId); } @GetMapping() public List<Comment> findAll() { return (List<Comment>) repository.findAll(); } @PutMapping("{postId}/{id}/likes") public int addLike(@PathVariable Integer postId,@PathVariable Integer id) { repository.addLike(id); return 1; } @PutMapping("{postId}/{id}/dislikes") public int addDislike(@PathVariable Integer postId,@PathVariable Integer id) { repository.addDislike(id); return 1; } }
{ "domain": "codereview.stackexchange", "id": 45092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mysql, rest, spring", "url": null }
java, mysql, rest, spring The Repository Interface for the Posts and Comments package dev.ellie.blogcontentmanagmentsystem.repository; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import dev.ellie.blogcontentmanagmentsystem.models.Post; public interface AccessingPostDataMySql extends CrudRepository<Post, Integer> { @Modifying @Query("UPDATE post p SET likes = likes + 1 WHERE p.id = :id") void addLike(@Param("id") Integer id); @Modifying @Query("UPDATE post p SET dislikes = dislikes + 1 WHERE p.id = :id") void addDislike(@Param("id") Integer id); } package dev.ellie.blogcontentmanagmentsystem.repository; import org.springframework.data.jdbc.repository.query.Modifying; import org.springframework.data.jdbc.repository.query.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import dev.ellie.blogcontentmanagmentsystem.models.Comment; public interface AccessingCommentDataMySql extends CrudRepository<Comment, Integer> { @Query("SELECT * FROM comment c WHERE c.postId = :postId") Iterable<Comment> findAllByPostId(@Param("postId") int postId); @Modifying @Query("UPDATE comment c SET likes = likes + 1 WHERE c.id = :id") void addLike(@Param("id") Integer id); @Modifying @Query("UPDATE comment c SET dislikes = dislikes + 1 WHERE c.id = :id") void addDislike(@Param("id") Integer id); } MySQL Schema CREATE TABLE IF NOT EXISTS post ( id INT PRIMARY KEY, creator_name VARCHAR(255), post_name VARCHAR(255), content VARCHAR(1000), likes INT, dislikes INT ); CREATE TABLE IF NOT EXISTS comment ( id INT PRIMARY KEY, postId INT, commentUsername VARCHAR(255), content VARCHAR(200), likes INT, dislikes INT );
{ "domain": "codereview.stackexchange", "id": 45092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mysql, rest, spring", "url": null }
java, mysql, rest, spring I would like some ideas on how to improve my code and what to add to it, thanks. Answer: relation between post and comment in my opinion the relation between comments post is a composition and therefor it should belong to the post. @RestController @RequestMapping("/api/posts/{postId}/comments") public class CommentController { ... @GetMapping public List<Comment> findAllByPostId(@PathVariable int postId) { return (List<Comment>) repository.findAllByPostId(postId); } ... } path variables can be set at class level, there is an stackoverflow article describing how this is what the API would look like after: GET /api/posts/{postId}/comments - get all GET /api/posts/{postId}/comments/{commentId} PUT /api/posts/{postId}/comments/{commentId}/likes PUT /api/posts/{postId}/comments/{commentId}/dislikes missing POST for comments you cannot create commonets with your API, there is no POST to create new ones (as well as there is no PUT nor DELETE). dangerous API while it is described in any tutorial to provide a getAll() method, it is dangerous in real applications. When data reaches a certain size, the amount of results will overburden the system. BUT: it is quite common to use Pagination for that use case. weird return values why do you return the magic number 1 in your like/dislike methods? you can use void methods. using entities as dtos there is a nice article from Martin Fowler addressing this issue, you should not send db-entities as dtos. using a logger just give it a try, you already try to log something... so do it now in a proper way, dont be afraid :-) @PostMapping public void insertPost(@RequestBody Post post) { //System.out.println(post.postName()); //use a logger instead repository.save(post); } summary your code is very readable and very good to understand! i appreciate what you have achieved! Especially i like how you do dependency injection in the PROPER way! i do not see this very often, nice.
{ "domain": "codereview.stackexchange", "id": 45092, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mysql, rest, spring", "url": null }
java, mathematics, composition Title: Mapping composition in Java - v2 Question: This post is the continuation of Mapping composition in Java. This time, I: Disallowed the null values as the range value. Simplified the toString method via using the streams. Code com.github.coderodde.mapping.Mapping.java: package com.github.coderodde.mapping; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; /** * This class implements a mapping from a domain set to a range set. * * @param <D> the domain element type. * @param <R> the range element type. * * @author Rodion "rodde" Efremov * @version 1.61 (Sep 14, 2023) * @since 1.6 (Sep 3, 2023) */ public final class Mapping<D, R> {
{ "domain": "codereview.stackexchange", "id": 45093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mathematics, composition", "url": null }
java, mathematics, composition final Map<D, R> data = new HashMap<>(); public void map(D domainValue, R rangeValue) { checkDomainValueNotYetMapped(domainValue); Objects.requireNonNull(rangeValue, "The range value is not allowed to be nul.."); data.put(domainValue, rangeValue); } public boolean isMapped(D domainValue) { return data.containsKey( Objects.requireNonNull( domainValue, "The input domain value is null.")); } public R map(D domainValue) { checkDomainValueIsMapped(domainValue); return data.get(domainValue); } @Override public String toString() { return data.entrySet() .stream() .map(Mapping::convertMapEntryToString) .collect(Collectors.joining(", ", "[", "]")); } private static <D, R> String convertMapEntryToString(Map.Entry<D, R> entry) { return new StringBuilder() .append("(") .append(entry.getKey()) .append(" -> ") .append(entry.getValue()) .append(")").toString(); } private void checkDomainValueNotYetMapped(D domainValue) { if (data.containsKey( Objects.requireNonNull(domainValue, "Domain value is null."))) { throw new DuplicateDomainValueException( "Trying to map a domain value [" + domainValue + "] twice."); } } private void checkDomainValueIsMapped(D domainValue) { if (!data.containsKey(domainValue)) { throw new DomainValueIsNotMappedException( "Domain value [" + domainValue + "] is not mapped."); } } } Critique request As always, please tell me whatever comes to mind.
{ "domain": "codereview.stackexchange", "id": 45093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mathematics, composition", "url": null }
java, mathematics, composition Critique request As always, please tell me whatever comes to mind. Answer: Your Mapping class seems unnecessary, as your compose function shown in the previous post could just use Map types, which are already defined in a standard way within Java. all you're really doing is wrapping the methods of the inner data instance variable which is a map.
{ "domain": "codereview.stackexchange", "id": 45093, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, mathematics, composition", "url": null }
c++, callback Title: C++ Structural Requests System with Payload Management Question: First things first, I'd thank Mr. G. Sliepen and Mr. Davislor regarding their help in the previous questions (C++ System data transfer design) (C++ System data transfer design - Following 1), given the resultant code can be found here*. * The code includes some added functionalities beyond the point :) Now I'm taking the review request one step further, as I've mentioned the "simplified SystemInterface" within the last question, I'm here to focus on it with any potential enhancements and optimizations. General notes: The System Data transfer is over-simplified within this code. An introduced "Guarders" to guard against inaccepted payloads and allowed for correction in some cases. A partial of SystemInterface is herein provided. Comes with a "simplified ServiceManager", which manages Services (or Entities), giving each one a unique number which is utilized to identify it across other entities (as Logger/SystemInterface/..). SystemInterface is provided here as one instance lies in the global scope, in my code it's a composed object within each entity, which receives a pid at construction. The SystemInterface uses a kind of structural recursion to find the intended request. Generally _execReq is called when a data is received by any communication mean (as MQTT/HTTP/Serial/...), and it's callable from other entities ofcourse. One of my concerns is the runtime of _execReq call, and whether it's already optimized or there's a room for optimizing. #include <algorithm> #include <cassert> #include <concepts> #include <cstdint> #include <functional> #include <iostream> #include <iterator> #include <ranges> #include <span> #include <string> #include <string_view> #include <unordered_map> #include <utility> #include <variant> #include <vector> // // Tools // #define CHOP_FRONT(vs) (std::vector<std::string>(++vs.begin(),vs.end()))
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback // // Tools // #define CHOP_FRONT(vs) (std::vector<std::string>(++vs.begin(),vs.end())) std::string join(const std::vector<std::string>& vs,const char* delim) { std::string rv=""; if(vs.size()){ std::string sd(delim); for(auto const& v:vs) rv+=v+sd; for(int i=0;i<sd.size();i++) rv.pop_back(); } return rv; } std::vector<std::string> split(const std::string& s, const char* delimiter){ std::vector<std::string> vt; std::string delim(delimiter); auto len=delim.size(); auto start = 0U; auto end = s.find(delim); while (end != std::string::npos){ vt.push_back(s.substr(start, end - start)); start = end + len; end = s.find(delim, start); } std::string tec=s.substr(start, end); if(tec.size()) vt.push_back(tec); return vt; } enum class RequestErrors : uint8_t { OK, NOT_FOUND, NOT_STRING, TOO_MANY_INPUTS, TOO_FEW_INPUTS, NOT_NUMERIC, }; // // Data types // using BasicReferenceData = std::variant<std::string_view, std::span<std::uint8_t>>; using BasicConcreteData = std::variant<std::string, std::vector<uint8_t>>; std::span<std::uint8_t> t; using ConcreteDataContainer = std::vector<BasicConcreteData>; using ReferenceDataContainer = std::vector<BasicReferenceData>; /* Over simplified ReferenceData and ConcreteData, for the full implemented: https://godbolt.org/z/EofKMzGE9 */ using ReferenceData = ReferenceDataContainer; using ConcreteData = ConcreteDataContainer; using ReturnData = ConcreteData; using RequestReturn = std::pair<RequestErrors, ReturnData>; using CallbackSignature = std::function<RequestReturn(const std::string &context, const ReferenceData &)>; /// /// Guarders /// using PayloadGuardFN = std::function<RequestReturn(const ReferenceData&)>; /* Guarders Helper functions */
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback /* Guarders Helper functions */ bool binaryData(const BasicReferenceData& data) { return std::holds_alternative<std::span<std::uint8_t>>(data); } bool printable(const BasicReferenceData& in) { auto span = std::get_if<std::span<std::uint8_t>>(&in); return !span || std::all_of(span->begin(), span->end()-1, isprint) && (isprint(span->back()) || span->back() == '\0'); // Allows the presence of zero terminator // !span means it's a string_view } void to_string(BasicReferenceData& data) { // Might remove the check. if (std::holds_alternative<std::span<std::uint8_t>>(data)) { auto span = std::get<std::span<std::uint8_t>>(data); data = BasicReferenceData{std::string_view(reinterpret_cast<char*>(span.data()), span.size())}; } } void to_string(ReferenceDataContainer::iterator it) { auto span = std::get<std::span<std::uint8_t>>(*it); *it = BasicReferenceData{std::string_view(reinterpret_cast<char*>(span.data()), span.size())}; } bool is_number(std::string_view s) { bool numeric = false; if (s.size()) { bool first_char_valid = numeric = (isdigit(s.front()) || (s.front() == '-' && s.size() > 1)); if (first_char_valid) { bool found_dot = false; for (auto it = s.begin(); it != s.end(); it++) { if (isdigit(*it)) continue; else if (*it=='.' && !found_dot) { found_dot = true; continue; } numeric = false; break; } } } return numeric; } class Guarder { public: virtual RequestReturn operator()(const ReferenceData& in) = 0; };
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback class Guarder { public: virtual RequestReturn operator()(const ReferenceData& in) = 0; }; /* Guarder classes */ class CountGuarder : public Guarder { // Or a template ?? size_t count; public: RequestReturn operator()(const ReferenceData& in) override{ return std::make_pair((in.size() > count ? RequestErrors::TOO_MANY_INPUTS : in.size() < count ? RequestErrors::TOO_FEW_INPUTS : RequestErrors::OK), ReturnData{});} CountGuarder(size_t count) : count(count) {} }; class StringsGuarder : public Guarder { public: RequestReturn operator()(const ReferenceData& in) override { std::cout << "String Guarder\t"; auto mut_in = const_cast<ReferenceData*>(&in); // auto view = in | std::views::filter(binaryData); if (std::all_of(in.begin(), in.end(), printable)) { for (auto it = mut_in->begin(); it != mut_in->end(); it++) { if (binaryData(*it)) { to_string(it); } } // std::ranges::for_each(mut_in | std::views::filter(binaryData), to_string); std::cout << "OK\n"; return std::make_pair(RequestErrors::OK, ConcreteData{}); } else { std::cout << "NOT_STRING\n"; return std::make_pair(RequestErrors::NOT_STRING, ConcreteData{}); } } };
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback // Should follow a StringGuarder within the pipeline and remove the StringGuarder inside? class NumericGuarder : public Guarder { public: RequestReturn operator()(const ReferenceData& in) override { std::cout << "Numeric Guarder\t"; StringsGuarder stringify; auto result = stringify(in); if (result.first != RequestErrors::OK) { return result; } for (auto& i : in) { auto* sv = std::get_if<std::string_view>(&i); if (!sv || !is_number(*sv)){ std::cout << "Not Numeric!\n"; return std::make_pair(RequestErrors::NOT_NUMERIC, ConcreteDataContainer{std::string(*sv)}); } } std::cout << "OK\n"; return std::make_pair(RequestErrors::OK, ConcreteData{}); } }; // Can build custom Guarders. RequestReturn toStringCorrector(const ReferenceData& pload) { StringsGuarder stringify; return stringify(pload); } // // SystemInterface // struct request { std::uint32_t owner; std::uint32_t levID; CallbackSignature cbf; std::vector<Guarder*> guarders; }; using REQMAP = std::unordered_multimap<std::string,request>; using REQMAP_I = REQMAP::iterator; enum REQ_ID { REQ_ROOT, REQ_LOGGER, // A predefined ID for some instances, as the Logger. REQ_MAX }; class SystemInterface { REQMAP requestsMap;
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback class SystemInterface { REQMAP requestsMap; REQMAP_I __exactMatch(const std::string& cmd,uint32_t owner){ auto any=requestsMap.equal_range(cmd); for(auto i=any.first;i!=any.second;i++) if(i->second.owner==owner) return i; return requestsMap.end(); } void __flatten(std::function<void(std::string)> fn){ // For generating "help" list REQMAP_I ptr; for(ptr=requestsMap.begin();ptr!=requestsMap.end(); ptr++){ if(!(ptr->second.owner)){ if(ptr->second.levID) _flattenCmds(fn,ptr->first,ptr->first,ptr->second.levID); else fn(ptr->first); } } }
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback RequestReturn _dispatch(std::vector<std::string> vs, ReferenceDataContainer ploads, uint32_t owner=0){ std::cout << "_dispatch: " << join(vs,"/") << "\n"; if(vs.size()){ REQMAP_I i; std::string cmd=vs[0]; i=__exactMatch(cmd,owner); if(i!=requestsMap.end()){ if(i->second.cbf) { return [=]()->RequestReturn{ for(auto& guard : i->second.guarders) { auto ret = (*guard)(ploads); if (ret.first!=RequestErrors::OK) { return ret; } } return i->second.cbf(join(CHOP_FRONT(vs),"/"), ploads); }(); } else return _dispatch(CHOP_FRONT(vs), ploads, i->second.levID); } else return std::make_pair(RequestErrors::NOT_FOUND, ConcreteDataContainer{}); } else return std::make_pair(RequestErrors::NOT_FOUND, ConcreteDataContainer{}); } public: void addRequest(uint32_t owner, uint32_t levId, const std::string &name, CallbackSignature cbf, std::initializer_list<Guarder*> guarders={}) { if (__exactMatch(name, owner) == requestsMap.end()){ // std::cout << "Inserting " << name << "\n"; requestsMap.insert(std::make_pair(name,request{owner,levId, cbf, guarders}));} else std::cout << "Already assigned path!\n"; }
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }
c++, callback RequestReturn _execReq(std::string topic, ReferenceDataContainer ploads){ std::vector<std::string> cmd=split(topic,"/"); return _dispatch(cmd, ploads); // optimise? } void _flattenCmds(std::function<void(std::string)> fn,std::string cmd,std::string prefix,uint32_t lev){ REQMAP_I i=requestsMap.find(cmd); for(i=requestsMap.begin();i!=requestsMap.end();i++){ if(i->second.owner==lev){ std::string trim = prefix+"/"+i->first; if(i->second.levID) _flattenCmds(fn,i->first,trim,i->second.levID); else fn(trim); } } } void help() { std::vector<std::string> unsorted={}; __flatten([&unsorted](std::string s){ unsorted.push_back(s); }); sort(unsorted.begin(),unsorted.end()); std::cout << "HELP: \n"; for (auto& path : unsorted) { std::cout << "\t" << path << "\n"; } } }; SystemInterface interface; // // Guarder objects // CountGuarder c1Guard(1); NumericGuarder nGuard; StringsGuarder sGuard; // // ServiceManager // class ServiceManager { protected: std::uint32_t pid; std::string name; static std::uint32_t services; ServiceManager(std::string name) : name(name), pid(++services+REQ_MAX) { // std::cout << "name=" << name << " pid=" << pid << "\n"; } }; std::uint32_t ServiceManager::services=0; class Service1 : public ServiceManager { public: Service1() : ServiceManager("service1") { // Installs a level of "svc1" interface.addRequest(REQ_ROOT, pid, "svc1", nullptr, {}); // LevelID // Can add sub level ID on top of (pid) further ...
{ "domain": "codereview.stackexchange", "id": 45094, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, callback", "url": null }