My codes are supper long


#1

I am half way through basic algorithm section and when i code i solve the problem, but am frustrated when i see other peoples solution because they are simple and short where else mine are long and complicated and it feels like a hack. I don’t know if am doing it right. Please advice me on how to go about it.


#2

Most people probably have been in the same position as you are now at some point, and you really shouldn’t feel discouraged about it because it’s just part of the learning process, and not least because you seem to have just started. My approach to it is:

  1. Read any documentation carefully and attempt a challenge only with what I know and what I have been taught first
  2. Don’t get distracted by writing short, fancy-looking code—aim to finish the challenge with logically-clear, well-formatted and well-commented code first and consolidate what you know/have just learnt
  3. Refactor your code where possible and submit your answer
  4. Study other people’s solution and learn from them by reading documentation and asking questions
  5. Don’t hesitate to get ask others to review your code (provided that your code is readable) and see what you can do to improve

I think writing short code is fun sometimes if you treat that as a brain-stretching exercise (like on codewars.com), but the goal shouldn’t always be short, as short doesn’t necessarily mean clean, maintainable, and/or more performant.

Good luck! :slight_smile:


#3

It’s great that you are able to solve the problem in the first place. What you can do is to also learn how other people solved the problem. From there on, try to improve your code for the same solution. That’s what I did mainly. Sometimes the same function of code can be written way shorter with the use of other available methods. But a shorter code doesn’t mean that’s far for efficient than the longer version. That’s what I did.