'How to apply seperation in one service for multiple tasks?
I have a service method that does so many things.
public Result DoSomething(){
var queryResult = service.GetResult();
SaveResultToRedis(queryResult);
logger.Log($"this data saved in redis successfully {queryResult.Id}");
AddSomethingToKafka(queryResult);
logger.Log($"this data saved in kafka successfully {queryResult.Id}");
logger.Log($"this data response is success {queryResult.Id}");
}
In this stuation,
- if redis or kafka fails, the request response will fail.
- if logger service fails, the request response will fail.
- if I put all logics in try catch blocks, code will appear so bad.
Which way may apply in this stuations? Is there any design pattern approaches or else?
Solution 1:[1]
If you want to try to make your method thinner, then try to apply SOLID rules.
If DoSomething()
method just saves data to some database or event system, then we can separate them by database or event systems. However, code example just saves in two places and it would not be great choice separate by storage.
As an alterantive, it is possible to hide logger.log
methods by creating a private helper method and call it from DoSomething()
:
private void ExecuteAndLog(Action action, logger, string message)
{
action();
logger.log(message);
}
and the full code looks like this:
public void SaveToKafka(string str)
{
}
public void SaveToRedis(string str)
{
}
public void DoSomething()
{
try
{
string s1 = "s1";
ExecuteAndLog(() => SaveToKafka(s1), logger, "someMessage");
ExecuteAndLog(() => SaveToRedis(s1), logger, "someMessage");
logger.log("this data response is success");
}
catch (Exception)
{
throw;
}
}
private void ExecuteAndLog(Action action, logger, string message)
{
action();
logger.log(message);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | StepUp |