views:

78

answers:

1

I have the following methods:

protected static void updateExistingSection(XmlDocument doc,
    XmlNode rootNode, string sectionTag, CreateSection createSection,
    Func<XmlNode[]> createChildNodes, Action<XmlNode> firstSection)
{
    IEnumerable<XmlNode> sections =
        getChildNodesByName(rootNode, sectionTag);
    if (sections.Count() < 1)
    {
        rootNode.AppendChild(createSection(doc, createChildNodes()));
        return;
    }
    removeSubsequentNodes(sections, rootNode, firstSection);
}

private static void updateExistingCredentialsSection(XmlDocument doc,
    XmlNode rootNode, string newUser, string newPassword, string newHost)
{
    updateExistingSection(doc, rootNode, CREDENTIALS_SECTION_TAG,
        createCredentialsSection,
        () => new[] {
            createNode(USER_TAG, doc, newUser),
            createNode(PASSWORD_TAG, doc, newPassword),
            createNode(HOST_TAG, doc, newHost)
        },
        credentialsNode =>
        {
            updateExistingLeafNode(USER_TAG, doc, credentialsNode, newUser);
            updateExistingLeafNode(PASSWORD_TAG, doc, credentialsNode,
                newPassword);
            updateExistingLeafNode(HOST_TAG, doc, credentialsNode, newHost);
        });
}

My question concerns the fifth parameter passed in updateExistingCredentialsSection to updateExistingSection, the () => new[] { createNode(USER_TAG, doc, newUser), ... } one. It was my understanding that those createNode calls will not occur unless that lambda expression is called in updateExistingSection, right? Likewise for the updateExistingLeafNode calls in the last parameter given to updateExistingSection.

Also, from a design perspective, does either method look ridiculous? Do you see a way I could make either method smaller, or require fewer parameters? I've been trying to DRY things out, which is what led to writing updateExistingSection in the first place, since I had several methods doing the same functionality.

+4  A: 

Correct. Think of the lambdas as methods. You can define them anywhere (legally allowed), but the code within them is not run until explicitly invoked.

In fact, the code for some lambdas might never be be run in a given execution path if there is branching logic in the function you pass them to.

Andrew Anderson