Doing it elegantly

There are plenty of programming languages out there and they all allow endless possibility in how to write a piece of code.
Very often things can be done in two ways: the blunt way and the elegant way.

Consider for instance this piece of code:

    […]
    For Each SingleFeed As XElement In XMLDoc.Descendants(XName.Get(CurrentFeed.RootElement))
        Dim SyndFeed As SyndicationFeed = SyndicationFeed.Load(System.Xml.XmlReader.Create(SingleFeed.Descendants(XName.Get("feed")).Value.ToString))
        Dim TempItems As New List(Of SyndicationItem)

        If SyndFeed.Items.Count >= CurrentFeed.TotalElements Then
            TempItems.AddRange(SyndFeed.Items.ToList.GetRange(0, CurrentFeed.TotalElements))
        Else
            TempItems.AddRange(SyndFeed.Items.ToList)
        End If

        […]

        FeedItems.AddRange(TempItems)
    Next
    […]

It has to do with the creation of an object to store items from an ATOM feed.
The important point I want to show is the one about the If … else … End If cycle. What you are looking here is the first implementation of the code: it’s the easy way and, as i discovered later, the longest and stupidest way to write it.

Yes, it was stupid: the compact, most logical and briefly the elegant way to wrote it turned out to be:

        TempItems.AddRange(SyndFeed.Items.ToList.GetRange(0, Math.Min(CurrentFeed.TotalElements, SyndFeed.Items.Count)))

Probably any coding language nowadays includes some kind of Minimum function to return the smallest of two numbers.
Very often is just a matters of knowing what you are doing.

Advertisements