English |  Español |  Français |  Italiano |  Português |  Русский |  Shqip

Developing a Functional Programming Edge

Structural Patterns

The classification of structural patterns is a wide-ranging one. After all, structure is a vague term. You could just as well call these organizational patterns, as that is an equally ambiguous term. In short, these patterns deal with the relationships between various objects. As such this can be an area where there aren't as many direct analogues with functional programming concepts. However, we will see that many fundamental concepts of functional programming pop-up in these patterns. Let's start with the Facade Pattern.

Facade Pattern

The idea behind a facade is simple enough--it is to make things simpler. It's the kind of thing that any programmer steeped in object-oriented principles appreciates--making something complex seem a lot simpler. In the of the Facade Pattern this is accomplished by introducing a simpler interface that hides more complicated interfaces behind it.

Let's create a simple example of a Facade Pattern. Our example will retrieve what's trending on Twitter and retrieve the Google search results for those trending topics. This involves interfaces into both Twitter and Google, as well as the HTTP interface needed to communicate with Twitter and Google. Our facade will hide all of that and present it's users with the simplest of interfaces, a pair of no-parameter methods:

class TrendFacade {
    def getSearchResultsForTodaysTrends = {
        val results = new HashMap[String, List[SearchResult]]
        val twitter = new TwitterSearch
        val trends = twitter.dailyTrends
        val google = new GoogleSearch
        trends.foreach(t =>
            results(t._1) = google.search(t._2))
        results
    }

    def getSearchResultsForThisWeeksTrends = {
       val results = new HashMap[String, List[SearchResult]]
        val twitter = new TwitterSearch
        val trends = twitter.weeklyTrends
        val google = new GoogleSearch
        trends.foreach(t =>
            results(t._1) = google.search(t._2))
        results
    }
}

This listing shows the basic idea behind a facade. There are two more complex objects that it hides, the TwitterSearch and GoogleSearch classes. Its interface uses these other two interfaces, but it hides how they are used. The implementation shows [missing text].

There has been error in communication with Booktype server. Not sure right now where is the problem.

You should refresh this page.