How to hide logic behind a class to improve readability of method and refactor class to follow SRP?

谁都会走 提交于 2019-11-29 09:36:50

Trying to understand your question

You have an entity... when the entity changes, you want to create a change-version for your entity. What is not clear to me is that why this change needs to be tracked against both variant and category?

Let's assume your entity is car and the categories for that entity are: Toyota, BMW and Nissan. Now your entity, let's say "Toyota Corona with id = 123" is changed. Why do you need to track the change against the category? Can't you just say that entity with id = 123 has changed?

Violation of SRP

As I mentioned in the comment, since you have left out part of your logic, it's hard to understand if your code if violating SRP or not, but I can give you some general suggestions:

You have a class called AggregateCalculator, I assume the main responsibility of this class is to calculate aggregation which happens in Transform() method. Now you require to execute 2 steps inside Transform(). This is not necessarily a violation of SRP... because from a higher level, your aggregate calculator does one thing: calculate aggregation.

You can look for general signs of SRP violation:

  1. According to Nikola Malovic's 2nd law of IoC:

    Any class having more than 3 dependencies should be questioned for SRP violation

  2. If the size of your class is too big, then you need to question it for SRP violation.

Violation of DRY

Both of your classes: AggregateCalculator and AdditionCalculator do their calculation in 2 steps, step-1 and step-2... and you have a common method: DeleteStep1Data() in both classes to delete step-1 if step-2 fails... I assume the implementation of DeleteStep1Data() is different for each of these classes, but I feel it still contains duplicated code (not DRY). One may argue that this violates SRP too, because AggregateCalculator is responsible for both: Calculating Aggregation and "Mirroring a DB Transaction" (this is hard to tell without seeing your complete code).

It appears that both step-1 and step-2 are DB transactions, so a different approach would be to put both steps inside a single DB transaction... for example you can write a stored procedure like this:

CREATE PROCEDURE AggregateCalculationSP
AS
BEGIN
    BEGIN TRANSACTION t1
        BEGIN TRY
            -- do step 1
            -- do step 2
        END TRY
        BEGIN CATCH
            ROLLBACK TRANSACTION t1
        END CATCH
    COMMIT TRANSATION t1
END

Now you can take out DeleteStep1Data() from your class.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!