4

Why refactor the argument of List & lt; Term & gt; to IEnumerable &...

 3 years ago
source link: https://www.codesd.com/item/why-refactor-the-argument-of-list-term-to-ienumerable-term.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Why refactor the argument of List & lt; Term & gt; to IEnumerable & lt; Term & gt;

advertisements

I have a method that looks like this:

    public void UpdateTermInfo(List<Term> termInfoList)
    {
        foreach (Term termInfo in termInfoList)
        {
            UpdateTermInfo(termInfo);
        }
        m_xdoc.Save(FileName.FullName);
    }

Resharper advises me to change the method signature to IEnumerable<Term> instead of List<Term>. What is the benefit of doing this?


The other answers point out that by choosing a "larger" type you permit a broader set of callers to call you. Which is a good enough reason in itself to make this change. However, there are other reasons. I would recommend that you make this change because when I see a method that takes a list or an array, the first thing I think is "what if that method tries to change an item in my list/array?"

You want the contents of a bucket, but you are requiring not just the bucket but also the ability to change its contents. Why would you require that if you're not going to use that ability? When you say "this method cannot take any old sequence; it has to take a mutable list that is indexed by integers" I think that you're making that requirement on the caller because you're going to take advantage of that power.

If "I'm planning on messing up your data structure" is not what you intend to communicate to the caller of the method then don't communicate that. A method that takes a sequence communicates "The most I'm going to do is read from this sequence in order".


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK