Creation of anonymous objects vs "named (?)"

Asked

Viewed 112 times

2

I have a class that loga some information in the database I am using it in the following way:

 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 my duplicate code problem being that the data to be logged always comes directly from the class or method where there is this duplicate snippet?

1 answer

2


I don’t know how this structure of yours but just create a static utility method in a class that makes sense to return it, something like that:

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())
});

I put in the Github for future reference.

From what I understand will be wrong if the USER_ID wrong. Anything that comes externally needs to be validated before use. It may even open security holes.

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

If I knew every solution I might have a better way to do this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.