Refactoring to separate business logic from code b

2019-07-24 14:27发布

问题:

I've inherited a asp.net project and I'm finding that the code behind pages contain a lot of business logic.

I've decided that in most cases it's better to leave the working code in place than try and do a massive refactoring. However there are pages that perform functionality that could be re-used in command line utilities for batch processing. I'd like to focus my energies on these pages, refactoring out the business logic and referencing that in other utilities.

I am currently looking to refactor this particular page which has 6200 lines of code in the code behind. What I'm finding is it's very tedious work trying to locate the dependencies between the code behind and the page specific objects.

I'm wondering if anybody knows of a tool, a VS feature, or a method that would allow me to systematically locate and attack these dependencies? Something that will allow me to identify any area of the code that references ViewState, a textbox, panel, drop downlist, etc..., so I can move these references to method parameters and ultimately move this functionality out of the page class.

回答1:

I would begin by examining any method that doesn't follow the Single Responsibility Principle and break them down so that they do. Once that's done you should have a handle on what the code does and you should be able to group the code more easily and move it into dedicated classes for those groups creating the necessary objects to use as you go. I find ReSharper is a very useful tool to help do all this. Ultimately you will always need to have a solid grasp of the fundamentals within the code before you can successfully refactor.

We've all been there at some point and you have my deepest sympathy but your willingness to attempt it at all means you're already heading in the right direction. Good Luck!



回答2:

Wow first of all sorry to here that. Anyone who would put 6000 lines of code in code behind deserve to be smacked :)

Now I have done this kind of refactoring before. I would approach this in few steps:

(1) Create Logical Regions #Region and #EndRegion Like - Save Methods , Load Methods or (2) See if you can create physical business objects based on these regions in your business layer (3) Once you are done just refer all your code to appropriate class.

I understand you want some tool to make this all go away but I am afraid by doing this you will dig the hole dipper. Understanding the code and moving it method by method will give you better understanding.



回答3:

One way I can immediately think is Compile then into Assemblies and Analyze the assembly using NDepend

http://www.ndepend.com/Features.aspx#DependencyCycle


(source: ndepend.com)