开发者

How to organise field initialization to reduce maintenance overhead?

开发者 https://www.devze.com 2023-04-03 10:24 出处:网络
I have inherited a class that initializes many private fields - some are initialized in the constructor (see dContext), and some are via field-initializers (see random).

I have inherited a class that initializes many private fields - some are initialized in the constructor (see dContext), and some are via field-initializers (see random).

public partial class Report_Aux
{
    public Report_Aux()
    {
        logger = Log.Instance;
        dContext = new DataContext(ConfigurationManager.AppSettings["DataContextConnectionString"]);
        created = Util.GetDate("constructor");
        ...
    }

    Log logger;
    DataContext dContext;
    Random random = new Random();
    DateTime created;        
    ...
}

This is confusing; what is best way to refactor this 开发者_开发技巧to reduce the maintenance overhead of too many fields and initializations?


Your class has many dependencies, or things that it needs in order to be able to do its job. Its job doesn't need to include creating such dependencies. You could create a constructor that advertises what those dependencies are and the creator of the class is responsible for seeing that the class has all the tools it needs in order to work. (Another code approach is to have those dependencies exposed simply as properties.) The question then becomes "Who supplies those dependencies? Who knows how to build this class?"

You might consider a factory approach. Whereas the job of your class is to execute whatever logic using the tools at its disposal, the job of the factory is to build the class and supply the tools. That's its single responsibility.

class ReportAuxFactory 
{
     public Report_Aux Create()
     {
          // create dependencies? 
          // instantiate class, provide dependencies 
          return theInstance;
     }
}

If you combine this with appropriate abstractions of those dependencies, you'll find that you can compose your class with different implementations that conform to a shared interface but provide different functionality. This could make your class open to extension without having to be modified. For example, perhaps it needs to deal with a different data source or logger. It can also make the class easier to test.

0

精彩评论

暂无评论...
验证码 换一张
取 消