Is there a data structure or design pattern or code structure to avoid multiple if statements?

84 views Asked by At

I have a web[forms] app that uses a reportviewer. In the code behind, I have code that looks like this:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    If Not Page.IsPostBack Then

        Dim u As New UriTypeConverter

        Dim vSDate, vEDate As Date
        vSDate = Session("StartDate")
        vEDate = Session("EndDate")

        If Session("ReportName") = "Report1" Then
            Dim reportparameters(1) As ReportParameter
            reportparameters(0) = New ReportParameter("StartDate", vSDate)
            reportparameters(1) = New ReportParameter("EndDate", vEDate)
            ReportViewer1.ServerReport.ReportPath = "/SSRS01/Report1"
            ReportViewer1.ServerReport.SetParameters(reportparameters)
        End If

        If Session("ReportName") = "Report2" Then
            Dim reportparameters(1) As ReportParameter
            reportparameters(0) = New ReportParameter("StartDate", vSDate)
            reportparameters(1) = New ReportParameter("EndDate", vEDate)
            reportparameters(2) = New ReportParameter("Product", Session("ProductName"))
            ReportViewer1.ServerReport.ReportPath = "/SSRS01/Report2"
            ReportViewer1.ServerReport.SetParameters(reportparameters)
        End If

And there are about 12 if statements, some having different number of parameters than others. So as opposed to having to write more if statements with varying parameters. I wonder if there's a structure, technique, pattern that would allow me get around writing if statements for every new report I create. And I don't care what's needed. Database, new library, learn 5 new GoF patterns. Whatever. Only requirement/restriction is that this is [obviously] a .NET app.

1

There are 1 answers

0
Yuri On

Your best bet is to replace multiple If or long switch statements with a Strategy Pattern. Good explanation on how to can be found here

another good example you will find in this discussion on stackoverflow - it is on Java, but logic is very clear and can be ported in any .Net language Converting many 'if else' statements to a cleaner approach