4 ms·
If I may pick on one piece of advice here: intermediate variables. I think both the bad and good examples are both equally unreadable and feel the "good" versio
by adregan 4y ago
If I may pick on one piece of advice here: intermediate variables. I think both the bad and good examples are both equally unreadable and feel the "good" version would introduce more confusion into a code base than the "bad" example.
For example, if I came across the example in code, I would begin to wonder why the `deltaX` variable exists at all if its only purpose is to be renamed `translateX` and spend some time tracing the code to see where the variable falls out of scope and to see if it's important. Then I might wonder whether it used for something else at some other point in time and trace the history of these lines (somewhat akin to nerd sniping).
Now I'm focusing on the variable as if it's important when really the important bit is the relationship of the current to the initial. The code is obscuring the fact that "delta" is `current - initial`. Look how many times the pattern is repeated! Perhaps we need an abstraction that can produce the delta for us. However, the data structure makes that a little bit tricky as scrollTop is held in an ad hoc manner, so maybe we should update the data structure so that we can eventually have an api like:
type ScreenPoint = { x: number; y: number; scrollTop: number }
type toDelta = (current: ScreenPoint, initial: ScreenPoint) => ScreenPoint
// example implementation of toDelta using ramda for brevity
const toDelta = R.mergeWith<ScreenPoint, ScreenPoint>(R.subtract)
const delta = toDelta(current, initial)
shadow.style.transform = `translate(${delta.x}px, ${delta.y + delta.scrollTop}px)`
Intermediate variables can be tricky because you can't always trust that the name matches what's actually going on inside, so you have to read everything anyhow.
- svnpenn 4y ago> using ramda for brevity please don't do that. Unless the article also uses Ramda (it doesn't) its not really appropriate for you to do so. If you want to use Ramda in your own, personal code, go ahead. But if you're posting a public example for other people to look at, including Ramda only makes sense if you're on a Ramda forum. The whole point of this article is clarity in programming, you've reduced that with you decision to include some obscure package.
- adregan 4y agoIt was only intended to be illustrative of thinking about the operation as merging two identical data structures in a manner that produces the result. You could accomplish the it using any technique your codebase prefers be it FP, OOP, &c. (some languages might even handle such an operation natively). In this case, I felt that it was sufficiently close to pseudo code “merge these objects by subtracting identical keys left to right,” but I understand your objection to obscurity. I actually feel that the implementation in this example is fairly unimportant.