diktat icon indicating copy to clipboard operation
diktat copied to clipboard

`MAGIC_NUMBER` false positive when `Long` constants are used together with `kotlin.time.Duration` extensions

Open 0x6675636b796f75676974687562 opened this issue 1 year ago • 5 comments

Describe the bug

The following constant declarations trigger the MAGIC_NUMBER false positive:

import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds

val fooTimeout = 10L.seconds

val barTimeout = 10L.minutes

Environment information

  • diktat version: 2.0.0
  • build tool: Maven
  • how is diktat run: plugin
  • kotlin version: 1.7.22
  • operating system: Any

How would you solve this? Just check for .seconds, .minutes and .hours from the nodeText?

rubenquadros avatar Oct 07 '24 19:10 rubenquadros

How would you solve this? Just check for .seconds, .minutes and .hours from the nodeText?

Yes, need to check that the syntax of the constant is the following:

val a = (some constant).(any method) . And if the expression really fits this pattern, then not to raise a warning in the code of diktat.

This is a really easy fix

orchestr7 avatar Oct 09 '24 05:10 orchestr7

@orchestr7 Do you know, that range will also be treated as magic number in same conditions?

import kotlin.time.Duration.Companion.seconds

val something1 = 1L.seconds // Not a magic number
val something10 = 10.seconds // Magic number
val something10long = 10L.seconds // Magic number
val someRange = 4..11 // Magic number

Can't figure out yet, I'm not familiar with this project, but looks like this test should fail, but it passes: com.saveourtool.diktat.ruleset.chapter3.MagicNumberRuleWarnTest#check ignore ranges

wolf-revo avatar Dec 26 '24 11:12 wolf-revo

@orchestr7 @0x6675636b796f75676974687562 Kind reminder. Do you think that behavior when range is also treated as magic number at the same conditions is correct?

wolf-revo avatar Jan 18 '25 12:01 wolf-revo

@orchestr7 @0x6675636b796f75676974687562 Kind reminder. Do you think that behavior when range is also treated as magic number at the same conditions is correct?

Actually I think so, yes, but may be it can be configured by the config flag

orchestr7 avatar Mar 29 '25 16:03 orchestr7