简体   繁体   中英

C# - Misusing static variables

I have a class like below (refactored for purpose) in a PR and one of the seniors who is now on holiday stated I was misusing static variables and I should pass variables from method to method.

class Class {
  static int dataPool;
  
  // the below methods are called cyclicly for the duration of the application, 
  // xxxx times, First method is called and then Second is called, 
  // over and over
  public static void First()
  {
    // at the start, reads dataPool count to do computation
    // at the end, set dataPool count based on computation
  }

  public static void Second()
  {
    // at the start, read dataPool count to do some computation
    // at the end, set dataPool count based on computation
  }
}

I want to understand why using variables like the above is 'bad' to learn. Can anyone explain please?

I want to understand why using variables like the above is 'bad' to learn. Can anyone explain please?

Main reasons:

  • It means your code is no-longer re-entrant.
  • It means your code is no-longer thread-safe (or even less thread-safe) and cannot run concurrently.
  • It means your code has state in unexpected places (see: Principle of Least Astonishment ).
  • It means your code will perform poorly in a multi-threaded system (even if it's strictly single-threaded and without reentrancy) as having mutable static-state means your compiler cannot optimize your program's use of memory because it cannot guarantee thread ownership of data. Cache coherency is expensive .
  • It means you cannot correctly unit-test your code (using the strict definition of "unit test", not Visual Studio's).
  • It means the JIT compiler cannot optimize your program as much as it could if it could otherwise because reasoning about the lifetime of static state is very difficult.
  • It means your code could be broken if another function or thread decides to mutate your static state without you knowing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM