How to refactor Clojure source code, especially to rename the keywords of a map collection?

Viewed 224

When I develop Clojure project, sometimes, I encounter a situation: It is somewhat difficult to rename the keywords of a map collection.

For example, if I have a map collection that is shared by several namespaces. Then, those namespaces will depend on the keywords of this map collection because the functions defined in these namespaces use map destruction syntaxes. When I rename the keywords of this map collection, I will definitely need to exhaustively check those namespaces.

Is there any tools or effective methods to use in this kind of situation?

1 Answers

It would be a challenge when you had used an unqualified :x for forty distinct meanings and then decide to rename one of them. And the challenge would become a headache if you did not have (and did not want to make) test cases sufficient to detect the loss of an intended argument.

Next time, consider designating (unique) namespace-qualified keywords for uses that will be spread wide. Replacement is unambiguous and tools are more likely to automate it.

A few language features can help while you rework your code, depending on the scale of the scope within which you decide to rename stuff.

Preconditions give you a place to assert about a destructured argument (or merely log it, if you need to judge success case-by-case).

Pure functions allow you to clone a bunch of your code, rename stuff (or revise any logic) in the cloned version, and then run both versions in parallel and assert they came up with the same result. For example, clone function f as f-1 and f-2, rework f-2, and reprogram f so it calls both f-1 and f-2 and asserts the results are the same. When they agree, you can delete the original.

Tests are super easy with the built-in clojure.test (and there are more elaborate alternatives).

Related