4

QuantConnect Lean | How Not To Code

 3 years ago
source link: https://hownot2code.com/2021/01/12/quantconnect-lean/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How Not To Code

C, C++, C#, Java bad practices: learn how to make a good code by bad example

Skip to content

Expression is always true

public virtual DateTime NextDate(....)
{
  ....
  // both are valid dates, so chose one randomly
  if (   IsWithinRange(nextDayOfWeek, minDateTime, maxDateTime) 
      && IsWithinRange(previousDayOfWeek, minDateTime, maxDateTime))
  {
    return _random.Next(0, 1) == 0  
           ? previousDayOfWeek
           : nextDayOfWeek;
  }
  ....
}

V3022 Expression ‘_random.Next(0, 1) == 0’ is always true. RandomValueGenerator.cs 142

The bottom line was that either one or the other value was selected with a 50% probability. However, in this case, the Next method will always return 0.

This happens because the second argument is not included in the range of values. That is, the value that the method can return will be in the range [0,1). Let’s fix that:

public virtual DateTime NextDate(....)
{
  ....
  // both are valid dates, so chose one randomly
  if (   IsWithinRange(nextDayOfWeek, minDateTime, maxDateTime) 
      && IsWithinRange(previousDayOfWeek, minDateTime, maxDateTime))
  {
    return _random.Next(0, 2) == 0
           ? previousDayOfWeek
           : nextDayOfWeek;
  }
  ....
}

Please click here to see more bugs from this project.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK