Показаны сообщения с ярлыком code. Показать все сообщения
Показаны сообщения с ярлыком code. Показать все сообщения

понедельник, 29 мая 2017 г.

(= (+ clojure emacs) :happiness)

I started programming in Clojure quite long ago and despite all the great advice spread through the Internet kept using Sublime Text editor for it (it's an awesome thing, anyway). However some months ago I stumbled upon Emacs - maybe after talking to some Haskell-ists. Yes, it felt totally unfamiliar and awkward and I had to spend minutes trying to accomplish the simplest things that took me an instant to do in other editors. Still, I can't explain why, it felt quite likeable and more suitable for doing Clojure. The funny part though is that I'm only starting to learn the full power of Emacs as a Clojure programming environment. Literally, it took me almost half a year to get accustomed with the editor and its addons - mostly Cider - to understand how much one can do there.

Even though there are guides on the web explaining what a Clojurist can do in Emacs (for example here and here), I feel the need to list the basic tricks that I have learnt here. For some it may soften the learning curve, others will possibly provide some greate advice to me. And it will certainly help me if I somehow got struck by amnesia in these dangerous times.

First things first. Once I run Emacs to do some Clojure or ClojureScript I make sure to press C-c M-j or C-c M-J (for cljs) to launch a REPL and have it ready. Most of the cider's awesome stuff won't work without that, but it is also simply stupid to do Clojure without having a hot REPL nearby.

At first I used to copy and paste lines from code buffers to REPL and run them there, when I wanted to check whether something would work. Quite recently I discovered that this is stupid as well. One can simply place a cursor at the end of an expression and type C-c C-e - cider will evaluate the expression and show the result right next to it!

I had some problems with that though, because once I wanted to copy the result of that expression elsewhere and couldn't figure out a way to do that. Fortunately, one can get pretty close: C-c C-p will also evaluate the last expression, but the pretty-printed result will appear in a special buffer. Afterwards you can go to that buffer, skim through it and copy the required bits.

The last time I used that trick my goal was to select some values from the database (yes, with Clojure, because with Emacs it's closer that any other gateway to the DB) and use them as parameters to test my web-service. I made calls to that service through a plugin for Google Chrome (yes, not familiar with curl), but I should definitely change that to running requests right from Emacs itself - that should be pretty easy. Frankly speaking, I don't know any other development environment that allows to make a couple calls and check whether a webservice that you're hacking together yields the expected results without even leaving the window (correction: buffer) in which you write the service's code.

The last big thing on my list are tests. I used to run tests through the terminal, like lein test. Yes, that means spinning up a JVM, which is 15+ seconds at best. Try to imagine my feelings when I first discovered that I can run all tests in a namespace simply by pressing C-c C-t C-n, while there. Even better, I can run the tests that I have for one of my modules (i.e. namespaces) without leaving the buffer of that namespace - with those same keys. This one, however, requires that the namespace with tests is called <the thing that you're testing>-test - it took me some time to learn and get accustomed to, but that's not a big deal. Also, while the cursor is on a particular test case I can run it with C-c C-t C-t. Then change it and run again in an instant. As a C# programmer I love Visual Studio, but unit tests experience there is by no means close to what you see in Emacs with Cider.

Sometimes I would also type C-c C-x just to see that my code still compiles - that's cider refresh, which reloads everything.

And one more thing, that makes cider-ed Emacs a true development environment is the M-. hotkey, that navigates you to the definition of whatever you're looking at. It does have glitches from time to time, but it's there.

There's a ton of other greatness in Cider, I'm sure. Many bits are easy to find and learn through the hotkeys reference C-h C-m - I simply didn't internalize most of it yet. For example, there are keys and commands for macro expansion and multiple other things. Still, even with the few tricks that I mentioned above I get programming experience that simply seems out of reach for the other languages and environments that I worked with. If you do Clojure and your environment of choice doesn't give you the same capabilities, you should definitely check out Emacs!

четверг, 16 февраля 2017 г.

Search Algortihms in the Real World

In the middle of my university life I had a very strong desire to build a computer game. I was studying for a software engineer and still understood little about most of the software applications. At the same time I loved PC games, which clearly brought me to the idea that I should produce one - the one with the best gameplay, of course. Many of the guys with the same background had that wish and like most of them I didn't succeed.

I spent a fair portion of my free time thinking over the game's design, writing the explanations in a textbook and studying computer graphics. The problem is that in these activities I focused on the things that were easier to comprehend for me. I liked to think through game mechanics - for example the way damage is dealt to the player. I worked this question out on a very detailed level - in many cases descending to the names of C++ classes and of course laying out the calculation rules. With graphics, I focused on trying to make primitives move around the screen using OpenGL, because moving stuff looked like an essential part of game development. This all happened where neither setting, nor even key game features were defined - I hardly settled with the genre. Instead of looking at these high-level concepts of the game, I grasped the details, which I could easily stick into my head, without even understanding what are the key building blocks that I will have to construct a video game from. Speaking in algorithms language, I was doing a depth-first search not wishing too see the entire tree that I will have to traverse eventually.

Recent observations at interviews and during the normal work process brought me to the idea that such a mistake is common among many younger developers. When put in front of an unfamiliar problem they tend to catch some detail that they understand and pursue it to the deep. Because they don't take time to step back and take a look at the problem as a whole, they may end up with weak solutions suffering from various illnesses that happen in the software world. Most likely you will see multiple leaky abstractions and dozens of lines of ad-hoc code in the programs produced this way. And of course don't be too optimistic about finding there clearly separated layers, constituted of the objects that comply with Single-Responsibility Principle.

After acquiring reasonable development experience we tend to replace the depth-first strategy with the breadth-first search. This happens not only because older developers are slower beasts, but more due to the acknowledgement of importance of the full context for the correct solution to the problem. The mistakes committed earlier make us approach both high- and low-level decisions with great respect to the surroundings and see the drawbacks of diving into details before thinking of the solution as a whole.

This obviously makes a lot of sense when we speak of software design and architecture definition, but actually the same breadth-first strategy is applicable to such activities as coding and bugfixing. For example, when analyzing a bug it is tempting to follow the first breadcrumbs seen in the data in an attempt to understand the issue, but this way one may end ep trying every possible hint and spend hours exploring dead-ends. Alternatively, one may take time to fully understand the context of the issue, appreciate its complexity and collect as many facts as possible before even trying to make assumptions regarding the cause of the problem. In this case he will be able to see clearly which guesses are worth a deep investigation and which can be ignored altogether.

There is a similar situation with, for example, writing blog entries. For some people it is natural to produce a good article  simply by letting their thoughts flow onto paper. For others producing a reasonable piece of writing requires planning it and doing a couple drafts first. I don't belong to the first kind and going the depth-first way always results in frustration and wasting lots of my time on a couple short paragraphs. To be honest, sometimes its very hard for me even to produce the first draft from the start to the end - details kill me on the way. Instead, I begin with a rough outline consisting of several key points, then gradually add several sub-points to each of them. Only after this two-tier plan is there, I would start expanding the sub-points to rough sentences, which make a foundation for the draft. This looks very much like traversing the tree of the future blog post with the breadth-first search algorithm, except for the fact that here nodes and leafs are themselves created by the search process.

While I have enough development and writing experience to understand these things, sometimes I still find myself using the details-first approach where breadth-first search is more appropriate. To some extent, this happens because there is always eagerness to produce results and the depth-first path always seems short and clear - until you start going. But at the same time, it may be the case that in absence of the right words to distinguish the two strategies nothing forced me to make a conscious choice - the analogy with the search algorithms came to me only recently. In addition to making the choice clearly visible, it also brings the criteria for picking one of the two approaches. When you need to devise a good solution or just to understand a large and potentially complex problem, breadth-first search will work better - the theory says it guarantees the best result possible. If, however, you need the result early and don't care about its quality too much - for example when building a quick prototype to get an idea of the look and feel of a future product - you'd better use the depth-first search, as it usually yields faster. Sounds obvious, but somehow just having this analogy with the algorithms world in mind seems to make the task of selecting the right approach to any problem easier.

пятница, 6 июня 2014 г.

How to Make an SQL From Clojure or My Macros Kata: Part 2

In a recent post I showed some strange things that one can do with macros to be able to write SQL-like queries right in Clojure. Several weeks ago we enabled selecting fields from records as well as filtering them with where clause. In the end of the first post I promised you that we will soon add sorting capabilities to our query language and enable joining “tables” together. Not that I am going to totally break this promise, but I will deliver on it only partially: this time we will do sorting and the sweetest part, joins, we leave for the final post.

Before proceeding, let me remind once more that the code obtained through this exercise is not something that can be used in any real application – it sucks from both performance and feature-richness perspectives and is hardly idiomatic, nice or readable. Furthermore, while doing the exercise I gradually came across the idea that what I show here is by no means a good way to utilize the power of macros. Still, I am sure that implementing a query language like this is a good exercise and can really help one understand what macros are about, how to handle them and, at least, where one should not use them. This way of learning is hard but it pays back a lot once you put enough effort into it.

Let’s recap where did we stop last time. First of all, we mastered picking fields from records and can write simple queries like this one:

(def table [
  {:a 1 :b 100 :c "100" :d 4}
  {:a 2 :b 200 :c "200" :d 3}
  {:a 3 :b 300 :c "300" :d 2}
  {:a 4 :b 400 :c "400" :d 1}])

(select :c from table)
;=> ({:c "100"} {:c "200"} {:c "300"} {:c "400"})

However, since this is hardly an impressing achievement and can be done in a much more concise way, we have gone further and allowed for filtering – starting from very simple conditions and proceeding to quite long and complex ones:

(select :a :b from table where :a < :d)
;=> ({:a 1, :b 100} {:a 2, :b 200})

(select :a :b from table where :a = 2 or (:d < 3 and :b > 300))
;=> ({:a 2, :b 200} {:a 4, :b 400})

Our key goals were to make the syntax as close to SQL as possible and I think we succeeded at it – at the cost of introducing a lot of complex stuff, whose main purpose is to deal with symbols like from, where and others. Now let’s take a look at our macros and see what we can do to make ordering possible. The key player in our team is select:

(defmacro select [& what]
  (let [fields (set 
          (take-while #(not= 'from %) what))
      source (fnext 
          (drop-while #(not= 'from %) what))
      conditions (next (drop-while #(not= 'where %) what))]
      `(map (fn [record#]
            (into {} (filter #(~fields (first %)) record#)))
          (filter #(condition % ~@conditions) ~source))))

For now, select is aware of from and where clauses, which it uses to find the desired fields, the source table and the filtering conditions in a query. To enable sorting we have to pay attention to the order by clause as well and here I am going to cheat. For the sake of making code a tiny bit simpler I will use a single orderby word without a whitespace – this will save us a couple keystrokes. The only place in our code where we have to pay attention to this symbol is in the select macro, where we have to retrieve the actual ordering conditions from the original query. For this we use the same approach as with where – basically skip everything up to the orderby symbol and the symbol itself. At the same time, we should remember that the new clause at the end of the query might introduce a problem: we don’t want this stuff to get into the condition macro, because upon meeting orderings it will immediately spit an “Unable to resolve symbol: orderby” error. Thus, we also restrict the conditions list on both sides:

(defmacro select [& what]
  (let [fields (set 
          (take-while #(not= 'from %) what))
      source (fnext 
          (drop-while #(not= 'from %) what))
      conditions (take-while #(not= 'orderby %) 
             (next (drop-while #(not= 'where %) what)))
      orderings (next (drop-while #(not= 'orderby %) what))]
      `(map (fn [record#]
            (into {} (filter #(~fields (first %)) record#)))
          (filter #(condition % ~@conditions) ~source))))

Now, once we have the orderings list extracted from the query, we can use it in some way. Because the select macro doesn’t look pretty straightforward already, it is a good idea to implement the sorting stuff elsewhere and just use it in select. For this purpose we are going to introduce another macro - order. To start with, let us make it distinguish between 2 situations: when no ordering is requested and when there is actually some stuff in the ordering conditions list. For now we can simply return nil in the latter case. The place to plug ordering in select seems quite obvious: sorting should be done after filtering so we will just wrap the existing body of select (the syntax-quoted part) in a call to the new macro:

(defmacro order [orderings what]
  (if (empty? orderings)
    what
    nil))

(defmacro select [& what]
  (let [fields (set 
          (take-while #(not= 'from %) what))
      source (fnext 
          (drop-while #(not= 'from %) what))
      conditions (take-while #(not= 'orderby %) 
             (next (drop-while #(not= 'where %) what)))
      orderings (next (drop-while #(not= 'orderby %) what))]
      `(order ~orderings
        (map (fn [record#]
            (into {} (filter #(~fields (first %)) record#)))
          (filter #(condition % ~@conditions) ~source)))))

If you execute any query with the updated macro you will see that the only thing that has changed is that now we get nil when there is a non-empty orderby clause:

(select :c from table where :a > 1)
;=> ({:c "200"} {:c "300"} {:c "400"})

(select :b :c from table where :a > 1 orderby :b)
;=> nil

Let’s take this as an evidence that we didn’t break anything and proceed with sorting. First, what are we expecting to get in the list of ordering conditions? Definitely, it should contain keywords denoting the fields to order by. Besides, each of these keywords may have an optional asc or desc symbol after it, standing for ascending and descending order, respectively. When the keyword is not followed by such a symbol, we will assume ascending order, similarly to what SQL dialects do. Now, this is not a completely trivial thing to implement, so let us first do something simple – for example, handle the case when there are only keywords in the orderings list. For this we only need to use the built-in sort-by and juxt functions in the order macro:

(defmacro order [orderings what]
  (if (empty? orderings)
    what
    `(sort-by (juxt ~@orderings) ~what)))

(def table [
  {:a 1 :b 400 :c "200" :d 4}
  {:a 2 :b 300 :c "100" :d 3}
  {:a 3 :b 200 :c "400" :d 2}
  {:a 4 :b 100 :c "300" :d 1}])

(select :b :c from table where :a > 1 orderby :b)
;=> ({:c "300", :b 100} {:c "400", :b 200} {:c "100", :b 300})

(pprint (select :a :b :c :d from table orderby :d))
;=> ({:a 4, :c "300", :b 100, :d 1}
;=> {:a 3, :c "400", :b 200, :d 2}
;=> {:a 2, :c "100", :b 300, :d 3}
;=> {:a 1, :c "200", :b 400, :d 4})

The examples show us that filtering and the simplest sorting facilities both work nicely. Still, if we chose to ask for ascending or descending order explicitly, the compiler will award us with something like “Unable to resolve symbol: asc”. Let us allow for these symbols and get closer to our goal. Here I want to start with something that I have been avoiding since the beginning of our strange exercise – we will get rid of the asc and desc symbols in the order macro well before doing anything else. Even though while implementing select and condition I got used to handling symbols in macros, they still bother me a lot and I want to force them out as fast as possible. We will replace asc with 1 and desc with -1 – this feels pretty logical and saves us from comparing everything to asc and desc as well as from the attempts to prevent Clojure from evaluating these symbols.

(defmacro order [orderings what]
  (if (empty? orderings)
    what
    (let [orderings-desym
        (vec (map (fn [s]
        (cond (= 'desc s) -1
            (= 'asc s) 1
            (keyword? s) s))))]
    `(sort-by (juxt ~@orderings) ~what))))

Next, we need a way to understand which keywords should go with which order. This would be very simple should we not allow to skip the asc symbol, but with this extra convenience feature we have to find a way to handle this without falling into some non-trivial loop-recur construct. Fortunately, this can be done in a not very elegant but satisfactory manner:

(defmacro order [orderings what]
  (if (empty? orderings)
    what
    (let [orderings-desym 
        (vec (map (fn [s]
        (cond (= 'desc s) -1
            (= 'asc s) 1
            (keyword? s) s))))
          orderings-separated 
          (->> orderings-desym
              (partition-by keyword?)
              (map (partial interpose 1))
              flatten
              (partition-all 2))]
    `(sort-by (juxt ~@orderings) ~what))))

This seemingly strange sequence of functions transforms the incoming list of ordering conditions into a sequence of pairs of the form (:key 1) or (:key -1). To achieve this result we first separate the list into sublists of keywords without ordering markers and those of ordering markers themselves. Then we use interpose, which will add missing 1‘s, and flatten the resulting list to finally split it into pairs. To make this easier to understand let’s take a look at the example – here are the stages of this transformation for a particular list of ordering conditions:

;0. [:a :b :c 1 :d :e -1 :f] ;initial orderings
;1. ((:a :b :c) (1) (:d :e) (-1) (:f)) ;partition-by keyword?
;2. ((:a 1 :b 1 :c) (1) (:d 1 :e) (-1) (:f)) ;map (partial interpose 1)
;3. (:a 1 :b 1 :c 1 :d 1 :e -1 :f) ;flatten
;4. ((:a 1) (:b 1) (:c 1) (:d 1) (:e -1) (:f)) ;partition-all 2

As you see, each keyword apart from the last one gets its 1 or -1. – missing tail is, in fact, not a big problem and we will deal with it shortly. Now we have set up everything except for the actual sorting part – we need to transform the new sequence of conditions into a list of functions suitable for sort-by. For this purpose, we can introduce an auxiliary function and consume it in the order macro:

(defn order-fn
  ([k]
    k)
  ([k ord]
    (if (neg? ord)
      `(fn [r#] (- (~k r#)))
      k)))

(defmacro order [orderings what]
  (if (empty? orderings)
    what
    (let [orderings-desym 
        (map (fn [s]
        (cond (= 'desc s) -1
            (= 'asc s) 1
            (keyword? s) s)) orderings)
          orderings-separated 
          (->> orderings-desym
        (partition-by keyword?)
        (map (partial interpose 1))
        flatten
        (partition-all 2))
          order-funcs 
          (map #(apply order-fn %) orderings-separated)]
    `(sort-by (juxt ~@order-funcs) ~what))))

(pprint (select :a :b :c :d from table orderby :a desc))

;=> ({:a 4, :c "300", :b 100, :d 1}
;=> {:a 3, :c "400", :b 200, :d 2}
;=> {:a 2, :c "100", :b 300, :d 3}
;=> {:a 1, :c "200", :b 400, :d 4})

It works! Let’s try to understand why. The key piece is the order-fn, which generates sorting functions for us. The one-argument version is trivial – it takes a single key and returns it to the caller. Why do we need something this stupid? Well, that’s simply our way to handle the last keyword in the orderings sequence when it comes without explicit asc or desc. As seen in the example above in this case it won’t have an ordering marker (1 or -1) in the orderings-separated list, but with the help of order-fn defined as above we can just ignore this and everything will work fine. 

The two-arguments version of order-fn is a bit less trivial but still manageable: it will either return the keyword if we want ascending order, or wrap it into a function that will "invert" the numeric value retrieved with the keyword otherwise.  At the same time, here we have one nasty feature: it returns a syntax-quoted fn form instead of a mere function. This might seem weird – and it is – but at the same time that’s the only way it is going to work. The problem here is that we use order-fn in a macro to produce another function – a closure around the k argument. This combination of macro, function and closure somehow makes compiler vomit “No matching ctor found for class user$order_fn$fn__*” errors. I must admit that I failed to understand this problem – if you can explain it I would be grateful. Still, for now we, at least, can go on with quoting.

The way we use order-fn is very simple – we map it onto the list of (key, sorting order) pairs and then pass the resulting functions to juxt. The latter produces a single function, which extracts all the values used for ordering from a record. Finally, in combination with sort-by this gives us a properly ordered results set.

Now, you might have spotted several problems with our solution. The most severe one (apart from the approach in general) is that we allow sorting only by the numeric fields – strings won’t do. This is because to produce an ordering function for desc we use simple numeric negation, which isn’t compatible with strings, sequences or anything else. I have tried to come up with a more generic solution, but the time and brainpower that I had put into it were not enough. Fortunately, my goal of understanding macros better and learning to be not afraid of quoting and unquoting allows me to live with this. However, if you come up with a more generic implementation of order-fn it will be a great pleasure for me to see it – please share it in comments!

On the other side, the use of quoting in the order-fn makes me think that something is definitely wrong with our approach to the problem. The degree of complexity of our macros also strengthens this feeling – I still can manage them, but it ceased to be an easy task long before we produced a working implementation of orderby. I have already stated that this way of implementing SQL-ish queries doesn’t look like an idiomatic way to use Clojure macros and all these concerns only reassure me in this idea. Still, the audible tension that I had in my brains when fighting this stuff confirms that the exercise is a damn good kata.

Here are some of my takeaways from this iteration:
  • Maybe the most frequent error that I faced here was the “Wrong number of arguments passed to a keyword” one. The reason for this was always that Clojure tried to evaluate a list starting from a keyword when I didn’t mean it to be evaluated. This same problem manifested itself in some other ways and I find it the most important thing to tackle: you should always pay close attention to what and when you are evaluating.
  • I have expected to face some difficulties with sorting over several fields – until I remembered that there is juxt in Clojure. So one of the lessons from each and every exercise in programming is actually that there is likely a function to solve your problem. That's actually one of the reasons why it is good to do these exercises – you discover and remember a lot of useful stuff.
  • One sign of using a wrong approach to a problem is that you have a lot of bindings or variables and find it difficult to come up with proper names for them (order, order-fn, orderings-separated, etc simply don’t sound very good). Maybe the most appropriate thing to do under such conditions is to step back and try to rethink the way you reason about the problem.

I will add joins to the mess in the next post – as promised. For now, feel free to play with what we already have – here is the code. By the way, there is a problem with our new select macro, which limits sorting capabilities, but is very easy to fix. Did you spot it? Let me know in the comments!

In addition to showing me where I messed up, please tell whether you find this exercise a good way to accustom oneself with macros or do you think it is as useless as it is long and complex? Maybe you have your favorite Clojure kata, which helps to explore and understand macros better? I will be glad to hear about it!

пятница, 9 мая 2014 г.

How to Make an SQL from Clojure or My Macros Kata

Despite the fact that I started learning Clojure about 2 years ago, until recently I didn’t explore, maybe, the most fascinating part of the language – macros. I did try to compose simple macros once or twice, but generally they failed to grasp my attention and I never understood how they work and, more importantly, when should I use them. To fix this, last month I decided to implement something interesting with the help of macros and here I will show what I did and sum up what I learnt.

The example that I’ve taken might be not the most suitable for the goal, but it worked out quite well. The idea was to allow for writing SQL-like queries against the lists of Clojure dictionaries or records – basically anything that allows key-based access to elements. The value of such a thing is doubtful, but SQL is a well-known Domain Specific Language and the fact that macros are considered a great tool for creating new languages in Clojure made me chose it as an exercise. Besides, I remember that there was an exercise like this – similarly with SQL-like queries – in the Joy of Clojure book, which made me think that this task suits my learning goals well. However, I intentionally avoided peeking into the book to not spoil my exercise and, kind of, do everything myself without borrowing others’ ideas and solutions.

The results at which I arrived are quite fascinating: I am now able to write almost real SQL against lists of records. The key difference between my queries and SQL is the use of keywords as the names of fields to select and filter on. In addition to that, well, my selects come in parenthesis, because I am still writing LISP. Otherwise, everything looks very similar to the queries one would execute against a database and that feels pretty awesome. Now, let me share my excitement and show you the code.

In the first article we will begin with simply selecting some fields from the records and add where clause for filtering. In the second one I will show how we can enable joining tables together and ordering the results. So, what we want to achieve at the first step is to be able to write a query like this:

(def table [
  {:a 1 :b 100 :c "100" :d 4}
  {:a 2 :b 200 :c "200" :d 3}
  {:a 3 :b 300 :c "300" :d 2}
  {:a 4 :b 400 :c "400" :d 1}])

(select :a :b from table)

This is not a very difficult task, because all that we have to do is limit the set of key-value pairs in each dictionary in the resulting list to only the keys, which are specified in the query. On the other hand, we have this from symbol to treat, but that’s quite easy as well.

(defmacro select [& what]
  (let [fields (set 
          (take-while #(not= 'from %) what))
      source (fnext 
          (drop-while #(not= 'from %) what))]
      `(map (fn [record#]
            (into {} (filter #(~fields (first %)) record#)))
          ~source)))

It turns out that similarly to the functions I can’t easily write a macro, which solves precisely one problem, so several things are going on in select. First, we have to get hold of a set of keys denoting fields to select. All of them come before the from word and for now we can assume that everything that goes before it is a field name. This said, we just take elements of the argument list until we meet from, push them into a set and bind it to the fields symbol. In a very similar fashion we extract the table, from which we want to select records – I expect that it is found right next to from, so I skip everything until from as well as from itself and grab the first element of the remaining sequence. Having fields and source, we can actually define what our macro will return to the caller. We simply map a function that filters each record according to the presence of the key in the fields set and composes a hashmap from the resulting key-value pairs  onto the “table”. Although this doesn’t feel like the most efficient and nice solution, I’m okay with it for now.

Because we are writing a macro we want to return something that will be evaluated upon execution of the program – that’s why we syntax-quote our map call with the `. Syntax-quoting prevents the form from being evaluated, but unlike simple quote (‘) it allows us to avoid unquoting map, fn and all the other stuff that is used inside it. One of the problems with quoting surfaces when we want to use a binding inside the body of a macro – in our case with fn. The idea is that binding requires a symbol and we need to introduce it somehow. There are several alternatives, but the simplest one is to use the gensym thing through suffixing a symbol with # character. When encountered with it inside a syntax-quoted form, Clojure will generate a non-qualified symbol, which we can then use. Finally, in select we need to unquote fields and source so that proper stuff will be inserted in the respective places. If you forget to unquote these symbols, syntax reader will try to resolve them to fully-qualified ones. This may result either in a failure in case you don’t have such a symbol outside the macro, or in a subtle failure – if you have one. The latter situation might lead to great confusion: the code that used to work will at some moment get broken because its surroundings have changed. Fortunately, in most cases such an error will surface quite soon if not instantly. Having done all these things right, we can check whether they work and, fortunately, they do:

(select :a :b from table)
;=> ({:a 1, :b 100} {:a 2, :b 200} {:a 3, :b 300} {:a 4, :b 400})

Let us try to understand what did macro allow us to do here that a function wouldn’t permit. Most notable thing is our use of the from symbol. Despite the fact that it is not bound to anything we can still utilize it in the macro – as a separator. A function wouldn’t allow that because it would try to evaluate all the arguments passed into it and fail with from. Macros, on the other side, receive their arguments in unevaluated form, which allows us to play with them in different and strange ways. Note that we could achieve the same behavior with a function if we used, for example, a keyword :from instead of the pure symbol, so there is actually little value in using macros like this. However, knowing that Clojure allows us to write down some utterance and can live with it is pleasant and inspiring.

Now, when we can select stuff, let us introduce filtering. This task is less trivial not only due to more complex constructs needed for conditions, but also because they will come in infix notation, which is natural for SQL, but hardly a common thing in LISPy Clojure. Even though this may sound difficult, it boils down mainly to tossing the list of arguments and just requires covering a couple of cases and careful use of recursion.

To make filtering possible we will define a macro that creates a Clojure-evaluatable condition from an SQL-like one. First, we will try to cover the most simple case – something like select :a :b from table where :a < :d. Our new macro – let’s call it condition – will get the :a < :d part of the above query from the select and return something like (< (:a table) (:d table)) – the piece, which Clojure will easily consume. The first version is going to be ve-e-ery simple:

(defmacro condition [t k1 op k2]
  `(~op (~k1 ~t) (~k2 ~t)))

The only thing that we do here is changing infix notation into prefix one and accessing the values from a record with the keys specified in the condition. We can use macroexpand to check that condition easily treats simple cases:

(macroexpand '(condition table :a < :d))
;=> (< (:a table) (:d table))

(macroexpand '(condition table :b = :c))
;=> (= (:b table) (:c table))

The fact that the macro fits easily into one line makes me ask myself whether there is any reason to writing it. However, instead of trying to find an answer I will simply fix the cause and… make it longer. One thing that condition misses is the ability to consume literals. For example, it is pretty natural to write a filter like this: where :a > 2 and we definitely should support this. We will do it the simple way – if we face a keyword in a condition, we will use it to get the corresponding value from the record and inject it in the resulting code. Otherwise, we won’t do any transformations to the value and will include it into the result as is:

(defmacro condition [t k1 op k2]
  (let [v1 (if (keyword? k1) `(~k1 ~t) k1)
      v2 (if (keyword? k2) `(~k2 ~t) k2)]
  `(~op ~v1 ~v2)))

Now condition treats both keys, which denote fields of the records, and mere numbers or strings equally well allowing us to filter both based on relationships between fields and on their comparison with some external values. What makes me feel particularly great about the new version of the macro is that there are no checks for keywords in the code that it outputs – it determines whether it looks at a keyword in the let form, which is not a part of the resulting code. This makes the output of the macro shorter and a bit more efficient. To see it we can do macroexpand as usual:

(macroexpand '(condition table :d not= :a))
;=> (not= (:d table) (:a table))
; no checks for keyword, table accessed in both cases

(macroexpand '(condition table :a < 3))
;=> (< (:a table) 3)
; no checks for keyword, and table accessed only once
; while for 3 we have just 3

Our condition macro can’t handle neither complex nor long conditions so far. We will make it almost universal a little bit later, but now let’s take a step back and assemble condition and select together. When faced with this task first I did introduce another level of indirection in the form of additional helper function, which would wrap the condition. However, it turns out that one can do this with much less clutter. After some experiments, I ended up using a lambda expression in the body of select:

(defmacro select [& what]
  (let [fields (set 
          (take-while #(not= 'from %) what))
      source (fnext 
          (drop-while #(not= 'from %) what))
      conditions (next (drop-while #(not= 'where %) what))]
      `(map (fn [record#]
            (into {} (filter #(~fields (first %)) record#)))
          (filter #(condition % ~@conditions) ~source)))) 

In the snippet above we have added another binding to take hold of the conditions passed into select. We assume that they go after the where word and thus extract them from the arguments list similarly to the fields keys and the table. Then, in the body of the macro we introduce filtering, which is performed with a lambda making use of our condition macro and the list of conditions in infix notation. The most surprising part is that this thing actually works:

(select :a :b from table where :a < :d)
;=> ({:a 1, :b 100} {:a 2, :b 200})
(select :d :c from table where :d >= 3)
;=> ({:c "100", :d 4} {:c "200", :d 3})
(select :a :b :c :d from table where :a = :b)
;=> ()

That’s a wonderful achievement, we can write SQL queries in Clojure! Well, almost. For now, we miss a couple things including joins, ordering and more complex conditions. The latter seem to be the most natural thing to address next, so let us enable queries like (select :a :b from table where :a <= 2 or :c = “400”). At the current stage trying to execute something like this will lead us to a “Wrong number of arguments passed to the condition macro” error, which is a not so often case when the error message is actually helpful. We do not in fact allow conditions composed of more than three elements and that’s what we will fix right now.

The most trivial way to allow for the longer conditions like :a <= 2 or :c = “400” is to introduce another version of condition macro, which would take 8 arguments: [t k1 op1 k2 link k3 op2 k4]. Here k3 and k4 are either field keys or values (:c and “400” in the above example) similar to k1 and k2, op2 is a comparison operator (=) like the op1 and link is a Boolean function (or), which glues two parts together. Now, 8 arguments is quite too much even if we try to bring SQL into Clojure. If you don’t think so, it is not difficult to come up with a three-part condition which would require 12 arguments with even more stupid names. Fortunately, we don’t have to write all these things out because the similarity between k3 op2 k4 and k1 op1 k2 suggests that we can generalize the implementation to allow arbitrary long conditions with quite a short and concise piece of code:

(defmacro condition 
  ([t k1 op k2]
    (let [v1 (if (keyword? k1) `(~k1 ~t) k1)
        v2 (if (keyword? k2) `(~k2 ~t) k2)]
    `(~op ~v1 ~v2)))
  ([t k1 op1 k2 link & other]
    `(~link
      (condition ~t ~k1 ~op1 ~k2)
      (condition ~t ~@other))))

First of all, the version with 4 arguments remains intact meaning that we don’t break the existing code, which is great. Another good thing to note, is that we reuse it inside the version with the longer argument list – there is no need to write the checks for keywords and move arguments once more, given that we have written this code before. Moreover, this new version of condition might reuse itself in case the other part of arguments list includes more than three elements. This basically means that in addition to the original goal we just allowed writing conditions like :a = 1 or :a = 2 or :a = 3 or :a = 5 or :a = 6 or :a = 7 at no cost. Recursion is a great thing by itself, but it is even greater when combined with argument lists of arbitrary length. Especially so when it works:

(select :a :b from table where :a <= 2 or :c = “400”)
;=> ({:a 1, :b 100} {:a 2, :b 200} {:a 4, :b 400})

(select :a :b from table where :a = 1 or :a = 2 or :a = 4 or :a = 5 or :a = 6 or :a = 7)
;=> ({:a 1, :b 100} {:a 2, :b 200} {:a 4, :b 400})

This all looks incredible, but there is another crucial thing that we miss – conditions can be complex, which means that we might want to include prioritization with parenthesis into them. This could be a difficult and messy thing to implement should we write in something that is not LISP. However, with Clojure macros everything wrapped in parenthesis is a list and can be treated as a list. The incredible power behind this idea becomes clear once we see how little code we have to add to the existing condition macro to  dramatically increase allowed complexity of conditions:

(defmacro condition
  ([t complex]
    `(condition ~t ~@complex))
  ([t k1 op k2]
    (let [v1 (if (keyword? k1) `(~k1 ~t) k1)
        v2 (if (keyword? k2) `(~k2 ~t) k2)]
    `(~op ~v1 ~v2)))
  ([t k1 op1 k2 link & other]
    `(~link
      (condition ~t ~k1 ~op1 ~k2)
      (condition ~t ~@other))))

As you can see, the only new thing in the macro is another override accepting two arguments: the usual record t and a complex condition. Having taken the complex part it basically unwraps it and calls itself with the extracted elements. As a positive side effect, this little addition drops the optional parenthesis in case someone decides to surround the entire restrictions list with them.

(select :a :b from table where :a = 2 or (:d < 3 and :b > 300))
;=> ({:a 2, :b 200} {:a 4, :b 400})

(select :a :b from table where (:a <= 2 or :c = “400”))
;=> ({:a 1, :b 100} {:a 2, :b 200} {:a 4, :b 400})

Once again, recursion and pattern matching do a lot of hard work for us. However, even though this feels like magic, it isn’t and there is an input that we should definitely handle, but don’t treat well so far. That’s the first of the above examples but with reversed order of restrictions: (select :a :b from table where (:d < 3 and :b > 300) or :a = 2) yields an error. The problem is that we allow parenthesis only in the tail position of the conditions list. On the other side, should we do TDD, tests would tell us that we have already broken the select macro – it doesn’t work without filtering anymore, because no matter if there is the where word and something after it in the arguments list, we always try to construct a filter. Since condition macro doesn’t work with a single argument, record, it rightfully fails. Here is the final version of the macro, which addresses both issues:

(defmacro condition
  ([t]
    `true)
  ([t complex]
    `(condition ~t ~@complex))
  ([t k1 op k2]
    (if (seq? k1)
      `(~op
        (condition ~t ~k1)
        (condition ~t ~k2))
      (let [v1 (if (keyword? k1) `(~k1 ~t) k1)
          v2 (if (keyword? k2) `(~k2 ~t) k2)]
      `(~op ~v1 ~v2))))
  ([t k1 op1 k2 link & other]
    (if (seq? k1)
      `(~op1 
        (condition ~t ~k1)
        (condition ~t ~k2 ~link ~@other))
      `(~link
        (condition ~t ~k1 ~op1 ~k2)
        (condition ~t ~@other)))))

To handle queries without filtering we simply introduce another overload of condition for empty restriction list that returns quoted truth (this even sounds cool!). When we invoke it from select, true ends up in the body of the filter function making it allow every record that it sees. As for making parenthesis work in any position, to allow this we have to do a little bit more work. The idea is that when introducing prioritization we made our older assumptions about what is a comparable value (k1, k2, etc.), what is a comparison operator (op, op1 and op2) and what is a Boolean link between several restrictions fallible. However, to fix this we can just check whether we look at something enclosed in parenthesis and handle the thing accordingly if we do. That’s what the new seq? parts are for. Even though this makes the macro grow in size significantly, I believe that’s a fair price for almost universally working solution:

(select :a :b from table where (:d < 3 and :b > 300) or :a = 2)
;=> ({:a 2, :b 200} {:a 4, :b 400})

(select :c from table)
;=> ({:c "100"} {:c "200"} {:c "300"} {:c "400"})

Now, that we achieved an important milestone of selecting stuff from lists of records or dictionaries and filtering it freely, let me sum up what I learnt from the exercise:
  1. Macros really make one think in a different way than when composing mere functions. Even though it is hard to communicate this feeling, writing code that produces code is whole another sensation than writing code that produces data.
  2. On the other side, Clojure does its best to make code as similar to data as possible. Storing programs in lists is cool, because here and there this saves you from extra difficulties.
  3. Arguments passed to a Clojure function are evaluated first; those passed to a macro are not. This makes a huge difference.  
  4. You can’t apply a macro, but you can splice-unquote arguments for it. 
  5. In a macro you can have code that it will return – usually quoted – and code that determines what will be returned and does not show up in the macro’s result. 
  6. Doing katas is worth the effort even if you don’t feel like it helps you understand anything. If something feels too much for you just force yourself into it and logic will gradually surface. To some extent learning is like violence. 
  7. If you don’t refactor, you might be missing a chance to understand both your code and your tools.
  8. Explaining what you have done in a sum-up blog entry might feel stupid, but if you are not doing this you are maybe missing another chance to understand both your code and your tools.

For now I didn’t cover a couple of things, which one expects from SQL. Most important are joins and ordering – these I will implement in the next article. Besides, there are a lot of minor features like, for example, selecting all the fields from a table with a star (*). This particular one is extremely easy to introduce, so I won’t show it here – you can take a look at the code on GitHub if you want.

Note that the above GitHub repository differs in some ways from the code shown in this post. If you want the latter, just grab this single file – zero dependencies is great.

I have also discussed my affair with macros in the recent episode of our Code Speak Loop podcast with my co-host Michael Pankov.

пятница, 11 апреля 2014 г.

Use Converters in your Windows Phone Apps

In a recent post I have covered several approaches to store data in a Windows Phone application. Another important problem is presenting data in an easy and controllable way that would not interfere with other layers of your app. To some extent XAML handles this task well, but from time to time just markup is not enough and one needs to introduce a portion of imperative code to present data nicely. To make this possible each binding in a XAML-based app may specify a converter, which will be responsible for transforming data between internal and external representations.

пятница, 7 марта 2014 г.

3 Easy Ways to Store Data Locally in a Windows Phone App

Our applications – no matter whether games, productivity tools or business software – are all about data. As a result, when developing a program of any kind we spend most of the time solving data-related problems like where to get it, what to do about it, how to show it to our users and where to store it. Here I want to discuss the ways to get along with the last task and focus only on the ways to persist your application’s information locally. In Windows Phone this is in fact incredibly easy to do, although there are still several options to pick from and the choice depends on both how complex your data structures are and how and when you plan to utilize them.



Settings


The first approach to storing data in a Windows Phone application uses the IsolatedStorageSettings. While this one imposes certain restrictions on the developer, it is at the same time probably most widely used one. The reason is that almost any application has a bit of settings – both available to user and those utilized by the app internally. IsolatedStorageSettings actually gives you a key-value storage to save some named values and makes them easily available to you. This approach is most appropriate for storing simple stuff like bools and strings, although with the help of data contracts it is possible to save complex objects in the settings dictionary as well. The following code snippet shows how you can put some values into the IsolatedStorageSettings:

//using System.IO.IsolatedStorage;

IsolatedStorageSettings.ApplicationSettings["DontAskForRating"] = false;
IsolatedStorageSettings.ApplicationSettings["UserName"] = "Just Someone";
IsolatedStorageSettings.ApplicationSettings["WinsCount"] = 9000;

Reading settings is no more difficult than storing them. One thing to keep in mind here is that you have to store the values before you try to retrieve them. Fortunately, like any dictionary, the one exposed by IsolatedStorageSettings allows to check whether some key is present in it:

if (IsolatedStorageSettings.ApplicationSettings.Contains("DontAskForRating"))
{
    var booleanSetting = (bool)IsolatedStorageSettings.ApplicationSettings["DontAskForRating"];
}

if (IsolatedStorageSettings.ApplicationSettings.Contains("UserName"))
{
    var stringSetting = (string)IsolatedStorageSettings.ApplicationSettings["UserName"];
}

if (IsolatedStorageSettings.ApplicationSettings.Contains("WinsCount"))
{
    var intSetting = (int)IsolatedStorageSettings.ApplicationSettings["WinsCount"];
}

The application will automatically persist the updated values when closing, although if you want to save them right away you are free to call the Save() method. To keep things simpler, easier to maintain and more readable I tend to encapsulate all the messing with application settings in my own helper class, which usually looks something like this:

class MySettings
{
    private const string _DontAskForRatingKey = "dontaskforrating";
    private const string _UserNameKey = "username";

    private IsolatedStorageSettings AppSettings
    {
        get
        {
            return IsolatedStorageSettings.ApplicationSettings;
        }
    }

    public bool DontAskForRating
    {
        get
        {
            if (AppSettings.Contains(_DontAskForRatingKey) == false)
            {
                DontAskForRating = false;
            }
            return (bool)AppSettings[_DontAskForRatingKey];
        }

        set
        {
            AppSettings[_DontAskForRatingKey] = value;
            AppSettings.Save();
        }
    }

    public string UserName
    {
        get
        {
            if (AppSettings.Contains(_UserNameKey) == false)
            {
                UserName = "Just Someone";
            }
            return (string)AppSettings[_UserNameKey];
        }

        set
        {
            AppSettings[_UserNameKey] = value;
            AppSettings.Save();
        }
    }
}

Here in getters I check the corresponding keys, so that if one is absent I first set the default value. Besides, it is better to keep your settings’ keys in some constants so that they are defined in one place and can be changed consistently with little effort. Finally, introducing the shortcuts like AppSettings, which reduce the amount of clutter in code and make it much easier to read always seems a good idea to me.

Even though the IsolatedStorageSettings dictionary’s value type is object and you can potentially stick anything DataContract-serializable into it, it is not a very good idea to store large and complex entities in settings. If you decide to do this you should keep in mind that the app’s settings are retrieved in the process of starting up the application so that they are available to the application once it is loaded. This means that the harder is the job of loading the objects the longer will be the loading time of the application and you won’t have a way to control it (what if deserialization throws an exception?). This said, we'd better move the complex entities out of the settings – in this case you can make the decision on when they should be restored or saved on your own.

Overall, according to recommendations from the MSDN, the IsolatedStorageSettings are most suitable for storing little pieces of data, which are required when the app starts or shuts down – at these moments the key-value storage is entirely accessible to you. If you want to know more about this approach, check this article on Nokia Developer portal.


Simple types serialization


Now let’s switch to file-based storage. Windows Phone gives developers access to application’s individual file system through the IsolatedStorageFile class. This one allows you to create, read, write and remove files in a way very similar to that used when writing, say, desktop programs. This basically means that you are free to store your data in whatever form that is writable to a traditional file – for instance, you can freely push text or bytes to the stream, acquired through opening a file. At the same time such a low-level approach is rarely convenient and maintainable, which brings us to serialization. The de-facto standard for serializing data in Windows Phone applications is the DataContract-based serialization, which I will cover in the next section. For now I will stick to the XmlSerializer just to demonstrate that almost any serializer is suitable here. What I want to offer you is to store a chunk of built-in types – for example, a list of strings. This option, while being not that widely applicable, is very convenient and easy to implement in some cases, because it does not require any data contract at all:

public void SaveStrings()
{
    var quiteImportantStrings = new List<string>
    {
        "Audi", "BMW", "Mercedes Benz", "Porshe", "Volkswagen", "Opel"
    };

    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (storage.FileExists("awesomefile.xml"))
        {
            storage.DeleteFile("awesomefile.xml");
        }

        using (var file = storage.CreateFile("awesomefile.xml"))
        {
            var serializer = new XmlSerializer(typeof(List<string>));
            serializer.Serialize(file, quiteImportantStrings);
        }
    }
}

Quite simple, right? The best use-case for this approach is when your application handles some objects, which are easily and unambiguously represented by a built-in type. It is even better if you need to convert between the objects and such representation anyway because the latter is somehow utilized by the application. In this case, using DataContract serialization would mean an unnecessary overhead, so leaning towards this approach is a good option saving you from writing extra code and covering your objects in a layer of attributes. On the other hand, when compared to IsolatedStorageSettings, which you could use to store the same representations of your objects, it has the advantages of controllable execution. This seems especially important when your collection might easily grow with time, So if you just have a plain list of things, which can be represented by, say, strings, consider this option, even though it shows a degree of Primitive Obsession. Loading things from file with XmlSerializer is no harder than saving them:

public IEnumerable<string> LoadStrings()
{
    using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (storage.FileExists("awesomefile.xml"))
        {
            using (var file = storage.OpenFile("awesomefile.xml", System.IO.FileMode.Open))
            {
                try
                {
                    var serializer = new XmlSerializer(typeof(List<string>));
                    return (List<string>)serializer.Deserialize(file);
                }
                catch (Exception)
                {
                    //You'd better do something more clever here
                    return new List<string>();
                }
            }
        }
        else
        {
            return new List<string>();
        }
    }
}

As you can see, storing stuff with the combination of IsolatedStorageSettings and XmlSerializer is pretty easy to do. The use cases for this approach are limited, because it sits between using IsolatedStorageSettings and DataContract serialization, which are both very powerful and can satisfy most needs of a developer. Still, there is a niche for this kind of serialization too – it works pretty well when one needs to store potentially long and not-always-needed collections of primitive objects, saving one from both setting up a DataContract and wasting space in the IsolatedStorageSettings.


Data Contract serialization


Now we can finally turn to the approach, which you will likely use most of the time – that is the combination of DataContract serialization with the use of IsolatedStorageFile. The files handling part of the story is absolutely similar to what we’ve just seen in the previous section. You just check whether a file with a particular name exists with IsolatedStorageFile.FileExists(..) method, open it with IsolatedStorageFile.OpenFile(..), create with IsolatedStorageFile.CreateFile(..) or delete with IsolatedStorageFile.DeleteFile(..). What is different is that to use DataContractSerializer on your own entity you have to define the data contract first. This is done through applying proper attributes to the class, which you are going to save and load. The class itself is marked with DataContractAttribute and the properties and fields, which you need to serialize, should bear the DataMemberAttribute:

[DataContract]
public class ImportantData
{
    [DataMember]
    public int GamesTotal { get; set; }

    [DataMember]
    public double WinsPct { get; set; }

    [DataMember]
    public string PlayerName { get; set; }

    [DataMember]
    public bool IsPremiumUser { get; set; }
}

Once you have the DataContract set up, you can serialize the instances of the corresponding class as easily as you did with plain collections:

//using System.Runtime.Serialization;
//using System.IO;
//using System.IO.IsolatedStorage;

public class StoreWithDataContract
{
    public void SaveData(ImportantData data)
    {
        try
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (storage.FileExists("important.xml"))
                {
                    storage.DeleteFile("important.xml");
                }

                using (var file = storage.CreateFile("important.xml"))
                {
                    var serializer = new DataContractSerializer(typeof(ImportantData));
                    serializer.WriteObject(file, data);
                }
            }
        }
        catch (Exception) 
        {
            //your clever error handling goes here
        }
    }

    public ImportantData LoadData()
    {
        try
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (isf.FileExists("important.xml"))
                {
                    var serializer = new DataContractSerializer(typeof(T));
                    using (var file = isf.OpenFile("important.xml", FileMode.Open))
                    {
                        return (ImportantData)serializer.ReadObject(file);
                    }
                }
            }
        }
        catch (Exception)
        {
            return new ImportantData();
        }

    }
}

The advantages of DataContract based approach are clear: it allows one to store quite complex objects – even the whole graphs of them – as well as thoroughly control their representation in one place without any imperative code and related duplication. The DataContract and DataMember attributes are really quite handy and don’t make the classes code much harder to read. Besides, there are several kinds of DataContractSerializer classes, allowing you to pick the most suitable data format – for example, you can use either traditional DataContractSerializer to store your information in XML, or switch to JsonDataContractSerializer and have all your data saved in JSON. Precisely as you would expect changing the serializer does not make you alter DataContract in any way (well there are dates, but…)

As far as DataContract serialization is concerned, there is one thing to keep in mind if you have some Windows Communication Foundation experience. In WCF this approach allows you to serialize not only public data members, but the protected and private ones as well, which makes it particularly useful in comparison to XmlSerializer that can’t peek at the guts of your objects. Windows Phone, however, is a different story and here DataContractSerializer can’t easily access protected and private data. Even though I find this quite constraining sometimes, it makes one better separate interfaces from implementation thus increasing the quality of our software.

So...


These are the 3 options, which I wanted to cover. At the same time, there exists at least one more technique, which plays better under certain circumstances: that is using a database embedded into your app. While there are plenty of engines to choose from, I believe SQLite is the most popular one. Here is an article, which covers the process of setting it up in your application. Finally, although you will most likely need some kind of local storage and use one of the methods described above to implement it, you still can decide to move most of your data to an external storage – a Cloud-based one or a database running on your personal server. There is almost infinite choice of tools and approaches, so you can certainly find one that suits your requirements best, but this topic falls out of scope of this post.

To help you going further, there are very nice slides by Matteo Pagani from the #wpdevfusion event, which compare the approaches to store Windows Phone app data in a shorter and more concise way than I do. Matteo also has a great deal of Windows Phone development materials in his blog – I really recommend it if you do develop apps for this great platform.

Please share your opinion on the best way to keep Windows Phone application data around. I will also highly appreciate suggestions or comments on the approaches, which I describe – feel free to let me know of any mistakes that I may have made here.