A great programmer makes their code clear, robust, efficient, and user-friendly.
Code needs to be clear so others can read and understand your code.
Code needs to be robust* to reduce the number of errors in your program.
Code needs to be efficient to reduce the cost of your code.
Code needs to be user-friendly so that people will want to use your program.
Here are some Do’s and Don’ts that will guide you to becoming a better programmer. Bad style will cost your grade so keep these in mind and think of your own as well.
DO:
- Comment your code concisely
- Give your variables and functions good names for clarity
- End your phrases with semi-colons
- Indent your code properly
- Include your name, andrew ID, and section on the top of your code
DON’T:
- Have more than 80 characters in a line.
- Have dead code (code that does nothing, or commented out code)
- Use meaningless variable names
- Use magic numbers (numbers that come out of nowhere)
- Add too many comments, or redundant comments.
Here is a comparison of good and terrible code. If you can’t differentiate the two, ask for assistance as soon as possible.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/* * Andrew Carnegie * andrew@andrew.cmu.edu * Section Z * * This program draws gray concentric circles. */ function setup() { createCanvas(600, 600); // Sets up the canvas size background(50); // background is dark gray } function draw() { // draw a 4-ringed circle in the center of the screen drawConcentric(width / 2, height / 2, width / 3, 4); } function drawConcentric(xLoc, yLoc, radius, numRings) { // Interate through numRings and draw circles of decreasing // size. for (i = 1; i <= numRings; i++) { ellipse(xLoc, yLoc, radius / i, radius / i); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Lol comments function setup() { createCanvas(600, 600); background(50); background(2); background(7); } function draw() { // draw a 4-ringed circle in the center of the screen Draw2(300, 300, 100, 4); } function Draw2(v1, v2, v3, v4) { for (i=1; i<=numRings; i++) { ellipse(v1, v2, v3/ i, v3 / i) } } function DRAWSOMETHING() { rect(100, 100, 100, 100) // Lol rekt } |
*“Robust” is a great adjective that, when talking about software, has a fairly specific and technical meaning. Robust software is software that works without depending on many assumptions or conditions. A program that crashes when an expected file is not found is not robust. A program that reports the missing file, prompts the user to find the file, or presses on using reasonable default values is more robust.