DEV Community

Valeria writes docs
Valeria writes docs

Posted on

How can I learn to write simpler code?

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 everyone goes through this stage where your code is overcomplicated. But how can I speed up my learning curve and write cleaner, simpler code?

When solving coding problems, I always write my own code first and after I'm sure it does what it needs to do, I go to Bard and ask it to improve it. What I've learned from comparing my code to Bard's version is that my algorithms are too complicated.

With all the shame I have, I will present an example.

Ashamed dog

The following code is part of a function that takes a string entered by a user and checks if the string complies with five different conditions. For the sake of simplicity, I will present the code for only one of these conditions. The condition is: the string can't have numbers in the middle and the leading number can't be a zero.

This is the code I wrote to check this condition:

if any(char.isdigit() for char in input_str):  
        for i in range(len(input_str)):
            if input_str[i].isdigit():
                if input_str[i] == '0':
                    break
                else:
                    number_index= i
                    contains_number = input_str[number_index:]
                    if contains_number[0] != 0 and all(char.isdigit() for char in contains_number):
                        condition_met += 1
                        condition_list.append(6)
                break
    else:
        condition_met += 1
        condition_list.append(6)
Enter fullscreen mode Exit fullscreen mode

and this is Bard's version:

digits = "".join(char for char in input_str if char.isdigit())
    if not digits:  
        condition_met += 1
        condition_list.append(5)
    else:
        if digits[0] != '0' and digits == input_str[-len(digits):]:
            condition_met += 1
            condition_list.append(5)
Enter fullscreen mode Exit fullscreen mode

My code has 15 lines and Bard's code has 8. A lot more concise.

So my question for more experienced programmers is, how can I improve my solving-problem thinking?

I am enjoying a lot learning to code precisely because it teaches you to break down problems into small tasks but I'm shocked to realize that my solutions are complicated and that I can do better at making them simpler. How can I learn to create simpler code?

Top comments (28)

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...