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 Nahar

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
 
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
 
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
 
lnahrf profile image
Lev Nahar

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 Nahar

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
 
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
 
kwnaidoo profile image
Kevin Naidoo • Edited

Well done! the mere fact that you are interested in improving your code - is a great quality to have and this mindset will make you a better developer as you gain more experience.

Seems to me that BARD is not as accurate as you may think. I did a quick scan of this code and an "if" inside an "else" instead of "elif" seems odd. Secondarily, you just need to find the length of the string and divide it by 2 to get to the middle - then you don't need the for loop.

I would suggest the following:

  1. Study the "big o notation".

  2. Learn your data structures and algorithms. You don't have to understand and know all of these 100%, just have them in the back of your mind and keep refreshing your memory every so often. Eventually, as you gain experience - you will draw on these to help you write better code.

  3. Pseudocode a solution. A rough draft of your code before actually writing the actual solution.

  4. Read open-source code. You don't need to understand everything - just read and try to learn as much as you can. This builds a mental map, so when you solving a similar problem - you have a reference from some of the best developers around. Just be careful - not all open-source projects are well-written and well-structured. Stick to well-established libraries and frameworks. A good indicator is the number of stars a project has, how many contributors they have and who are the main contributors.

  5. Single responsibility and loose coupling. The above is a simple script, but on bigger projects - you want to ensure your code is separated into functions and classes that are as narrow-focused as possible. It's not always about less code, sometimes more code is better.

Good code is often highly readable, well-documented, very modular, well-tested, takes into account performance bottlenecks, and other business requirements (like hosting costs, time to ship, etc...), and finally actually solves the problem.

As a beginner - do not expect to be good at this just from the get-go, it takes time and years of experience. Don't worry if your code looks verbose and more complicated.

Focus rather on solving the problem. How do you do that?

1) Break down each task into steps, and write down each step.

2) Next write the Pseudocode of your solution. Since you using Python, it's so close to English that you can probably just write out the solution in Python.

3) Now review the Pseudocode and change it accordingly to best solve the problem at hand.

4) Test that it works. If you solve the problem without any major bugs or security issues that you are aware of - then you are fine.

5) Now that you confirmed the solution is working. Go back and re-look at the code to see if there is anything further you can improve. There are various tools you can use to memory profile and measure the time spent processing. Learning how to use and understand these analysis tools can help you immensely. Examples: pypi.org/project/cognitive-complex... and pympler.readthedocs.io/en/latest/.

When you get into a company, there will be senior developers who will review your code. This is a great way to learn, as they will have the experience and domain knowledge and give you valuable feedback on ways to improve your code.

Even before getting into the workforce, you can still find people who are well-established and respected by the community of your language, follow these people on GitHub or Twitter and try to learn as much as you can from them.

Both the above approaches are far more valuable than just relying on BARD or ChatGPT. Remember LLMs use prediction algorithms and won't always give you a solution that works or is efficient.

Furthermore, reading books from well-established authors in your language of choice is a great way to learn the best practices. Hope this helps!

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