How should I split large and bloated classes into smaller ones?

匆匆过客 提交于 2019-12-03 09:42:33

You really shouldn't put all data access into one class unless it's generic. I would start by splitting out your data access classes into one manager per object or related groups of objects, i.e. CompanyManager, CustomerManager, etc. If your need to access the manager through one "god class" you could have an instance of each manager available in your one true Manager class.

Your FooBarManager looks a lot like a God Object anti pattern.

In a situation like yours, consider delving into Patterns of Enterprise Application Architecture, by Martin Fowler. At first sight, it looks like you want to create a Data Mapper. But consider alternatives like Active Records, that might be enough for your needs.

Also consider using an ORM library/software for your platform. Building your own without a good reason will only confront you to the many problems that have already been more or less solved by these tools.

       / FooManager
Manager                  (derive from Manager)
       \ BarManager

Should be self-explaining

I'd suggest using composition. Think about the functions the manager is doing. Split them along the lines of single responsibility. It appears most of FooBarManager is a collection of Foo and bar entities. So, at a minimum, break out the collection logic from FooBarManager

public class EntityCollection<T> : IList<T> 
 where T : BaseEntity
{ /* all management logic here */}
public class FooCollection : EntityCollection<foo> {}
public class BarCollection : EntityCollection<bar> {}
public class FooBarManager 
{ 
public FooCollection { /*...*/ } 
public BarCollection { /*...*/ } 
public FooBarManager() : this(new FooCollection(), new BarCollection()){}
public FooBarManager(FooCollection fc, BarCollection bc) { /*...*/ } 
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!