DEV Community

How can I learn to write simpler code?

Valeria writes docs on December 22, 2023

I'm taking Harvard's CS50 Introduction to Python Programming course and I'm shocked by how ugly my code is. I'm a beginner and assume that everyo...
Collapse
 
ben profile image
Ben Halpern

One trick in my bag is the squint test.

Take a step back, squint your eyes. Now how do you feel about the code you're looking at?

It's hard to explain, but good code usually passes the squint test.

Collapse
 
valeriahhdez profile image
Valeria writes docs

I have to give it a try

Collapse
 
mistval profile image
Randall

I like to look at my code in different places for a similar reason. If I look at my code in VS Code and then I look at my code on GitHub, it can feel like looking at it from a fresh perspective. I find mistakes all the time by doing this. I read the code 5 times in my editor, push it up to GitHub, read it one time there, and find a bunch of mistakes I missed. Maybe switching themes in my editor would have the same effect.. I should try that.

Collapse
 
lnahrf profile image
Lev N.

I have to try this

Collapse
 
alaindet profile image
Alain D'Ettorre

This is a very long journey with no simple answers, it takes time and practice. "Conciseness" comes in layers, but I'd say concise code is code expressing what you want via the shortest readable way possible. Please note the readable part, which is the corner stone of good code.

Readable means many things to many people, but there are some objective rules

  • Possibly short
  • Unambiguous
  • As little abstraction as possible
  • Clear context via variables and functions names, not comments
  • If you're about to use an "else" or worse "elif", don't, use a function maybe
  • If you're about to indent some code, don't, unless you're forced to, as indented code means you're moving away from the happy path
  • Creating functions for each step of the algorhitm is good
  • Exiting functions as early as possible if anything bad occurs is good (early exiting)
  • Functions should have the smallest scope possible, hence have as few arguments and be as short as possible
  • Never go beyond 80 chars on a single line and don't you dare to go beyond 100 chars sparingly
Collapse
 
valeriahhdez profile image
Valeria writes docs

This list of rules is so helpful, thank you for sharing!

Collapse
 
lnahrf profile image
Lev N.

We all want visually pleasing code, but at the same time it’s important to understand that visually pleasing is not more efficient, and shorter code is not better code.

That being said, optimized and clean code is important. The best advice I got was to try and divide the larger task at hand to smaller, simpler tasks. Then create a short and precise function for each of those tasks. Rinse and repeat until you are satisfied with the result.

Along the way you will probably think that this function and that function should be one function, or vice-versa. That is natural, try and find the sweet spot between “too many functions” and “ugly blobs of unmaintainable code”.

Collapse
 
valeriahhdez profile image
Valeria writes docs

Totally agree with you. One of the reasons why I enjoy learning to code is because it teaches you to break up problems into smaller ones. And though I really like it, I've come to realize I'm not so good at it 😅

This is a humbling experience and I shall learn to be patient with myself and trust one day I'll be where I want to be.

Thank you for the advice

Collapse
 
lnahrf profile image
Lev N.

I would also like to add that coding is a very subjective experience. There is no "right way" to code, there are only agreed upon "wrong ways" to code. Every developer is unique, and has a unique style. Just keep coding until you find yours.

Collapse
 
ivanzanev profile image
Ivan Zanev

Hi,

I don't think there is a way to "speed up" the process. Leave Bard's code aside for now. Share your solution as an algorithm (a sequence of steps). Document your reasoning and share it as well.

Collapse
 
valeriahhdez profile image
Valeria writes docs

I'm not a developer, is there any community where I can post my code to ask for feedback?

Collapse
 
ivanzanev profile image
Ivan Zanev

I thought this community will suffice.

Collapse
 
prsaya profile image
Prasad Saya

First, you are conscious that you want to improve your coding and want to put effort into it - this is a good step towards becoming a better programmer.

Here is what I feel you can try about writing code (not just Python programming language).

The condition is: the string can't have numbers in the middle and the leading number can't be a zero.

condition_met = None
get all chars in a string as an array
if the leading (or first) char is a 0
    condition_met = False
else if any other chars are digits
    condition_met  = False
else
    condition_met = True
Enter fullscreen mode Exit fullscreen mode

This is generally referred as pseudo-code (or explaining the logic in more English like terms). Now, you write the code from here. Your code can be couple of lines more or less depending upon the constructs you prefer to use.

Note that good and efficient code can be written using the most basic constructs of a programming language.

Collapse
 
valeriahhdez profile image
Valeria writes docs

This is an excellent advice! Writing pseudo-code will help me clarify my thought process. Thanks

Collapse
 
praful profile image
Praful

Many programmers I worked with or managed didn't want to improve. It's great you're asking these questions.

Although the book has aged in some ways, my favourite book for writing code is Code Complete by Steve McConnell. I read the first edition many years ago and it was the first book I saw that looked at every aspect of coding: comments, indentation, readability, naming, etc. I was pleased to find someone else who was obsessive about the details of writing code.

Your question about simplicity is profound. I learnt to program 40 years ago and now do it for pleasure. Even now when I look at some old code, I can improve it. Simplicity is the result of deep knowledge and you never stop learning if you're passionate about something.

On a more practical front, do you tackle the Advent of Code - 25 puzzles in December, going back to 2015. You can do them any time but if you do them whilst it's happening, you can interact with the wonderful community on reddit (people still post at other times of the year). Every day people present their solutions (many programming languages are used) and you can compare your solution to theirs, allowing you to see different algorithms or the same algorithms written in a different way from yours.

Finally, I found it useful to learn about different programming approaches and how they solve problems: procedural, object-oriented, and functional.

Collapse
 
valeriahhdez profile image
Valeria writes docs

Didn't know about the advent of code. Sounds like fun and exactly what I need. I will look for the book you mention. I'm just a beginner but I really want to have a good understanding of all the details you mentioned. Thanks a lot for your advice 🙌

Collapse
 
vb64 profile image
Vitaly Bogomolov

The two most difficult problems in programming: naming and cache invalidation :)

All other you can learn in the courses.

In addition to the practical advice already given here, my two cents.

Function docstring should be one simple sentence.

If this is not the case, then it is worth thinking about how to transform/split function so that it complies with the "one simple sentence" rule.

Collapse
 
javier_jimenezmatilla profile image
Javier Jimenez Matilla

Trick for me: don’t worry, if I don’t know the language or the framework, I use iterations

Write code and test. When it works, iteration 1 . Review and ask your self: how would I do it better, could I ask to an expert? Search on google, ask ai, and compare your first solution with each improve iterations.

Collapse
 
valeriahhdez profile image
Valeria writes docs

I'm learning on my own, I don't have a team to share my code for review. I've been asking AI since the beginning but it's always nice to have the human perspective as well. Thank you for your advice 🙌

Collapse
 
sumitkumardev10 profile image
SumitKumarDev

Instead of looking at the whole code, try to look at smaller sections like an if condition and think "Hmmm... I think this can be made simpler."

Make sure you know what conditions you are checking, else you may get stuck with an overly complicated code.
Try to implement DSA(Data Structure And Algorithms).
Ask AI for the same and ask it to give a couple of assignments. Do the assignment and check it against the code of the AI. Only then shall improvement could be seen.
Finally, be humble and keep the attitude of the longingness to acquire more knowledge and ideas.

Collapse
 
valeriahhdez profile image
Valeria writes docs

Thank you for the advice. I really liked your suggestion of asking AI for assignments. I don't know what DSA is so I should look it up

Collapse
 
mcharytoniuk profile image
Mateusz Charytoniuk

You can check this article I wrote: dev.to/mcharytoniuk/common-misconc...

Collapse
 
morphzg profile image
MorphZG

Only 1 word fo you: Experience. You just need more experience. Write code and over time you will improve.

Collapse
 
valeriahhdez profile image
Valeria writes docs

You're right. I need to trust the process and be patient.

Collapse
 
hellishbro profile image
HellishBro

theres no exact way to speed up the learning curve, but having a good problem solving skill is key.

try to break down the problem into sub-tasks, and code them however you like. sure, go ahead, press that tab key 3.64E57 times, i dont care. after you are sure your code works, try to remove unnessessessecary logic and code; use or, and, and not statements in your if statements. try to use match case instead of if elif else if it exceeds like, 4 conditions.

learn how to use functions and classes properly instead of making a mumbo jumbo, as it allows for code organization

and lastly, comprehensions. try to use as few comprehensions as possible, but use some. dont make an incredibly long condition: i aint reading allat. if you must, break it into managable chunks and dont burden your future self

Collapse
 
valeriahhdez profile image
Valeria writes docs

Never thought of reading other's code. But you're right, it's important, especially because I'm learning on my own and have no colleagues to ask for comments. I made this post precisely because I needed the human perspective. And I'm so pleased with the answers I received from all of you!

I made a list of all the good tips I received to start practicing them.

Collapse
 
taijidude profile image
taijidude

My two cents in this:

  • You will get there. A lot of this is experience.
  • Don't try to create the perfect solution in the first Iteration. A colleague once said to me: "First make it work and than make it pretty"
  • In my humble opinion rather than aiming for concise code i would try to get the code as understandable, readable and as easy to debug as possible.
  • You could try to write unit tests for your code. When something is easy to test, chances are higher that the code fufills the criteria from my last point.