I have an algorithm to create a version for an entity and then I save that version against below 2 entity:
1) Variant
2) Category
interface IEntityVersion
{
string GetVersion();
}
public class EntityVersion : IEntityVersion
{
public string GetVersion()
{
return null;
}
}
public interface IVariant
{
void Process(Variant model, string connectionString);
}
public abstract class BaseVariant : IVariant
{
private readonly IEntityVersion _entityVersion = new EntityVersion();
public void Process(Variant model, string connectionString)
{
try
{
Transform();
string variantVersion = _entityVersion.GetVersion();
using (var myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
using (var transaction = myConnection.BeginTransaction())
{
try
{
VariantRepo.UpdateVariantVersion(
myConnection,
transaction, model.VariantId, variantVersion);
CategoryRepo.UpdateCategoryVariantMapping(
myConnection,
transaction, model.CategoryId, variantVersion);
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
DeleteStep1Data();
}
}
}
}
catch (Exception)
{
//log error
}
}
protected abstract void DeleteStep1Data();
protected abstract void Transform();
}
public class Variant
{
public int VariantId { get; set; }
public int CategoryId { get; set; }
}
public class VariantRepo
{
public static void UpdateVariantVersion(SqlConnection sqlConnection,
SqlTransaction transaction, int variantId, string version)
{
//save logic here
}
}
public class CategoryRepo
{
public static void UpdateCategoryVariantMapping(SqlConnection sqlConnection,
SqlTransaction transaction, int categoryId, string version)
{
//save logic here
}
}
I have 2 derived types(AggregateCalculator
and AdditionCalculator
) each having their own implementation of Transform
and DeleteStep1Data
methods.
public class AggregateCalculator : BaseVariant
{
protected override void DeleteStep1Data() // Is it violating SRP ?
{
throw new NotImplementedException();
}
protected override void Transform()
{
throw new NotImplementedException();
}
}
public class AdditionCalculator : BaseVariant
{
protected override void DeleteStep1Data()// Is it violating SRP ?
{
throw new NotImplementedException();
}
protected override void Transform()
{
throw new NotImplementedException();
}
}
I feel like the Process
method is doing too much work and if it would be possible to hide version saving related logic behind the EntityVersion
class so that the Process
method looks simple.
Step1
and Step2
are in sync so that if there is an error in Step2
, I call the DeleteStep1Data
method to delete all the data saved in Step1
.
Also I feel like my 2 derived classes AggregateCalculator
and AdditionCalculator
are handling more than 1 responsibility, i.e. running a transformation and also deleting the data stored during the transformation process, although I am not sure if this is true or not.
Is there a possibility to refactor above code to improve readability and handle SRP ?