I'm working in a C# codebase that was largely written by a former developer and this pattern is used extensively...
public class AuditInserter
{
public static void Insert(
DataContext dataContext,
Person person,
AuditableAction action)
{
return
new AuditInserter(
dataContext,
person)
.InsertAudit(action);
}
private AuditInserter(
DataContext dataContext,
Person person)
{
_dataContext = dataContext;
_person = person;
}
private readonly _dataContext;
private readonly _person;
private void InsertAudit(AuditableAction action)
{
_dataContext.AuditTable.Insert(_person, action);
}
}
// Consuming object
public class MainProgram
{
public static void Main()
{
AuditInserter.Insert(
new DataContext,
new Person,
new AuditableAction);
}
}
The constructor is private and construction of the object is handled by the static method. Note that this is not an example of the singleton pattern - the object does not hold a reference to a static instance of itself.
Is there any benefit of this design? It would be my natural inclination to design it like so:
public class AuditInserter
{
public AuditInserter(
DataContext dataContext,
Person person)
{
_dataContext = dataContext;
_person = person;
}
private readonly _dataContext;
private readonly _person;
public void Insert(
AuditableAction action)
{
return InsertAudit(action);
}
private void InsertAudit(AuditableAction action)
{
_dataContext.AuditTable.Insert(_person, action);
}
}
// Consuming object
public class MainProgram
{
public static void Main()
{
new AuditInserter(
new DataContext,
new Person)
.Insert(
new AuditableAction);
}
}
I'm loathe to just blindly follow this existing pattern without understanding what benefits it offers (if any).
The code is in C# but this issue is not C#-specific.
AuditInserter
? That looks like a rather roundabout way of writingdataContext.AuditTable.Insert(person, action);
– Caleth Jun 13 '18 at 10:35return
invoid Insert(AuditableAction action)
– Bill Tür Jun 14 '18 at 9:37