Home How can I modularize this C# code?
Reply: 1

How can I modularize this C# code?

Gary Huckabone
1#
Gary Huckabone Published in 2017-12-06 21:18:23Z

I've been working with .NET table adapters and data tables and I've been wrestling with how to modularize this code but I just can't "see" it. Here's what I have but there's gotta be a way to combine into a one-liner that handles both cases.

  class What_I_have
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }

This is an idea of what I'm trying to do (The type 'HowToTypeThis' presents my quandary):

  class What_Id_like
  {
    public void TableAdapterFiller(TSNKF30_STRUCT_ELMNTTableAdapter TableAdapter,
      dsGrids.TSNKF30_STRUCT_ELMNTDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }
    public void TableAdapterFiller(TSNKF52_CGFM_USERSTableAdapter TableAdapter,
      dsGrids.TSNKF52_CGFM_USERSDataTable DataTable)
    {
      IsolatedMethod(TableAdapter, DataTable);
    }

    void IsolatedMethod(HowToTypeThis tabAdapter,
      HowToTypeThis DataTable)
    { 
      try
      {
        TableAdapter.Fill(DataTable);
      }
      catch (SystemException sex)
      {
        GenericExcHandler(sex, DataTable.TableName);
      }
    }

  }
Erik Philips
2#
Erik Philips Reply to 2017-12-06 21:24:03Z

Add interfaces:

public interface ITableAdapter 
{ 
  Fill(IdataTable dt);
}
public interface IDataTable { }

Update your classes

public class TSNKF30_STRUCT_ELMNTTableAdapter : ITableAdapter {}
public class TSNKF30_STRUCT_ELMNTDataTable  : IDataTable {}

Write an extension method

public static class TableAdapterExtensions
{
  public static void FillWith(this ITableAdapter adapter, IDataTable dataTable)
  {
    try
    {
      adapter.Fill(dataTable);
    }
    catch(SystemException sex)
    {
      GenericExcHandler(sex, DataTable.TableName);
    }
  }
}

Then usage:

var ta = new TSNKF30_STRUCT_ELMNTTableAdapter();
var dt = new dsGrids.TSNKF30_STRUCT_ELMNTDataTable();
ta.FillWith(dt);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.298746 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO