C# Best Practices – How to Encapsulate ‘Global’ Variables

cprogramming practices

In C# what is the best practice for encapsulating variables I need to use in multiple methods? Is it OK to simply declare them at the top of my class above the two methods?

Also if I am using app settings from my config file should I use a getter? like this…

private string mySetting{ get { return WebConfigurationManager.AppSettings["mySetting"]; } }

What best practice is?

Best Answer

It's not just OK. According to the book Clean Code it's actually a very good practice, and Uncle Bob really encourages it. A variable used by many methods could show a high degree of cohesion between the methods . Moreover, a high degree of object variables could also hint that said class should be split in two so declaring them as object variables could help you find out hidden class candidates.

Object level variables aren't global variables, so don't be afraid to use them if they should be shared by various methods.

Related Topic