Moderators: phlip, Moderators General, Prelates
pollywog wrote:I want to learn this smile, perfect it, and then go around smiling at lesbians and freaking them out.Wikihow wrote:* Smile a lot! Give a gay girl a knowing "Hey, I'm a lesbian too!" smile.
PM 2Ring wrote:It may be necessary to use comments to explain what some code is doing, and perhaps to explain why it's doing it. They should not be required to explain how it's doing it, unless the code is using some obscure but efficient algorithm. In general, use of arcane clever code is discouraged, since it breaks Kernighan's rule: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."
int x = getMachineStatus();
if (x == 4)
{
doSomething();
}
int x = getMachineStatus();
if (x == 4) // Check if the machine is running
{
doSomething();
}
enum MachineStatus {Idle, Running, Alarm};
MachineStatus currentStatus = getMachineStatus();
if (currentStatus == MachineStatus.Running)
{
doSomething();
}
enum MachineStatus {Idle, Running, Alarm};
MachineStatus getMachineStatusImproved()
{
#pragma push ignore deprecated getMachineStatus
MachineStatus currentStatus = getMachineStatus();
#pragma pop ignore deprecated getMachineStatus
// There is a problem with the legacy API where Idle is sometimes returned
// on an Alarm if we are in a particular corner case (describe corner case here).
// There are other consumers of the API that rely on that corner case working,
// and we are unable to deal with it at this time, because of problems X, Y
// and Z. The decision was taken to fix it in an extended function. The
// original function is now deprecated.
if (currentStatus == MachineStatus.Idle)
{
dealWithCornerCase();
}
return currentStatus;
}
rpenido wrote:Can you post a code example of what are you talking about ?
if entry.file?
<<< do something >>>
elsif entry.directory?
<<< do something else >>>
endif entry.file?
<<< do something >>>
else # entry is a directory
<<< do something else >>>
end-- Project Euler, Problem 55
import Data.List (unfoldr)
import Text.Printf (printf)
numToDigitsRev = unfoldr (\n -> if n < 1 then Nothing else Just (n `mod` 10, n `div` 10))
digitsToNum = foldl (\n d -> n*10 + d) 0
reverseInt = digitsToNum . numToDigitsRev
isPalindrome n = let ds = numToDigitsRev n in ds == reverse ds
isLychrel x = not $ any isPalindrome $ take 50 $ drop 1 $ iterate (\x -> x + reverseInt x) x
main = printf "There are %i Lychrel numbers below 10000.\n" $ length $ filter isLychrel [1..9999]Phasma Felis wrote:rpenido wrote:Can you post a code example of what are you talking about ?
Let's see, I was recursing over a directory tree and doing something different with each entry depending on whether it was a file or a subdirectory. The inner block was something like this (Ruby):
- Code: Select all
if entry.file?
<<< do something >>>
elsif entry.directory?
<<< do something else >>>
end
We talked briefly about how "entry.directory?" was unnecessary, since if it wasn't a file it had to be a directory, so I started to change it to this:
- Code: Select all
if entry.file?
<<< do something >>>
else # entry is a directory
<<< do something else >>>
end
He quickly said that if I needed a comment I should leave it in the original form, because code that needs comments to explain it is bad code. In this case I don't mind leaving it that way, but I do like to explain strange bits of code and generally describe functional blocks in comments, so.
(Although perhaps I should break functional blocks down into actual functions more than I do, and just document the functions.)
Ben-oni wrote:I'd go with the former. Mostly because entry.file? and entry.directory? might not be exhaustive tests. What if you want to do something different on symlinks?
if choice1:
....
else:
assert choice2
....if (iterations % 100 == 0)
{
//Sleep for 1 minute after sending 100 emails
Thread.Sleep(60000);
}
if (iterations % 100 == 0)
{
//Because my helper class new connection to the SMTP server for every email sent
//and .NET didn't provide a Close/Disconnect/Dispose method for SmtpClient
//we need to sleep every minute so the GC can close the connections I open
Thread.Sleep(60000);
}
Thesh wrote:If I didn't have to ask around to find out the history, I would have just added the two lines of code to initialize an SmtpClient class and add the credentials, commented out his method and replaced it with SmtpClient.Send and the problem would have been solved much faster.
if (iterations % 100 == 0) GC.Collect();Sc4Freak wrote:That doesn't sound right... if a class holds onto some resources (unmanaged or otherwise) that need deterministic destruction, it should always implement IDisposable. It sounds like an oversight.
Phasma Felis wrote:Had a conversation with a coworker today who said that you should never leave a comment explaining what code does--the function should be clear from reading the code; if it's not, you need to rewrite, not comment.
if(window != NULL && window->callback != NULL)
{
long result = window->callback(w,x,y,z);
return result;
}if(window != NULL && window->callback != NULL)
return window->callback(w,x,y,z);if(noErr == ATSFontGetName(font, kATSOptionFlagsDefault, &fontName))
{
/* Do something */
CFRelease(fontName);
}background-color: #ffb300; /* orange */
lorb wrote:What about this? It's not exactly coding as my example is css but i could see the same happening in code.
- Code: Select all
background-color: #ffb300; /* orange */
background-color: #00b3ff; /* orange */
lorb wrote:What about this? It's not exactly coding as my example is css but i could see the same happening in code.
- Code: Select all
background-color: #ffb300; /* orange */
const Color _orange = #ffb300lorb wrote:What about this? It's not exactly coding as my example is css but i could see the same happening in code.
- Code: Select all
background-color: #ffb300; /* orange */
#include <stdio.h>
int main()
{ struct { unsigned a:3, b:3, c:2; } n = {0};
do do printf("%hhu\n", *&n);
while(!(n.a-- && !++n.b));
while(++n.c);
return 0; } Breakfast wrote:lorb wrote:What about this? It's not exactly coding as my example is css but i could see the same happening in code.
- Code: Select all
background-color: #ffb300; /* orange */
If your example appears in code you should do something like:
- Code: Select all
const Color _orange = #ffb300
This way, you can have many places that reference the _orange variable and if you ever wanted to change the color of _orange you would only need to make the change in one place and it would propagate to all of the references. This leads to the code being self-documenting.
weight / 1000.0weight / 1000.0, # Weight, converted from grams to kilogramsgram_to_kilogram_multiplier = 1.0 / 1000
weight * gram_to_kilogram_multiplier
for row in data:
yield tablib.Dataset(row).csv
yield tablib.Dataset(*data).csvMaelstrom. wrote:While you could guess thatis a unit conversion, guessing in code is bad. Clever variable naming could have helped, but I hold that
- Code: Select all
weight / 1000.0is clearer than
- Code: Select all
weight / 1000.0, # Weight, converted from grams to kilograms
- Code: Select all
gram_to_kilogram_multiplier = 1.0 / 1000
weight * gram_to_kilogram_multiplier
weight_kg = weight_g / 1000weight_kg = weight_g / g_per_kgUnits<int, grams> weight1 = whatever;
Units<int, kilo<grams>> weight2 = RoundUp(weight1);cjmcjmcjmcjm wrote:If it can't be done in an 80x24 terminal, it's not worth doing
Meem1029 wrote:Does such a thing actually exist in any language? That actually sounds really awesome and useful
Maelstrom. wrote:The Ordered product weight was in grams, but the CSV output needed to be in kilograms. Both fields were called 'weight'. While you could guess thatis a unit conversion, guessing in code is bad. Clever variable naming could have helped, but I hold that
- Code: Select all
weight / 1000.0is clearer than
- Code: Select all
weight / 1000.0, # Weight, converted from grams to kilograms
- Code: Select all
gram_to_kilogram_multiplier = 1.0 / 1000
weight * gram_to_kilogram_multiplier
const double GramsPerKilogram = 1000.0;
double weight_g = 1376;
double weight_kg = weight_g / GramsPerKilogram;
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.
Phasma Felis wrote:Had a conversation with a coworker today who said that you should never leave a comment explaining what code does--the function should be clear from reading the code; if it's not, you need to rewrite, not comment.
<SNIP>
Thoughts?
def gcd(a,b):
if b == 0:
return a
else:
return gcd(b, (a%b))def gcd(a,b):
# Calculate the GCD of two numbers
if b == 0:
#if b is 0, then return a.
return a
else:
#otherwise, recurse.
return gcd(b, (a%b))
def gcd(a,b):
# Calculate the Greatest Common Denominator of two numbers using the Euclidean Algorithm (see http://en.wikipedia.org/wiki/Euclidean_algorithm)
# a and b are Numbers from which to calculate the GCD. They are interchangable
if b == 0:
return a
else:
return gcd(b, (a%b))
Subroutine get_S(Sx,Sy,Sz)
Double Precision, intent(out) :: Sz,Sy,Sx
!Returns the "classical" Sx,Sy,Sz using the Pauli Spin Matrices
Sx=2d0*(Rup*Rdown+Iup*Idown)
Sy=2d0*(Rup*Idown-Iup*Rdown)
Sz=(Rup**2+Iup**2)*2d0-1d0
End Subroutine
Yea, I haven't seen anything quite that bad, though I have seen lots of comments with just a number for a bug in our tracker system. This is redundant because all our changesets are already marked with that number.sigsfried wrote:On the other hand I have seen some truly terrible commenting standards, for example my supervisors code has comments consisting purely of the date that line was changed.
TheAmazingRando wrote:If you find yourself commenting excessively then it's a sign of bad code, and there's definitely something to be said for making your code as clear and self-documenting (well structured with descriptive variable names) as possible, but I don't think that makes comments themselves a bad thing.
Comments can be great for other people who are learning the system you're using, though. For example, take the Windows API pattern where you call the same function twice: once with a null output parameter to get the size you need, and again after you've allocated the appropriate space. If you've done a lot of Windows programming you'll recognize it instantly, and it isn't too difficult to figure it out, but a single comment explaining it would be useful. Granted, the Windows API is designed horribly so this kind of supports the idea that comments are a sign of bad design, but if you're working in the industry it's pretty much a given that you're going to encounter bad design and you're going to have to work with it and around it. Comments aren't necessary, but they can save time.
TheAmazingRando wrote:If you find yourself commenting excessively then it's a sign of bad code, and there's definitely something to be said for making your code as clear and self-documenting (well structured with descriptive variable names) as possible, but I don't think that makes comments themselves a bad thing.
Comments can be great for other people who are learning the system you're using, though. For example, take the Windows API pattern where you call the same function twice: once with a null output parameter to get the size you need, and again after you've allocated the appropriate space. If you've done a lot of Windows programming you'll recognize it instantly, and it isn't too difficult to figure it out, but a single comment explaining it would be useful. Granted, the Windows API is designed horribly so this kind of supports the idea that comments are a sign of bad design, but if you're working in the industry it's pretty much a given that you're going to encounter bad design and you're going to have to work with it and around it. Comments aren't necessary, but they can save time.
// Call foo twice, once to get size, another to get the data
int size = Foo(NULL);
char *buffer = new char[size];
Foo(buffer);
char *GetTheFoo(int &size)
{
size = Foo(NULL);
char *buffer = new char[size];
Foo(buffer);
return buffer;
}
http://en.wikipedia.org/wiki/DSV_Alvin#Sinking wrote:Researchers found a cheese sandwich which exhibited no visible signs of decomposition, and was in fact eaten.
std::vector<char> GetTheFoo()
{
// Calling Foo with a null returns the size.
int size = Foo(nullptr);
std::vector<char> retval;
retval.resize(size);
int size2 = Foo( &retval.front() );
Assert(size == size2);
return std::move(retval);
}Users browsing this forum: No registered users and 6 guests