go-mnd icon indicating copy to clipboard operation
go-mnd copied to clipboard

time duration not considered a magic number

Open bmayfi3ld opened this issue 5 years ago • 3 comments

Currently when you define a time duration with a number it is considered a magic number.

timeToWaitForTask := 30 * time.Second

I would think this qualifies as not being a magic number since it is clear what you are using the number for. It also reads better than the desired state which would be this.

timeInSecondsToWait := 30
timetoWaitForTask := timeInSecondsToWait * time.Second

bmayfi3ld avatar Oct 13 '20 16:10 bmayfi3ld

Setting this as a package level constant and using the constant as a reference should avoid the reports:

const (
    timeToWaitForTask = 30 * time.Second
)

I think the caveat with this specific case here is that while it is flagging the 30 * time.Second, the context of the variable assignment is more important for potential ignore consideration than the * time.Second. I work on a team that maintains a large codebase with lots of time durations and having those show as magic number reports is immensely useful to keep values consistent across files and packages. We use const declarations to avoid this particular type of assignment report.

bflad avatar Dec 14 '20 19:12 bflad

actually, I was wondering the same, I think not every project needs this, I believe it would make much more sense than to make this check as optional, and default to as what @supernova2468 suggested

gopherine avatar Feb 26 '21 16:02 gopherine

If defined as a const in a function it should also not report that as a magic number.

Otherwise this encourages people to increase the scope of a constant by moving it to the package level, where we should rather try to keep the scope as small as possible.


EDIT: it seems I was mistaken about a const being flagged. Ignore me 😅

tehsphinx avatar Jul 06 '22 07:07 tehsphinx

Hi there,

in general I share totally the same point that @bflad brought up. But on the other side I can also understand that, especially in smaller projects, time related findings looking weird because it's very common to write timeouts inline. So I tried the last 3 evenings to filter them out via a new flag "time-sensitive" yes/no.

But unfortunately it's harder than I thought in the beginning and I ended up with some partly very complex code that also shows some false-positives during my tests and even more bad with an operation checker who also jumps in for assignments.

So maybe it's me and the lack of time but I'll break up here to prevent some strange results in the future.

tommy-muehle avatar Oct 11 '22 20:10 tommy-muehle