HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Suggest how to extract method

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
suggestmethodextracthow

Problem

I have 3 methods( BindingSource are bindingsources, context is data context, cache -are some List for cache operations):

```
private void AddUpdateRowDocuments()
{
try
{
tRANSMITDOCDOCUMENTSRELATIONSBindingSource.EndEdit();
var t = tRANSMITDOCDOCUMENTSRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_DOCUMENTS_RELATIONS;
if (t.TRANSMIT_DOC_ID == 0)
{
if (!cachetddrList.Contains(t))
{
cachetddrList.Add(t);
}
return;
}
context.UpdateObject(t);
}
catch (Exception ex)
{
logger.ErrorException(string.Empty, ex);
}
}
private void AddUpdateRowOrganizations()
{
try
{
tRANSMITDOCORGANIZATIONRELATIONSBindingSource.EndEdit();
var t = tRANSMITDOCORGANIZATIONRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_ORGANIZATION_RELATIONS;
if (t.TRANSMIT_DOC_ID == 0)
{
if (!cachetdorList.Contains(t))
{
cachetdorList.Add(t);
}
return;
}
context.UpdateObject(t);
}
catch (Exception ex)
{
logger.ErrorException(string.Empty, ex);
}
}
private void AddUpdateRowPartators()
{
try
{
tRANSMITDOCPARTATORRELATIONSBindingSource.EndEdit();
var t = tRANSMITDOCPARTATORRELATIONSBindingSource.Current as WcfDataServiceReference.TRANSMIT_DOC_PARTATOR_RELATIONS;
if (t.TRANSMIT_DOC_ID == 0)
{
if (!cachetdprList.Contains(t))
{
cachetdprList.Add(t);
}
ret

Solution

Something along the lines of this. Generics aren't that difficult. Just replace every occurance of 'some desired type' with the generic identifier.

private void AddUpdateRow(BindingSource bindingSource, List cachedList)
    where T : ITransmitDocId
{
    try
    {
        bindingSource.EndEdit();
        T t = bindingSource.Current as T;
        if (t.TRANSMIT_DOC_ID == 0)
        {
            if (!cachedList.Contains(t))
            {
                cachedList.Add(t);
            }
            return;
        }
        context.UpdateObject(t);
    }
    catch (Exception ex)
    {
        logger.ErrorException(string.Empty, ex);
    }
}


The where constraint in the function definition should indicate a common interface/class in which TRANSMIT_DOC_ID is defined.

Code Snippets

private void AddUpdateRow<T>(BindingSource bindingSource, List<T> cachedList)
    where T : ITransmitDocId
{
    try
    {
        bindingSource.EndEdit();
        T t = bindingSource.Current as T;
        if (t.TRANSMIT_DOC_ID == 0)
        {
            if (!cachedList.Contains(t))
            {
                cachedList.Add(t);
            }
            return;
        }
        context.UpdateObject(t);
    }
    catch (Exception ex)
    {
        logger.ErrorException(string.Empty, ex);
    }
}

Context

StackExchange Code Review Q#1089, answer score: 4

Revisions (0)

No revisions yet.