Jump to content
ydoaPs

The Official Programming Tips Thread

Recommended Posts

I noticed that a lot of the programming questions here, while phrased in terms of coding in specific languages, are actually rooted in a broader context of programming itself. People are having problem with the ideas behind programming in general. If we help people with algorithm building, the language-specific syntax falls into place.

 

So, this thread is for tips on programming in general. This isn't about programming in python or programming in java. This is about the fundamental heart of what one needs to do. If anything, it's tips on how to code in PseudocodeTM.

 

I'll start:

 

One of the biggest thing about programming is being able to break a problem down into chunks and then break those subproblems down. Keep doing that until you get a picture of what specifically you need to do to accomplish each major step. So, if your program needs to do things in three big steps, start even lower than pseudocode; start with a list.

 

Step 1

Step 2

Step 3

 

Then, take each of those steps and do the same thing.

 

Step 1:

Step 1a

Step 1b

Step 1c

Step 2:

Step 2a

Step 2b

Step 2c

Step 3:

Step 3a

Step 3b

Step 3c

 

You may or may not notice the indentation. That brings up my second tip.

 

Use indentation, called "whitespace", in your programs and even pseudocode. Some languages require you to have whitespace indentation (like python and the never ending tabs v spaces war), but many do not. It is still good practice for writing though. Most languages have interpreters or compilers that ignore anything about whitespace other than whether there is at least one space between two letters, so it won't hurt the program but it will help you. Writing, or at least planning, with whitespace keeps ideas organized. Look at the example in the previous tip. You see each substep, and it's clear where in the logic that it belongs. It makes code easier to read and understand, even if it's not required.

 

Speaking of readability and understanding, that's where my last two tips come in.

 

Make good names. Names like "MyFunction" or MY_CONSTANT are bad names. They don't tell you what the function is doing or what the constant is for. Make names descriptive, and your code will be easier to understand and easier to read. Rename (or "refactor") if you need to. Many programming environments will even let you replace all instances of one name with instances of the new name, so it won't even be a long tedious thing. Renaming, if giving a new name, is a good thing. It promotes clarity.

 

Comment everywhere. Comment to the point that you think you're overcommenting, and then comment some more. Future you will likely have no idea what your code is doing, so leave good notes for future you to use to figure it out.

 

Your turn.

Share this post


Link to post
Share on other sites

Comment everywhere. Comment to the point that you think you're overcommenting, and then comment some more. Future you will likely have no idea what your code is doing, so leave good notes for future you to use to figure it out.

 

Make your comments descriptive and useful (e.g. don't comment a line that increments a counter with /* increment counter */, try something like /* keep track of the number of lines we have processed */). Imagine you are explaining your code to someone else (who isn't as smart as you) when writing comments.

 

Add comments at the start of each file saying what that file contains.

 

Add comments at the start of each function/procedure saying what the function does, what parameters it takes and what it returns. Add comments at each step in the function explaining what it is doing and why it is doing it that way - it is OK to document your design decisions in the comments. Otherwise, one day you might come back and think, "that seems an odd way of doing it; I think I'll simplify it .... Oh no! Why doesn't it work any more!?"

 

As well as using meaningful variable names, add comments to the declarations with more info (e.g. why it is that type /* We use a set rather than a list here to automatically remove duplicates, and we don't care about the ordering */)

 

If you "temporarily" comment out lines to try a different implementation then:

1. Add a comment explaining why those lines are commented out

2. Consider deleting them when you are happy with the new version

3. Start using a version control system!

 

Keep the comments up to date with the code; e.g. if a function is given an extra parameter, update the comments.

Share this post


Link to post
Share on other sites

Make your comments descriptive and useful (e.g. don't comment a line that increments a counter with /* increment counter */, try something like /* keep track of the number of lines we have processed */). Imagine you are explaining your code to someone else (who isn't as smart as you) when writing comments.

 

Add comments at the start of each file saying what that file contains.

 

Add comments at the start of each function/procedure saying what the function does, what parameters it takes and what it returns. Add comments at each step in the function explaining what it is doing and why it is doing it that way - it is OK to document your design decisions in the comments. Otherwise, one day you might come back and think, "that seems an odd way of doing it; I think I'll simplify it .... Oh no! Why doesn't it work any more!?"

 

As well as using meaningful variable names, add comments to the declarations with more info (e.g. why it is that type /* We use a set rather than a list here to automatically remove duplicates, and we don't care about the ordering */)

 

If you "temporarily" comment out lines to try a different implementation then:

1. Add a comment explaining why those lines are commented out

2. Consider deleting them when you are happy with the new version

3. Start using a version control system!

 

Keep the comments up to date with the code; e.g. if a function is given an extra parameter, update the comments.

A common analogy is to comment like you're explaining it to a rubber duck.

Share this post


Link to post
Share on other sites

 

Make your comments descriptive and useful (e.g. don't comment a line that increments a counter with /* increment counter */, try something like /* keep track of the number of lines we have processed */). [...]

Or you call your counter variable "numberOfLinesProcessed" or "linesProcessed" and reconsider if you really need to comment the increment. In my experience, certain circles tend to dislike in-code commenting except for cases where something unexpected happens or a non-obvious choice has to be explained (and both case classes should be avoided). And in recent years I have come to adapt that way of programming. That said, "comment a lot, even in-code" is probably still a good advice for beginning programmers, who I assume are the target audience for this thread.

 

As for a tip I'd have: If in doubt, try it out. Simple examples: What values does a loop over "range(10)" cover? Is "x[1]" the first or the second element in an array x? What is the result of y = A*x, where A is a 2D-array/matrix and x is a 1D-array/vector? You can read the manual. But it takes time and you need to be certain that you understood it correctly. And once you leave language features and go to library-features you also have to implicitly assume that the library behaves according to its documentation (i.e. that it does not have a bug). Or you can just assume something and hope everything goes well. Or you can just try it out and discover the answer for yourself, which is often faster than reading manuals and produces less errors than just assuming some behaviour. And most importantly: It's the most fun variant.

Edited by timo

Share this post


Link to post
Share on other sites

One of the biggest thing about programming is being able to break a problem down into chunks and then break those subproblems down. Keep doing that until you get a picture of what specifically you need to do to accomplish each major step. So, if your program needs to do things in three big steps, start even lower than pseudocode; start with a list.

 

The best is to start with activity diagrams, with arrows.

https://en.wikipedia.org/wiki/Activity_diagram

Share this post


Link to post
Share on other sites
Learn some math. Even the really basic stuff can let you do really cool things. Many of the machine learning techniques aren't all that mathematically complicated. Neural networks, for examples, are little more than optimizing weighted averages of a step (or sigmoid or something like a sigmoid) function.

Share this post


Link to post
Share on other sites

I am exaggerating very slightly in this list. But not much.

  1. Write a specification.
  2. Get it reviewed.
  3. Then write a test plan based on the specification.
  4. Get it reviewed.
  5. Then write the tests, based on the test plan.
  6. Get them reviewed.
  7. Correct the specification based on the errors this throws up.
  8. Write the documentation.
  9. Get it reviewed.
  10. Correct the specification and test plan based on the errors this throws up.
  11. Oh, yes. Implement the software. (Nearly forgot.)
  12. Correct the specification and test plan based on the errors the throws up.
  13. Run the test suite for each module and for the complete program.
    Fix any bugs and get the changes reviewed before committing them back to the repository.
    This should not be the longest part of the development process (but, sadly, for most people it is).
Edited by Strange

Share this post


Link to post
Share on other sites
On 9/29/2016 at 5:41 PM, ydoaPs said:

Comment everywhere. Comment to the point that you think you're overcommenting, and then comment some more. Future you will likely have no idea what your code is doing, so leave good notes for future you to use to figure it out.

I'd say the opposite: Be conservative in your use of comments. Code should typically be reasonably self-descriptive.

Share this post


Link to post
Share on other sites
28 minutes ago, Thorham said:

I'd say the opposite: Be conservative in your use of comments. Code should typically be reasonably self-descriptive.

I use comments (in 99.9% of times) only to disable some part of code.. ;)

ps. And to-do e.g. // TODO: [...what to fix in the future...]

Some IDE even have special feature to automatically search for and make a list of such TODO comments.

Edited by Sensei

Share this post


Link to post
Share on other sites
1 hour ago, Thorham said:

I'd say the opposite: Be conservative in your use of comments. Code should typically be reasonably self-descriptive.

The point of commenting is to explain what the code is doing at a higher level than the code can describe. And to explain why the code is implemented in a particular way.

// We have to check the fuel level doesn't get too low or the pump could burn out
if (fuel_level < MIN_FUEL_LEVEL) {
    ... ring alarm bell
}

Or

// Note we use a bubble sort here: you may have been taught that this is the worst
// possible type of sort, but it works really well on a parallel architecture like this
... sort routine

 

And I suspect people who argue for minimal commenting haven't had to debug soon else's code!

Share this post


Link to post
Share on other sites
4 hours ago, Strange said:

And I suspect people who argue for minimal commenting haven't had to debug soon else's code!

By conservative I don't mean minimal commenting, I mean not commenting obvious code. I don't like having so many comments that maintaining them becomes a second job.

Share this post


Link to post
Share on other sites
6 hours ago, Thorham said:

I don't like having so many comments that maintaining them becomes a second job.

Good point.

Share this post


Link to post
Share on other sites

If you notice yourself trying to do too much in a single function, break it down into helper functions, and have your function just call those helper functions. Give the helper functions descriptive names, such that when you read the main function, you know exactly what is happening, without looking at the implementation of the helper functions.

Share this post


Link to post
Share on other sites
On 4/2/2018 at 9:39 AM, Thorham said:

By conservative I don't mean minimal commenting, I mean not commenting obvious code. I don't like having so many comments that maintaining them becomes a second job.

Comments should explain why something is to be done, not what is being done.

Maintaining comments is not a second job, it is the FIRST job.

You should always write the comments before you write any code at all.

And similarly, you change the comments before you change any code.
The reason is because if you only write code for yourself and don't make it obvious through comments, no one else if going to every use it, and it will just be thrown away.  Code I write is still being used 30 years later, because I made sure anyone can understand it easily.

Edited by Rigby5

Share this post


Link to post
Share on other sites

Thanks for sharing such a great knowledge and the replies over your thread are also useful. Thank you again.

Share this post


Link to post
Share on other sites
On 4/2/2018 at 7:31 AM, Strange said:

And I suspect people who argue for minimal commenting haven't had to debug soon else's code!

I've had to do a lot of it with absolutely no commenting. I'd actually venture to say that descriptive variable names are more useful(But this doesn't mean that comments shouldn't be used!!!!!!!!!! Just that they're not as helpful as descriptive variable names.) . Using your code example:

 

On 4/2/2018 at 7:31 AM, Strange said:

The point of commenting is to explain what the code is doing at a higher level than the code can describe. And to explain why the code is implemented in a particular way.


// We have to check the fuel level doesn't get too low or the pump could burn out
if (fuel_level < MIN_FUEL_LEVEL) {
    ... ring alarm bell
}

 

For example #1. 

I'll read the words above. That'll take me 17 words.

I'll then read the code below it. That'll translate to me as: "If fuel level is smaller then the minimum fuel level, ring the alarm bell." (14 words)

I still would have had to read the 14 words of code. The comments simply would have made it take twice as long to read.

However, had it been extremely complicated to understand the code, such as parsing out delimited data, comments are definitely warranted.

Share this post


Link to post
Share on other sites
Posted (edited)

@Raider5678

Absolutely. Descriptive variable names, descriptive class names, descriptive structure names, descriptive constants etc. etc. are essential for readable and maintainable in the future source code..

ps. Example from my yesterday project: context.getString( R.string.voiceedittext_speech_error_insufficient_permissions ); .... I don't need to comment, I hope so.. ;)

 

Edited by Sensei

Share this post


Link to post
Share on other sites
On 10/2/2019 at 10:12 PM, Sensei said:

ps. Example from my yesterday project: context.getString( R.string.voiceedittext_speech_error_insufficient_permissions ); .... I don't need to comment, I hope so.. ;)

Is there a point where variable names become too descriptive?

For example, would "InsufficientPermissionsErrorString" have sufficed? (Go CamelCase!)

Share this post


Link to post
Share on other sites
Posted (edited)
4 hours ago, Raider5678 said:

Is there a point where variable names become too descriptive?

Yes.. when you have to horizontally scroll text to be able to read them all.. ;)

 

4 hours ago, Raider5678 said:

For example, would "InsufficientPermissionsErrorString" have sufficed? (Go CamelCase!)

Some prefer "reverse notation".. e.g. main_error_insufficient_permissions

so other "main_" strings/variables/classes etc. are listed in alphabetically sorted order together in IDE,

and other "main_error_" are listed in sorted order together in IDE,

etc.etc.

If you have human natural language order, they would be all mixed together.

"main" is place where is used specified string (in Android app),

"error" is what is subject of specified string.

e.g. you have class which has name PasswordEditText,

so prefix will be

"passwordedittext_" and the all its strings grouped together in strings.xml

This has to help them listed together due to sorting algorithm in IDE (auto-fill/auto-completion feature of IDE).

 

Edited by Sensei

Share this post


Link to post
Share on other sites
18 hours ago, Sensei said:

This has to help them listed together due to sorting algorithm in IDE (auto-fill/auto-completion feature of IDE).

I used visual studio, and it has the auto-completion feature.

But I've never actually used it. Naming conventions for variables where I work at are usually just "Make sure they're descriptive" not that they follow an order that allows them to be identified faster.

That being said we don't program in form 5 much either, so this situation wouldn't apply very often.

Share this post


Link to post
Share on other sites
5 minutes ago, Raider5678 said:

I used visual studio, and it has the auto-completion feature.

But I've never actually used it. Naming conventions for variables where I work at are usually just "Make sure they're descriptive" not that they follow an order that allows them to be identified faster.

That being said we don't program in form 5 much either, so this situation wouldn't apply very often.

You are not using correctly ordered names, so auto-fill/auto-completion cannot work. I am using it every day.

In Android Studio (Java) OTOH if you start writing e.g. "permission", IDE is searching this term also inside of name and make it bold. e.g. main_error_insufficient_permissions (so actually it would be sufficient to enter "pe" or "per" to limit list of available results, and pick the right one from drop-down list).

Share this post


Link to post
Share on other sites
8 minutes ago, Sensei said:

You are not using correctly ordered names, so auto-fill/auto-completion cannot work.

It does work actually. Type the first 4-5 letters of the variable, then hit tab when that variable you want is highlighted, and it almost always gets it right.

Visual studio accounts for variable types and it also predicts the variable you're going to use from some sort of artificial intelligence algorithm. Works quite well. 

Share this post


Link to post
Share on other sites

Descriptive comments and structured programming techniques are probably the best things that all programmers can do at all times but comments are a little different.

If you have worked on much legacy code you have probably already seen extremes from both ends of the commenting spectrum. From those who think that comments only induce people who don't know how to read code to stuff up programs to people who comment on every single line.

I can see the benefits of both extremes and tend to go for a happy medium where comments are used as necessary/sparingly to describe the tricky bits and the garden variety code speaks for itself.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.