söndag 26 november 2017

Refactoring: Replace Magic Number with Symbolic Constant example i C#

Part three in my series of refactors I've used the most from the book Refactoring - Improving the design of existing code.

Replace Magic Number with Symbolic Constant

You have a literal number with a particular meaning.
Create a constant, name it after the meaning, and replace the number with it.

Example 1

The code before

1:  double PotentialEnergy(double mass, double height)  
2:  {  
3:    return mass * 9.81 * height;  
4:  }  

The code after

1:  private const double GravitationalConstant = 9.81;  
2:    
3:  double PotentialEnergy(double mass, double height)  
4:  {  
5:    return mass * GravitationalConstant * height;  
6:  }  

Example 2

I thought I would find a better example, but it wasn't that easy, so I settled with just another example. The example below is from the page https://www.eliotsykes.com/magic-numbers, but I think the real world examples in the bottom of that page might give you a better understanding of how you can use constants.

The code before

1:  public bool AllowedToComment()  
2:  {  
3:    return _age >= 13 && CommentsInLastHour.Count < 20;  
4:  }  

The code after

1:  const int CommenterMinAge = 13;  
2:  const int MaxCommentsPerHour = 20;  
3:    
4:  public bool AllowedToComment()  
5:  {  
6:    return _age >= CommenterMinAge && CommentsInLastHour.Count < MaxCommentsPerHour;  
7:  }  

Motivation

Magic numbers are one of the oldest ills in computing. They are numbers with special values that usually are not obvious. Magic numbers are really nasty when you need to reference the same logical number in more than one place. If the numbers might ever change, making the change is a nightmare. Even if you don't make a change, you have the difficulty of figuring out what is going on.

The source code



Inga kommentarer:

Skicka en kommentar