by faizshah · 3y ago · 0 comments
The problem is when your code does not have a single mental model that can be learned your team then you end up with lots of copy pasting with lots of different patterns and your codebase can rapidly become a pain to maintain.
I have been returning a lot to ”Design Patterns” lately and I think one of the under utilized patterns is the template method pattern. It can be used in places like this where the algorithm is almost the same except for one or two parts of the algorithm that could be extended.
/* IF YOU CHANGE THIS see if you also need to change bar() in otherfile.js
with comment code OSIJDF */
function foo() { ...
I try to put a comment like this in front of every instance, and smash the keyboard for a single random character sequence like `OSIJDF` above that I put in each instance and can do a quick find-all for, in case my original bar() got renamed or moved to a different file, or there's a third function I forgot to add in later but I copy-pasted the comment.However this is very much a personal practice for cross-referencing that I'm not sure would be received very well as a mandatory practice for code reviews etc.
It does make me very much wish for a best-practices way to essentially provide hyperlinks or cross-references between functions, to indicate that a code should always be interpreted in context of other bits of code that are not in a nearby obvious/contiguous spot. I've never seen anything like that though.
open class Importer {
fun import() {
// do common logic...
val parsed = parse() // call specialized behaviour
}
open fun parse() { ... }
}
Vs. class Importer(private val parser: Parser) {
fun import() {
// do common logic...
val parsed = parser.Parse() // call specialized behaviour
}
}
In my experience, using inheritance can quickly make things worse.
(Go seems to agree, there is no inheritance in Go, only composition.)I have seen code-bases where these patterns are applied excessively. Generic implementations often take longer to read and understand, and are frequently much more difficult to modify. Adding inheritance can add effort to simple things like code-reviews (the abstract base class is not in the change), and the code cannot be read without jumping between files.
My point is not that the template or strategy patterns are bad, but that there is a price to pay. Just use them judiciously.