Please pardon my poor knowledge of design patterns.
Sometimes methods have many parameters and introducing a Parameter Object is the right way to refactor your code according to refactoring-guru article.
Imagine a situation when we have a service which handles some sort of documents.
public class FinancialStatementService : IFinancialStatementService
{
public void Print(Options input)
{
// creating basic document content and adding optional data below:
if (input.HasAccountNo)
{
// include account number
}
if (input.HasPaymentDetails)
{
// include payment details
}
if (input.HasZeroBalances)
{
// include zero balances
}
if (input.HasTotal)
{
// include total
}
// and then print the document
}
}
public class Options
{
public DateRange DateRange { get; set; }
public bool HasAccountNo { get; set; }
public bool HasPaymentDetails { get; set; }
public bool HasZeroBalances { get; set; }
public bool HasTotal { get; set; }
}
The document consists of many parts, some are optional. Sometimes we need the document to contain all possible details.
But imagine a case when a certain organization doesn't want some of the details.
Ideally I'd like to have a class which handles options creation and has methods containing organization name e.g.
public class OptionsCreator
{
// in tax office they want to see all possible details
public static Options GetTaxOfficeOptions(DateRange dateRange)
{
return new Options() { HasAccountNo = true, HasPaymentDetails = true, HasZeroBalances = true, HasTotal = true, DateRange = dateRange };
}
// in some other organization they DO NOT NEED zero balances & payment details
public static Options GetSomeOtherOgranizationOptions(DateRange dateRange)
{
return new Options() { HasAccountNo = true, HasPaymentDetails = false, HasZeroBalances = false, HasTotal = true, DateRange = dateRange };
}
}
But I'm afraid the above example is an anti-pattern.
Another thing I can think of is a Builder Pattern.
Would Builder Pattern be the most optimal solution for the Parameter Object?
IMHO, implementing a Factory is an overkill as it would involve implementing an interface for the Parameter Object.
Aucun commentaire:
Enregistrer un commentaire