What is you're tips to write clean and readable code? | SoloLearn: Learn to code for FREE!

+24

What is you're tips to write clean and readable code?

1/1/2020 7:38:09 PM

TempName

33 Answers

New Answer

+44

There is one thing that is very easy, and it's disregarded by way too many people, at least here on Sololearn: Choose proper names for everything! I see programs all the time that look like this (this is a simple case, there are a lot worse): for a in b[:]: if input()==c[a]: b.remove(a) Anybody an idea what's this about? There's a loop, there's a comparison with input, and a removal from whatever. Could be anything really. Now look at this: for word in words_to_learn[:]: if input() ==translation_of[word]: words_to_learn.remove(word) Suddenly we understand! Write your programs in a way that even a bystander taking a look can get *some* idea of what it's about.

+21

The first thing that I was searching in the answer section was "COMMENTS". Apart from identation and good naming conventions, COMMENTING YOUR CODE plays a major role in writing clean and readible code. I've seen many coder(including myself😅) neglecting comments (also proper naming convention and identation) in their code, i dont know whether they know or not that commenting your code wouldnt slow the Runtime or whatever. My new year resolution would be to improve what i have cited above.🙂

+18

I don't think anyone can answer that correctly, because it comes with experience. The more you write, you start to notice that some things are more redable than other. For example, you can't have someone tell you that you should keep a space after function, classes, loops.. because you would be confused. So just keep on learning, and try to write in a way that you can notice different blocks, different functions, different actions.. and so on There are some programming conventions tho, like naming, indenting.. you can read about them online by searching: Programming Conventions

+18

Here's some useful tips👍 https://www.sololearn.com/post/163011/?ref=app

+12

Never underestimate the use of a consistent style and formatting to enhance the readability of code. There's an often overlooked utility called "indent" that doesn't get as much use as it should. Some projects and organisations mandate a particular coding style and may even require the use of a source code document generator such as doxygen, javadoc, robodoc etc. See... https://en.wikipedia.org/wiki/Indent_%28Unix%29 https://en.wikipedia.org/wiki/Doxygen https://en.wikipedia.org/wiki/ROBODoc NASA C Style Guide https://ntrs.nasa.gov/search.jsp?R=19950022400 NASA C++ Coding Standards and Style Guide https://ntrs.nasa.gov/search.jsp?R=20080039927 GNU Coding Standards https://www.gnu.org/prep/standards/standards.html

+12

Lord Krishna, sure, if there's a convention, I would also use abbreviations, like x, y for a point in a coordinate plane, n for a number, i, j for matrix indexes, tmp or temp or _ for a throwaway value etc. Also if the context is obvious, in a short piece of code, you might not always need full words, like something like this: [w for w in words if len(w)>5] Also names might become too long, alright. But removing vowels from names just to lose a few letters - word to wrd, list to lst, maintenance to mntnnce, documentation to dcmnttn - looks more like a party game to me. No one reads any text letter by letter - we glance at full lines at once and recognize words in an instant. I recognize a long word more quickly if I'm used to it, than a short word or abbreviation I have to think about or even look it up. I don't understand the point 'I can't remove documentation'. In many cases, vague names make documentation necessary in the first place! Isn't it better, if the code is expressive by itself?

+11

HonFu I agree, to an extent. The 1st e.g, isn't obvious because you do not explain its purpose & the variables do not follow any convention--using short form of variables related to their functions, w, wrd for word, lst for list variables, etc. it's also missing documentation. Following basic conventions and writing documentation aproppriately, explaining its purpose, it would be more redable. The 2nd code while understandable based on its naming conventions is more verbose. If i was to write code in that style it would be less readable. As, I would be spending more time parsing the lengthy code. Besides, I can't not remove documentation. It's crucial in understanding the function/purpose of that specific piece of code, or the project as a whole, without having to read the entire thing every single time. # Remove words which match input from a list of words def wrd_rm(lst, wrd_lst) for w in lst[:]: if input() == wrd_lst[w]: lst.remove(w)

+9

I like my code to be elegant and efficient. The logic should be straightforward to make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well. In short, a programmer who writes clean code is an artist who can take a blank screen through a series of transformations until it is an elegantly coded system.

+8

My Tip: I recommend going through my solutions to truly grasp what dirty and unreadable code is. Inside sololearn, since i only use the app, i keep things as short as possible. But i would never tell someone to use my solutions because you would bang your head against the wall trying to break it down. In fact, even I as the writer would struggle to look back and understand what i wrote. Code is clean and readable when you can look back after days or months and still understand it.

+8

There are much guides and so on. This few points are only the facts, I learned "on the hard way". I totaly failed in this on the beginning. Name the variables as clear as possible. My first function name, which I shared with a community (not SL, ~3years ago), was: dont_repeat_this_shit_again(this, that). :( They told me, this name id just bs and not funny in any kind. This is not the spirit of clear expressions. With this mind, it will not work. Readablility I should not do spagetticode. I should divide complex functions in clear, little parts. Fantastic poetic expressions of code are nice example for skill- but horrible for other ppl. Maybe I need a code review, or I want to implement some new for myself later. Spagetticode is hard to read/ edit/upgrade. In proffesional surrounding, ppl must work with it. In open source ppl could say, rework this, I dont want research your code. Comments. Not clever comments- clear and easy to understand as possible. So much as needed, to understand the script.

+8

[cont...] > I recognize a long word more quickly if I'm used to it, than a short word or abbreviation I have to think about or even look it up. I do not write abbreviations/nmemonics for every code definitions all the time. They happen when solving code. e.g, I find myself using the 'range' function one too many times. It becomes 'rg'. >I don't understand the point 'I can't remove documentation'. In many cases, vague names make documentation necessary in the first place! A brief skim, reading a line or two of comment to get the purpose. The problem i'm trying to solve. That's what i mean by documentation. >Isn't it better, if the code is expressive by itself? Now getting to your main point. Math: Numbers vs words. Would you say words are more expressive than numbers? 2+9*8 vs two plus nine multiplied by eight Are words more or less readable here? 'notation as a tool of thought' comes to my mind. A bit heavy for some, try to skim the non heavy paragraphs https://www.jsoftware.com/papers/tot.htm

+8

BTW, did you know people were happy when es6 added arrow notation for functions: function(){} vs ()=> Edit: I didn't know it was a big deal either. e.g (check the js section), https://code.sololearn.com/WQ7PbJRB5W40

+7

Ivan Collado You have got only 1 public code, with an error. Solutions to code coach problems aren't visible to other people. If that's what you meant.

+7

Lord Krishna Oh, i always thought if you tapped on solutions in someone’s profile, it would show you their answers. I never clicked it because i didnt want spoilers. Maybe once I’ve done them all, I’ll post it if its not against the rules. As for that code i copied it from the comments with the intent to do something requested. I should get around to that.

+7

HonFu > But removing vowels from names just to lose a few letters - word to wrd, list to lst, maintenance to mntnnce, documentation to dcmnttn - looks more like a party game to me. It is, if removing vowel's the ultimate goal in it XD. list can also be l or L at least for function parameters, documentation would be doc, not that voweless thing... I'm not sure about maintenance. But, if I came up with that pretty sure could not find a better context related alternative. I lean on tacit definitions using full word definitions when necessary. Saving typing to absolute minimum. >No one reads any text letter by letter - we glance at full lines at once and recognize words in an instant. True. But, when I'm looking at code longer than a few lines. The amount of stuff its filled with decides if i'm going to bother reading it. Will explain with an analogy later. [Char limit...]

+6

Use Coding Methodologies, that will help you a lot especially when you are debugging your code. Comments will also help you.

+6

A few tips: 1. Keep variable names consistent (decide if you prefer integerArray or integer_array, continue with this naming convention throughout code). 2. Keep an eye out for repeated lines of code. Sometimes, it may be better to store repeated lines in a single function, then iterate over the function multiple times. 3. The simplest code is usually the most efficient. If you have "int a = 12; print(a);", decide if it is better to store the integer in "a" to reuse, or if it is better to just print("12"). 4. Have a main() function that calls the other functions. Try not to call functions inside functions that do not return void. 5. Keep declared variables grouped by their data type. "int a, b; char c[5]" looks better than "int a; char c[5]; int b;" EDIT: One of the most important factors-- indentation! For readability on multiple devices, tab indentation is usually preferred over single spaces. In many languages other than Python, whitespace is typically ignored, but for legibility purposes, whitespace and indentation should remain consistent. Decide if you prefer "int a = (b/c);" or "int a = ( b / c );"

+5

Martin Taylor indentation is not overlooked in python because it is absolutely necessary

+5

I'dd like to add - 1. To use constants and not non sense numbers in the code. 2. Write simple stupid code - don't try to find a complicated way to show how intelligent you are - remember you have to understand it in a year ! (example is to write a complicated C sentence that to understand it , any how someone should write 5 lines t! ) 3. Keep conventions. 4. The code shall view nicely. If is cluttered, the mind is cluttered!

+5

Reading other developer's code, filtering out what I don't prefer including in my shelf. Next, I practice what I have till they become part of me. Some of my preferred styles are. #1. A function shouldn't exeed 10 lines of code #2. A function should do one and only one task. #3. Variable name should try to be expressive even when it is used once. For example, if a function 'renameFile(String name)' returns true or false when successful or otherwise, I prefer boolean renamed = renameFile("test.txt") than boolean x = renameFile("test.txt"). #4. Decide this for(i=0; i<10; i++) Or for(i = 0; i < 10; i++) #5. I use Java mostly, and when a class code exceeds a thousand line of code, I am mostly doing something wrong. Come up with a standard limit. # 6. Comments should be as short as possible and informative. For example, don't do this x = y + z // x is the sum of y and z (not informative) but this I prefer x = y + z // x is the sum of y coordinate and z coordinate (informative; they are coordinates) . ....