trainings/CreatingReliableSoftwareCpp/Presentation/good_practise_dry.md

1.5 KiB

DRY


Don't Repeat Yourself

  • If you have two identical functionality, like searching for some resource, just make a separate function and always call it
  • Create some utility files, which will contain functions reused in your project
  • It could contain functions for:
    • Filtering
    • Searching
    • Removing
    • Operate with string etc...
  • If you have some value/ string which is used in few places, create one constexpr variable for it and always refer to this variable instead magic value/ string

class Foo {
    constexpr static const char* DATABASE_NAME = "superDb";
    constexpr static size_t CONNECTION_TIMEOUT_SECONDS = 30;

public:
    // Don't hardcode value here, instead of create a variable which store this info
    void connect(const std::string& dbName = DATABASE_NAME) {
        db.createConnection(dbName, CONNECTION_TIMEOUT_SECONDS);
    }

    bool connected() const { return db.connected(); }

    json sendRequest(const json& request) {
        // use already implemented functions
        if (!connected()) {
            connect();
        }

        return db.request(request);
    }
};