DEV Community

Akuma Isaac Akuma
Akuma Isaac Akuma

Posted on

Once you start writing a lot of code you're surely doing it wrong

On several occasions, I've had a moment when very few lines of code solved an issue I was trying to solve earlier with very complicated or confusing and huge lines of codes which makes me come to the conclusion to this saying

Once you start writing a lot of code you're surely doing it wrong

Here's a recent example of me trying to convert a text to an Array of Strings based on the occurrence of a valid HTTP URL found in the text.
I was trying to implement a feature Twitter has Alt Text , that's shortening and highlighting URLs found in a post which is very useful and could also help if you want to implement a secure redirect from your app.

My First attempt:

// Copied from https://stackoverflow.com/a/63022807/10365156
const linkReg = /(https?\:\/\/)?([\w\d-]+\.)*[\w-]+[\.\:]\w+([\/\?\=\&\#]?[\w-]+)*\/?/gm

const text =
  "Look at what he https://twitter.com/signalapp/status/1346258308496150528 vool     https://twitter.com/asemota/status/1346396079466622980"

 const links = post.title.match(linkReg) || []
  const texts = links.reduce((all, cur) => {
    if (all.length) {
      return all.map((v) => {
        let strs = []
        const all = v.split(cur)
        for (let [index, value] of all.entries()) {
          if (all.length - 1 === index) {
            strs.push(value)
          } else {
            strs.push(value, cur)
          }
        }
        return all
      }).flat()
    }
    return post
  }, [])
Enter fullscreen mode Exit fullscreen mode

At this point, I was already confused and really tired as well, so I had to leave it for a while to clear my head.

And here is my second attempt:

const ph = "[z&&&&z]" // placeholder
let t = text.replace(linkReg, (v) => `${ph}${v}${ph}`)

console.log(t.split(ph))
// [
//   "Look at what he ",
//   "https://twitter.com/signalapp/status/1346258308496150528",
//   " vool     ",
//   "https://twitter.com/asemota/status/1346396079466622980",
//   "",
// ]
Enter fullscreen mode Exit fullscreen mode

At this point, I've already achieved what I needed but going through MDN Specifying a string as a parameter reminded me about $& pattern so I refactored the code once more to get this

Third attempt:

const tokens = text.replace(linkReg, `${ph}$&${ph}`).split(ph)
console.log(tokens)
// [
//   "Look at what he ",
//   "https://twitter.com/signalapp/status/1346258308496150528",
//   " vool     ",
//   "https://twitter.com/asemota/status/1346396079466622980",
//   "",
// ]
Enter fullscreen mode Exit fullscreen mode

This still gives me the same result as the second attempt but with lesser code, much readable and simpler overall.

Top comments (18)

Collapse
 
cyrilcabo profile image
Cyril Cabo

Fair point, but I guess this may mislead beginners into thinking that writing a lot of code is wrong or bad practice. Surely, there are cases (like this one), where you can leverage the language's perks, and be able to solve it with a few lines of code, but it is not always the case. I'm not trying to criticize you though, I just want to give a fair warning to beginners reading this. It was a good read, nonetheless. Good work!

Collapse
 
akumzy profile image
Akuma Isaac Akuma

You're not wrong, This is more like encouragement to maybe take a few step back whenever things become complicated or confusing and challenge yourself to seek a simpler way.

Collapse
 
phantas0s profile image
Matthieu Cneude

This is highly depending on the context. Sometimes you'll need "a lot" of code, sometimes you won't. No silver bullet here.

It's hard to get it your code right the first time, so here's what we should really do:

  1. Writing some code.
  2. Refactoring when you have more knowledge about the business domain / your functionality / other.

When you write something a bit consequent, you often write a draft first. It's the same for programming.

Collapse
 
akumzy profile image
Akuma Isaac Akuma

I agree

Collapse
 
ksaaskil profile image
Kimmo Sรครคskilahti

Good job showing how to write more readable and robust code by using the right tools for the job ๐Ÿ‘ The first version could also be made more readable by defining helper functions to remove all that nesting?

Collapse
 
akumzy profile image
Akuma Isaac Akuma

Yeah, but that's will come after the implementation is being figured out completely

Collapse
 
ksaaskil profile image
Kimmo Sรครคskilahti

I respectfully disagree, I think it's better to write short functions with single responsibilities from the beginning. That makes refactoring a lot simpler and easier to see if the composed function is doing what it should. But that's just my experience ๐Ÿ™‚

Thread Thread
 
akumzy profile image
Akuma Isaac Akuma

That's okay

Collapse
 
epsi profile image
E.R. Nurwijayadi

This is why we have Haskell.

Collapse
 
akumzy profile image
Akuma Isaac Akuma

Hahaha! I don't know Haskell and I'm sure it'll be overkill for web

Collapse
 
epsi profile image
E.R. Nurwijayadi

For web, there is purescript that very similar with haskell.

Something like this one
๐Ÿ•ท dev.to/epsi/purescript-playing-wit...

Purescript: Playing with Record

Thread Thread
 
akumzy profile image
Akuma Isaac Akuma

That's interesting, thanks for sharing

Collapse
 
sirseanofloxley profile image
Sean Allin Newell

In this case, less code is indeed simpler; sometimes, more code is simpler. Looking at you bit twiddling over optimized one liners...

Collapse
 
burdier profile image
Burdier

It depends on what you are doing at the moment.

Collapse
 
akumzy profile image
Akuma Isaac Akuma

๐Ÿค”๏ธ I never thought of it as clickbait

Collapse
 
xseman profile image
Filip

I personally prefer more code, if it's more explicit and self explanatory with no needed for comments or documentation.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.