Jump to content




Eight Good Coding Habits


  • You cannot reply to this topic
56 replies to this topic

#1 Bubba

    Use Code Tags!

  • Moderators
  • 1,142 posts
  • LocationRHIT

Posted 30 October 2012 - 03:42 AM

Props to Lyqyd for pointing out some errors in my tips
Lua is an incredibly versatile programming language. Many things that one would think to be incorrect will run correctly in Lua, and in some cases that's a good thing: Usually though, it's not. When you begin to write long programs (and by long, I mean multiple files and mind-blisteringly complex interweaving of functions), things that you started writing at the beginning of the program are not going to be as obvious several months later as they were when you first wrote them. Bad coding practices in this regard will kill your program in readability and functionality if you're not careful, so try to make these simple programming practices a habit so that life doesn't suck later.

1) Make comments on you own code. You're probably rolling your eyes right now thinking, "I know what my own code does. Why should I put comments on it?" And that's a valid question. Today I was looking back through some several month old code of mine and I didn't even know what the thing was supposed to do, let alone how I was supposed to utilize it. Figuring out its purpose would be nearly impossible without painfully going over every single function and testing them individually. So unless you want to rewrite your code every few months, or if you enjoy that painful 'decompiling' process, don't forget to comment as much as possible.

2) Indentation. I can't stress this one enough. When you're inside of an if statement inside of a for loop inside of a while true do loop inside of a function, your code gets really messy really quick. If you don't indent everything, you are going to absolutely hate life later on when you find get an eof or 'end expected' error and you have no idea why. So yeah. Indentation is important.

3) Be concise: If you are making a function that moves a turtle forwards 12 spaces, don't name it 'thisisafunction()' because somebody looking at your code will have absolutely no idea what it's supposed to do without parsing it out. And it will suck if that somebody is you twelve months later.

4) Use the right tool for the job and be consistent about it. If you think that an ipair loop would fit a certain situation and that situation comes up later, be consistent and use the ipair loop again. Coding consistently is enormously helpful when you find yourself using the same tools over and over again because you become familiar with how you should go about different situations.

5) Remove unnecessary code. This one seems like a no-brainer, but you'd be amazed at how lazy the average human being is (or maybe you wouldn't). I often find myself just ignoring the fact that I don't use a certain function in an API and adding new things just becomes confusing when you keep looking at the unused code to see what it does. Another reason to remove unnecessary code is that it makes the whole program just 'better' and more satisfying than when the whole thing is a rag-tag mess. Making a complex program using only a few ingenious lines of code is the most enjoyable thing in programming, in my opinion :)/>

6) Take breaks. If you're stuck on a problem, don't sit there and stare at it for ages trying to figure it out. Go grab a drink, eat some cereal, or play a game to take your mind off it for a while. Better yet, go and take a nap. When you come back, I can promise you that you'll be able to solve the problem much, much quicker than you would otherwise.

7) Try to make an 'outline' of what you want your program to do and how you might want to go about it. This mostly only applies to long and/or complex programs, but if you're having difficulty writing anything, an outline will help out enormously.

8) Program in a way that fits you: If you program best jumping about from function to function, program like that. If you program best completely finishing each function before moving on, program like that. The unique thing about programming is that there are an infinite number of ways to go about a problem. If you have trouble working in a certain way, don't force yourself to do so.

If you take to heart these eight simple coding habits, I promise you life will be infinitely easier when you're faced with that mega-challenge you've been wanting to solve for a long time.

Thank you for reading,

Bubba

Edited by Bubba, 18 February 2014 - 08:19 PM.


#2 Dlcruz129

    What's a Lua?

  • Members
  • 1,423 posts

Posted 31 October 2012 - 03:05 AM

Another idea: always, always, ALWAYS, use local variables unless the program calls for global variables.

#3 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 31 October 2012 - 05:25 AM

View PostChallenge.Accepted, on 30 October 2012 - 03:42 AM, said:

1) Make comments on you own code. You're probably rolling your eyes right now thinking, "I know what my own code does. Why should I put comments on it?" And that's a valid question. Today I was looking back through some several month old code of mine and I didn't even know what the thing was supposed to do, let alone how I was supposed to utilize it. Figuring out its purpose would be nearly impossible without painfully going over every single function and testing them individually. So unless you want to rewrite your code every few months, or if you enjoy that painful 'decompiling' process, don't forget to comment as much as possible.

I would stress that the why of the code is far more important than the what of the code you're commenting. Why do we need to take the third character of the string and convert it to uppercase? Oh, because this other function we're calling needs it that way. So instead of "convert the third character to uppercase", something like "checkCharacter() requires its input to be uppercase" where that code is will be much more meaningful. The code will tell you what it's doing usually, but it can be much trickier to figure out why it needs to do that.

View PostChallenge.Accepted, on 30 October 2012 - 03:42 AM, said:

3) ALWAYS return something when you exit a function. I know it oftentimes seems unnecessary, but trust me when I say that debugging is a pain in the ass if you don't return something printable.

As with everything, there are exceptions to this rule. Sometimes nil or a boolean is all a function needs to return. Just know when to use what.

View PostChallenge.Accepted, on 30 October 2012 - 03:42 AM, said:

4) Keep your programming consistent. What I mean by that is don't sometimes use ipairs loops and other times use fori loops, unless of course the situation absolutely calls for that inconsistency. Things often become confusing when you mix and match your code.

This falls more under "use the right tool for the job" rather than "be consistent with your tools". You can try to drive a screw with a hammer, but damned if it isn't going to suck. Each of those things has their place.

View PostChallenge.Accepted, on 30 October 2012 - 03:42 AM, said:

6) Take breaks. If you're stuck on a problem, don't sit there and stare at it for ages trying to figure it out. Go grab a drink, eat some cereal, or play a game to take your mind off it for a while. When you come back, I can promise you that you'll be able to solve the problem much, much quicker than you would otherwise.

Better yet, go sleep on the problem. It's relatively well-documented that your subconscious will continue working on problems long after your conscious mind has moved on to other thoughts.

View PostChallenge.Accepted, on 30 October 2012 - 03:42 AM, said:

7) Program in a linear manner. When you program, do you find yourself jumping about from function to function, leaving some unfinished and others with errors in them? If you do, programming big programs will be extremely difficult. When you start a function, don't stop until you either finish it or you do away with it in favor of something else.

8) Program in chunks. This one is sort-of related to the previous point in that you should focus on certain aspects of a program and complete them before moving on to something else. For example, if you're making a mining program which sorts items based on ID, you might want to focus on the comparison of items first before moving on to navigation.

Neither of these are quite right. For the most part, program how it works best for you. Some people find it easiest to crank out code from the top of the file to the bottom and very infrequently jump around until the initial code is all written. Some people use a more figurative top-down approach where they write out the flow of the program using placeholder functions and then go flesh out what everything actually needs to do a bit at a time, until all the details are there. There are a myriad ways to program. Don't try to force yourself into a certain method of doing so. As long as you're creating good code, I wouldn't worry about changing your process. That said, if you're having trouble with getting lost or being unable to keep track of what you're doing, you might consider changing the way you write code.

All in all, a good post, Challenge.Accepted. Hope you don't mind me adding my thoughts!

#4 ChunLing

  • Members
  • 2,027 posts

Posted 31 October 2012 - 08:44 AM

I find that it can be very helpful, when you go back over a code with "fresh eyes", to not have any comments on what the code is supposed to do or even why it is supposed to do it. This isn't to say that comments aren't valuable, but if you are going to substantially revise a code later, you might consider having a version that has no comments so you can really approach it fresh. Of course, you don't want to throw away the version that has all the comments, particularly if the code is very complex.

Also, try to distinguish between your comments on something that the code really does and comments saying what you want it to do.

#5 BigSHinyToys

  • Members
  • 1,001 posts

Posted 31 October 2012 - 10:14 AM

Writing code in a IDE or word pad designed for development is also a good idea. trying to write code in Microsoft office is not going to end well where as Notepad ++ will help you with highlighting and showing start / end of blocks. Most of the bugs I have fixed in code posted in the "ask a pro" section have been from placing it in Notepad ++ and adding indentation till i find where a missing end is or problems like using "else if" instead of elseif and putting an end for elseif's is also common.

I have been doing most of the tips already I put a header with intended purpose / other relevant information at the top as quick reference I don't comment or have returned values < I may conceder doing this thought. I work form the start of a program to its finish making and testing every function in turn until I have a working program. I don't jump around inside my code much. My main problem is I don't plan out how I want my code to look / what function / structurer at the start I sort of wing it with a basic idea of intended function. This leads to unintelligent solutions for problems that may have never existed had I coded a different way.

Seeing as I want to move to a more powerful language I think I will incorporate some of these tips into my "coding style" .

Thanks for the tips

#6 KaoS

    Diabolical Coder

  • Members
  • 1,510 posts
  • LocationThat dark shadow under your bed...

Posted 31 October 2012 - 11:34 AM

I find that writing code strictly in functions helps. I will never write a code for a specific menu, I will always write a generic menu generator and use it later, I also store most data in tables etc. basically I try to categorize my code into a function and table for one thing and another function and table for another thing. it keeps things organised, makes bug testing easy as you just test each function and the actual executing part of the code is about 5 lines long, easy to rearrange and change as needed. you will also find that if you keep all generic functions in a single file you end up coding less and less to make stuff 'cos you already have functions for everything... it is a long term tactic but is great in my opinion

-perfectionist coder out

EDIT: Oh yeah, great thread man. kickass stuff

#7 kazagistar

  • Members
  • 365 posts

Posted 31 October 2012 - 05:49 PM

While I agree with KaoS that more abstraction is needed by a majority of the newer programmers here, there is a danger of overabstraction. If you create a "menu system" and then only use it to build one menu, you have wasted time. Often, the best approach is to only abstract once you are actually building the second menu, and then refactor the first.

If you copy and paste code within your program, you are probably not abstracting enough.

If you have functions you only use once, you are probably overabstracting.

#8 Bubba

    Use Code Tags!

  • Moderators
  • 1,142 posts
  • LocationRHIT

Posted 31 October 2012 - 08:46 PM

View PostLyqyd, on 31 October 2012 - 05:25 AM, said:

Good stuff
Yes I agree with pretty much everything you said and have shamelessly stolen some of your points and modified my post concordantly.

I should also mention that not all individuals will find that these tips apply to them - as you said, some people do skip around when they're coding, and they can do just as fine a job as someone who does not. If one of these things doesn't work for you, don't try to force it. Find a workflow you like, and utilize that workflow to your advantage. Some things (indentation for example) are in my opinion indispensable - others however are up to you.

#9 Learning_inpaired

  • New Members
  • 77 posts

Posted 20 December 2012 - 03:07 PM

Bumbed!

#10 Tiin57

    Java Lunatic

  • Members
  • 1,412 posts
  • LocationIndiana, United States

Posted 20 December 2012 - 03:58 PM

-.-

View PostLearning_inpaired, on 20 December 2012 - 03:07 PM, said:

Bumbed!
Why do you persist in bumping?

View PostLearning_inpaired, on 20 December 2012 - 03:06 PM, said:

Bumbed!
In http://www.computerc...2101#entry62101
Stoppit.

#11 sjkeegs

  • Members
  • 75 posts

Posted 20 December 2012 - 04:50 PM

Here's another tip:

If you are programming something to do X, write the function that does that by just writing the comments. Once you convince yourself that the comment flow is correct then add the actual code.

#12 Doyle3694

  • Members
  • 815 posts

Posted 20 December 2012 - 11:25 PM

Ehrm.... How would that work, @sjkeegs ?

#13 Mikeemoo

  • Members
  • 732 posts
  • LocationLondon, UK

Posted 21 December 2012 - 12:36 AM

View PostDoyle3694, on 20 December 2012 - 11:25 PM, said:

Ehrm.... How would that work, @sjkeegs ?

function gotoMyFurnace()
  -- find current  position
  -- grab the position of the furnace
  -- move x times in x direction

  -- move y times in y direction
  -- move z times in z direction

end

Evolves to..

function getCurrentPosition()
  -- return current position
end


function getFurnacePosition()
  -- return furnace position
end
function getRelativeCoords(from, to)
  -- return relative coords
end
function moveBy(vec)
  -- move the turtle by vec (x, y, z)
end
function gotoMyFurnace()
  local currentPosition = getCurrentPosition()
  local furnacePosition = getFurnacePosition()
  local relativeCoords = getRelativeCoords(currentPosition, furnacePosition)
  moveBy(relativeCoords)
end

Evolves to...


function getWaypoint(key)
  return waypoints[key]
end

function getCurrentPosition()
  -- gps.blah
  return { x=, y=, z=}
end


function getFurnacePosition()
return getWaypoint("furnace")
end

function getRelativeCoords(from, to)
  return {x=from.x-to.x, y=from.y-to.y, z=from.z-to.z}
end

function moveX()
  -- face x
turtle.forward()
end


function moveY()
  -- face y
turtle.forward()
end


function moveZ()
  -- face z
turtle.forward()
end

function moveBy(vec)
  for x=1, vec.x do moveX() end
  for x=1, vec.y do moveY() end
  for x=1, vec.z do moveZ() end
end

function gotoMyFurnace()
  local currentPosition = getCurrentPosition()
  local furnacePosition = getFurnacePosition()
  local relativeCoords = getRelativeCoords(currentPosition, furnacePosition)
  moveBy(relativeCoords)
end

..etc..etc..

(this is obviously badly written code that would never work, but you get the idea)

#14 sjkeegs

  • Members
  • 75 posts

Posted 21 December 2012 - 03:07 AM

View PostMikeemoo, on 21 December 2012 - 12:36 AM, said:

View PostDoyle3694, on 20 December 2012 - 11:25 PM, said:

Ehrm.... How would that work, @sjkeegs ?

function gotoMyFurnace()
  -- find current  position
  -- grab the position of the furnace
  -- move x times in x direction

  -- move y times in y direction
  -- move z times in z direction

end

Evolves to.. ..etc..etc..


Yes, Essentially you write the code in comments. The process of doing that makes you think about how you are implementing it before you start to write the code. You find errors in your structure before you start writing anything. If you get half way through and your discover that your implementation isn't actually going to work, you haven't wasted time building code that you are going to have to throw away. It's also easier to recognize that the implementation is wrong and start over. It curbs the desire to muddle through on a design that doesn't quite work. An added bonus is that when you are already done your code should already be commented - No need to go back and do that. You end up with comments that are a better description of the code flow. (You are less likely to have a comment like // increment counter by one)

#15 ChunLing

  • Members
  • 2,027 posts

Posted 21 December 2012 - 06:52 AM

I think that Doyle was asking how the function would do anything just by being full of comments.

View Postsjkeegs, on 20 December 2012 - 04:50 PM, said:

--snip--
If you are programming something to do X, write the function that does that by just writing the comments.
--snip--
Clearly, this is not the intended meaning. It just happens to be the literal meaning of the actual wording of the post.

In a situation where the apparently possible intended meaning of a post does not match the literal meaning (particularly when the literal meaning is apparently impossible), it is appropriate to ask about the intended meaning. It may be considered less appropriate to focus on the impossibility (or mere silliness, as the case may be) of the literal meaning. We all mess up our literal meanings sometimes.

#16 Loki

  • New Members
  • 26 posts
  • LocationA flatland world with 100's of computers and a village that was covered with lava with a parkour course about it; Minecraftia.

Posted 04 January 2013 - 05:41 PM

Well, I'm glad I follow 6 out of 8 of these habits. Time to take a nap, I guess.... Or eat some cereal...^_^

#17 PixelToast

  • Signature Abuser
  • 2,265 posts
  • Location3232235883

Posted 04 January 2013 - 08:19 PM

the only ones i dont follow are 6 and 7
i dont take verry many breaks and i dont really have an outline for things im making :s

#18 Leo Verto

  • Members
  • 620 posts
  • LocationOver there

Posted 05 January 2013 - 03:26 PM

I also don't follow 6 and 7, I sometimes spend hours fixing a problem, then finding another one, and another one, etc until my code works.
I think I should organize my coding better by making an outline and adding comments that explain why a function is coded as it is (as immibis explained above).
I did not know about always making a function return stuff, now that I read about it it seems to make sense but a lot of programs I read don't do it.

I think properly naming your arguments is another important point, unless you don't want anyone to be able to read your code.

#19 ChunLing

  • Members
  • 2,027 posts

Posted 05 January 2013 - 05:21 PM

Eh, if we're all talking about which ones we don't follow, I'm not very consistent about following any of them. I only comment for the benefit of others, and I suck at it. My indentation is an atrocity. I only bother to put in returns when I'm definitely using them. I have pet functions and control structures. I almost never entirely remove a function, even if I never use it. I obsess over a code till it works. I have a vague concept rather than an outline. And I'm pretty sure that all of this is not "coding in a way that suits" me.

So I try to do whichever of these I happen to remember when the moment is appropriate. I do them "sometimes". Maybe trending up, maybe not.

They're all good ideas.

But I don't do "good" ;)

#20 Luanub

    Lua Nub

  • Members
  • 1,135 posts
  • LocationPortland OR

Posted 05 January 2013 - 05:30 PM

It all depends on the script I'm working on on which ones I follow. Small simple scripts I pretty much do not follow any of them while the larger projects I follow most of them. I do not do a lot of commenting since I pretty much know whats doing what. The only time I return something is if I am going to use it. I'm absolutely horrible about taking breaks, once I start working on a specific part of a script I don't like to stop until I have it functioning as desired.

For someone that is just getting starting I think these are some good guidelines to put in place until you become a little more comfortable with what you are doing.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users