Creation of anonymous vs. "named (?) objects"

2

I have a class that loga some information in the database I am using it as follows:

 new StudyLogRepository().Create(new StudyLog() {
  StudyId = Study.Id,
   CycleId = null,
   DateOccurrence = DateTime.Now,
   CycleActionName = "Nova estudo gerado",
   UserId = int.Parse(System.Web.HttpContext.Current.Session[SessionKeys.USER_ID].ToString())

 });

But in the same method I end up having to log in various information, so I end up having this code duplicated in several classes and methods making maintenance super complicated.

How can I solve this problem of duplicate code where the data to be logged in always comes directly from the class or method where this duplicate excerpt exists?

    
asked by anonymous 08.05.2017 / 19:06

1 answer

2

I do not know how your structure is but just create a static utility method in a class that makes sense to return it, something like this:

public static StudyLogRepository BuildStudyLog() => new StudyLogRepository().Create(new StudyLog() {
        StudyId = Study.Id,
        CycleId = null,
        DateOccurrence = DateTime.Now,
        CycleActionName = "Nova estudo gerado",
        UserId = int.Parse(System.Web.HttpContext.Current.Session[SessionKeys.USER_ID].ToString())
});

So I understand it will give an error if USER_ID goes wrong. Anything that comes in externally needs to be validated before use. It may even open up security holes.

The most commonly used mechanism for avoiding code duplication is always the function or method. You create it once and then just call to get the desired result. The function engine was created just for this.

If you knew any solution, you might have a better way to do it.

    
02.10.2017 / 14:19