Re: what do you think about this code?
From my own experience I think the following is relevant: - functions are either specific to a context or abstract. Specific functions need to be understood in the context of their call site and the domain. Trying to make the name of the specific functions capture the entire context leads to noise. I would gently suggest that most of your functions are specific, particularly the ones motivated by extracting intent. They aren't and almost certainly can't be reusable so their call site is part of their context. If you do want the to be reusable then all that context caotured in the label works against you - again, the drive for reusability and the drive for future proofing often lead us astray. In the solution domain there is only one sensible interpretation of flipping vertically - there is a hint of trying to make the code completely unambiguous and self contained. This is also very similar to trying to make it idiot-proof. I don't think any of these are achievable. (Collective gasp whilst I out on my fireproof coat). The syntax of any programming just isn't expressive enough. Literate programming rocks, but that is because you aren't writing code, you are writing prose - FP programmers tend to be more familiar with the inbuilt catalogue of idiomatic FP solutions, and dare I say I have met many more average OO programmers than FP programmers :). This, coupled with the succinctness of Clojure means idiomatic Clojure already contains a bunch of context. You don't need to tell me what your code is doing because idiomatic Clojure code is inherently readable *once I grok idiomatic Clojure*. For me, I found myself writing that sort of code at the beginning because I was compensating for my lack of familiarity. Nowadays, I tend to find it much more successful producing code that has a certain number of assumptions: - it will be maintained for far longer than it took to write (some of our apps are decades old) - readers will be competant wielders of the toolsets used - idiomatic code is strongly preferred, as are coding conventions - reader understands the problem domain and the solution domain Trying to write code that is somehow a training manual, a design document etc. Is a hiding to nothing. The best communication tool I have found is regular discussions with the relevant people. Corporate mindshare is best maintained through words not code. I said before, and I think I it needs repeating as you asked again, but no, I dont think FP is any less concerned with the WHY or the HOW etc. I do think it uses seperate tools to achieve the same goals. I would claim that my code still satisfies all of the excellent points rsised in the best practices literature, but Clojure doesn't require the same verbosity. As ever, this is only my opinion :). On 14 Dec 2014 07:34, Philip Schwarz philip.johann.schw...@googlemail.com wrote: Hi Leif, if I compare your suggestion (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) with mine (let [top-right-quadrant (create-top-right-quadrant-for letter) top-left-quadrant (drop-first-column-and-reverse-every-row-of top-right-quadrant) top-half-of-diamond (join-together-side-by-side top-left-quadrant top-right-quadrant) bottom-half-of-diamond (flip-bottom-up-and-drop-first-row-of top-half-of-diamond) diamond (put-one-on-top-of-the-other top-half-of-diamond bottom-half-of-diamond)] yours is more inviting, and mine just looks like a barrage of verbiage. But with some judicious spacing and syntax highlighting, I think mine regains IMHO its effectiveness (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(* *drop-first-column-and-reverse-every-row-of* *top-right-quadrant**)* *top-half-of-diamond* *(**join-together-side-by-side* *top-left-quadrant * * top-right-quadrant**)* *bottom-half-of-diamond* *(* *flip-bottom-up-and-drop-first-row-of* *top-half-of-diamond)* *diamond* *(*put-one-on-top-of-the-other *top-half-of-diamond* *bottom-half-of-diamond**)*] even better if I adopt the 'beside' you suggested, and its 'above' counterpart: (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(* *drop-first-column-and-reverse-every-row-of* *top-right-quadrant**)* *top-half-of-diamond* *(**beside* *top-left-quadrant * *top-right-quadrant**)* *bottom-half-of-diamond* *(* *flip-bottom-up-and-drop-first-row-of* *top-half-of-diamond)* *diamond* *(*above *top-half-of-diamond* *bottom-half-of-diamond**)*] Do you see the value of hiding the HOW at all?
Re: what do you think about this code?
Urk , one bit of my post came across wrong: I said before, and I think it needs repeating as you asked again refers to how long these posts are and I thought it had gotten lost in the walls of text. I didn't mean it in the sanctimonious or condescending way it comes across. I really shouldn't try and write these responses whilst entertaining 4 under 10s :). On 14 Dec 2014 10:32, Colin Yates colin.ya...@gmail.com wrote: From my own experience I think the following is relevant: - functions are either specific to a context or abstract. Specific functions need to be understood in the context of their call site and the domain. Trying to make the name of the specific functions capture the entire context leads to noise. I would gently suggest that most of your functions are specific, particularly the ones motivated by extracting intent. They aren't and almost certainly can't be reusable so their call site is part of their context. If you do want the to be reusable then all that context caotured in the label works against you - again, the drive for reusability and the drive for future proofing often lead us astray. In the solution domain there is only one sensible interpretation of flipping vertically - there is a hint of trying to make the code completely unambiguous and self contained. This is also very similar to trying to make it idiot-proof. I don't think any of these are achievable. (Collective gasp whilst I out on my fireproof coat). The syntax of any programming just isn't expressive enough. Literate programming rocks, but that is because you aren't writing code, you are writing prose - FP programmers tend to be more familiar with the inbuilt catalogue of idiomatic FP solutions, and dare I say I have met many more average OO programmers than FP programmers :). This, coupled with the succinctness of Clojure means idiomatic Clojure already contains a bunch of context. You don't need to tell me what your code is doing because idiomatic Clojure code is inherently readable *once I grok idiomatic Clojure*. For me, I found myself writing that sort of code at the beginning because I was compensating for my lack of familiarity. Nowadays, I tend to find it much more successful producing code that has a certain number of assumptions: - it will be maintained for far longer than it took to write (some of our apps are decades old) - readers will be competant wielders of the toolsets used - idiomatic code is strongly preferred, as are coding conventions - reader understands the problem domain and the solution domain Trying to write code that is somehow a training manual, a design document etc. Is a hiding to nothing. The best communication tool I have found is regular discussions with the relevant people. Corporate mindshare is best maintained through words not code. I said before, and I think I it needs repeating as you asked again, but no, I dont think FP is any less concerned with the WHY or the HOW etc. I do think it uses seperate tools to achieve the same goals. I would claim that my code still satisfies all of the excellent points rsised in the best practices literature, but Clojure doesn't require the same verbosity. As ever, this is only my opinion :). On 14 Dec 2014 07:34, Philip Schwarz philip.johann.schw...@googlemail.com wrote: Hi Leif, if I compare your suggestion (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) with mine (let [top-right-quadrant (create-top-right-quadrant-for letter) top-left-quadrant (drop-first-column-and-reverse-every-row-of top-right-quadrant) top-half-of-diamond (join-together-side-by-side top-left-quadrant top-right-quadrant) bottom-half-of-diamond (flip-bottom-up-and-drop-first-row-of top-half-of-diamond) diamond (put-one-on-top-of-the-other top-half-of-diamond bottom-half-of-diamond)] yours is more inviting, and mine just looks like a barrage of verbiage. But with some judicious spacing and syntax highlighting, I think mine regains IMHO its effectiveness (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(* *drop-first-column-and-reverse-every-row-of* *top-right-quadrant**)* *top-half-of-diamond* *(**join-together-side-by-side* *top-left-quadrant * * top-right-quadrant**)* *bottom-half-of-diamond* *(* *flip-bottom-up-and-drop-first-row-of* *top-half-of-diamond)* *diamond* *(*put-one-on-top-of-the-other *top-half-of-diamond* *bottom-half-of-diamond**)*] even better if I adopt the 'beside' you suggested, and its 'above' counterpart: (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(*
Re: what do you think about this code?
I'm somewhat late to the party, but what the hey - it's a quiet Sunday afternoon, and for my own amusement I came up with: (defn spaces [n] (apply str (take n (repeat . (defn n-a [n] (char (+ n (int \A (defn a-n [a] (- (int a) (int \A))) (defn gap [n] (spaces (dec (* 2 n (defn diamond [c] (let [l (a-n c)] (when (= (a-n \A) l (a-n \Z)) (doseq [i (range l)] (println (str (spaces (- l i)) (n-a i) (gap i) (when-not (zero? i) (n-a i) (println (str c (spaces (dec (* 2 l))) (when-not (= \A c (doseq [i (reverse (range l))] (println (str (spaces (- l i)) (n-a i) (gap i) (when-not (zero? i) (n-a i Normally I'd add a few comments to this code , especially the diamond function - which is at the limit of the density I feel comfortable with. That said - it seems to work. What I find interesting about this is the length of the code compared with the various Java solutions I looked at; looks like Paul Graham was right: http://www.paulgraham.com/power.html -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hi David In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema https://www.google.com/url?q=https%3A%2F%2Fgithub.com%2FPrismatic%2Fschemasa=Dsntz=1usg=AFQjCNFIdJn-v4ShLockO3sVBrwopRZiOQ) to document as well as provide further safety for my functions goes on my todo list Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.joh...@googlemail.com javascript:: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would
Re: what do you think about this code?
David, - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I was influenced by the following passage in Web Development with Clojure: Build Bulletproof Web Apps with Less Code https://pragprog.com/book/dswdcloj/web-development-with-clojure: The project.clj file will allow us to manage many different aspects of our application, as well. For example, we could set the foo function from the myapp.core namespace as the entry point for the application using the *:main *key: (defproject myapp 0.1.0-SNAPSHOT :description FIXME: write description :url http://example.com/FIXME; :license {:name Eclipse Public License :url http://www.eclipse.org/legal/epl-v10.html} :dependencies [[org.clojure/clojure 1.6.0]] ;;this will set foo as the main function *:main *myapp.core/foo) The application can now be run from the command line using lein run. In Java, the entry point to an application is called main, so I thought if the lein entry point for an application is labelled main, and I am in a hurry to get on with the meat of the diamond kata, I'll just call it main for now, and improve it later. But as Kent Beck says: later means never ;-) Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you
Re: what do you think about this code?
David, More generally, I think reasonable people could disagree on naming conventions yes, and on what constitutes clean code, too. I like the viewpoint Robert Martin's offers us in his book Clean Code http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882. Here is my own super-short summary: - What is clean code? - There are probably as many definitions as there are programmers. - Martial artists do not all agree about the best martial art, or the best technique within a martial art. - There are various 'Schools of Thought' - None of them is absolutely right. - But within each School, the teachings and techniques are treated as being right, being absolutes - Over time students may immerse themselves in the teachings of different masters, to broaden their knowledge and practice - At some point they may even found their own school The Clean Code book is Martin's School of Clean Code. It describes the School’s values, principles, practices, patterns, heuristics, etc. Are there books describing functional programming schools of thought? Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim
Re: what do you think about this code?
Hi Colin, Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. Interesting, thanks I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. Yes I am on the fence, and fall down frequently either side (you wouldn't believe the chaffing :)) - Yes, I may soon be in the same position But I also *feel the loss of the info captured in variable names/function names* as well. Yes the more Clojure you write the more you start to realise that the same shapes of functions come up time and time again - the structural shape of the code imparts knowledge sometimes. OK Philip On Saturday, 6 December 2014 18:40:16 UTC, Colin Yates wrote: Excellent question and I will be watching this thread with interest. Similar to David Della Costa, I find a bit difference between Clojure and Java for example is that there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. I am on the fence, and fall down frequently either side (you wouldn't believe the chaffing :)) - the more Clojure I write the more comfortable I am with dense calls to core.clj functions. But I also feel the loss of the info captured in variable names/function names as well. Another point worth mentioning is that the more Clojure you write the more you start to realise that the same shapes of functions come up time and time again - the structural shape of the code imparts knowledge sometimes. As David says, if you haven't looked at Prismatic Schema then have a look. I find the definition of the schema is also an excellent place to capture this extra layer of info in the names of those structures. Good question. On Saturday, 6 December 2014 10:48:02 UTC, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hi Leif, You have the idea of a palindrome in your solution: neat! Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) The broad takeaway is: if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon :). This is somewhat a matter of taste, and again, the requirements history usually determines what gets abstracted into functions, and history can be messy. :) Hope that helps, Leif On Saturday, December 6, 2014 5:48:02 AM UTC-5, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
thanks On Tuesday, 9 December 2014 08:01:58 UTC, Colin Yates wrote: I forgot to mention but https://github.com/bbatsov/clojure-style-guide is a pretty good resource. On 9 Dec 2014 00:24, Philip Schwarz philip.joh...@googlemail.com javascript: wrote: Hello David, I had set myself the constraint that I wanted the solution to exploit two symmetries: (1) The top left and top right of the diamond are mirror images (2) The top half and bottom half of the diamond are also mirror images I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to) I was on a train commuting back home, and what I did was sit in a loop where I wrote some code and then tweaked it until executing it in the REPL gave me the part of the diamond that I wanted, by eyeballing the console output. What a coincidence that in your gist you linked to http://blog.jayfields.com/2014/01/repl-driven-development.html . I was looking at exactly that blog post on Sunday to determine if what I had been doing could be classified as REPL-based? Still not sure. Thoughts? My first version of the code was this https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf: (defn print-diamond [letter] (let [alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ position-of (fn [letter] (inc (- (int letter) (int \A number-of-letters (position-of letter) dashes (fn [n] (repeat n \-)) fixed-text-for (fn [letter] (concat (dashes (dec (position-of letter))) (list letter))) template (map fixed-text-for (take number-of-letters alphabet)) pad-with-trailing-dashes (fn [index line] (concat line (dashes (dec (- number-of-letters index) top-right-quadrant (map-indexed pad-with-trailing-dashes template) top-left-quadrant (map reverse (map rest (take number-of-letters top-right-quadrant))) top-half (map concat top-left-quadrant top-right-quadrant) diamond (concat top-half (drop 1 (reverse top-half)))] (doseq [line (map #(apply str %) diamond)] (println line I showed it to Extreme Programming and Agile Guru Ron Jeffries, and the following conversation ensued: @philip_schwarz 1st stab at Clojure print-diamond using symmetries identified by @TotherAlistair @RonJeffries @gdinwiddie @sebrose https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf @RonJeffries @philip_schwarz *can people read that and figure out what it does? *i can't but not a closure person. @totheralistair @gdinwiddie @sebrose @philip_schwarz @RonJeffries @TotherAlistair @gdinwiddie @sebrose *I like defns of top-half diamond think they r graspable-ish; top-left-quadrant less so* @philip_schwarz one interesting Q for us all is *if one didn't know the prob could one grok the prog* @totheralistair @gdinwiddie @sebrose @gdinwiddie .@RonJeffries I think *the program is generally easier to grok if you've got the tests, too.* @philip_schwarz @TotherAlistair @sebrose @philip_schwarz Dec 3 @gdinwiddie @RonJeffries @TotherAlistair @sebrose agree - I have added tests: https://github.com/philipschwarz/diamond-problem-in-clojure/blob/master/test/diamond_problem_in_clojure/core_test.clj I notice you did not write tests. I also notice that you added comments to your methods. I like your comments. Find them useful. I am not saying the following applies to your comments, but it will give you an idea of the programming culture I am part of. In that culture, comments are looked at with suspicion: e.g. 1: https://twitter.com/nzkoz/status/538892801941848064 https://pbs.twimg.com/media/B3qIJLFCcAEJLWm.jpg e.g. 2: The proper use of comments is to compensate for our failure to express ourself in code. - Robert C. Martin e.g. 3: Comments often are used as a deodorant... often comments are there because the code is bad. - Martin Fowler e.g. 4: - Primary Rule: Comments are for things that *cannot* be expressed in code. - Redundancy Rule: Comments which restate code must be deleted. - Single Truth Rule: If the comment says what the code *could* say, then the code must change to make the comment redundant. In that culture, we aim to use certain implementation patterns that make comments unnecessary. Also, where possible, the tests act as (executable, more reliable) documentation. Moving on, after writing the terse first version of the code, I set out to *make my code more readable*. Are you familiar with Robert Martin's dictum?: The Three Functions of a s/w module: * The function it performs while executing * To afford change. A module that is difficult to change is broken and needs fixing, even though it works * *To communicate to its readers. A module that does not communicate is broken and needs fixing.* The rationale for making code more readable is an economic one. Here is a brief summary of Ken't Beck's thoughts on the
Re: what do you think about this code?
Hi Leif, what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. ...the difference between maintainable and easily maintainable depends on predicting the future somewhat. There are interesting views on the subject in Agile and Extreme Programming. Have you heard of Extreme Programming's YAGNI principle: You Ain't Gonna Need It http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it In Refactoring http://www.informit.com/articles/article.aspx?p=1400866seqNum=13, Martin Fowler has a code smell called *Speculative Generality*: You get it when people say, Oh, I think we need the ability to this kind of thing someday and thus want all sorts of hooks and special cases to handle things that aren't required. The result often is harder to understand and maintain. If all this machinery were being used, it would be worth it. But if it isn't, it isn't. The machinery just gets in the way, so get rid of it. In ASD:PPP http://www.amazon.co.uk/Software-Development-Principles-Patterns-Practices/dp/0132760584 Robert Martin has a Design Smell called *Needless Complexity* A design smells of needless complexity when it contains elements that aren't currently useful. This frequently happens when developers anticipate changes to the requirements and put facilities in the software to deal with those potential changes. At first, this may seem like a good thing to do. After all, preparing for future changes should keep our code flexible and prevent nightmarish changes later. Unfortunately, the effect is often just the opposite. By preparing for many contingencies, the design becomes littered with constructs that are never used. Some of those preparations may pay off, but many more do not. Meanwhile, the design carries the weight of these unused design elements. This makes the software complex and difficult to understand. I already mentioned elsewhere in the thread that according to Kent Beck, - cost(total) = cost(develop) + cost(maintain) - cost(maintain) = cost(understand) + cost(change) + cost(test) + cost(deploy) - learning what the current code does is the expensive part So his strategy for reducing overall costs is to *ask all programmers to address the cost of understanding code during the maintenance phase by focusing on communicating, programmer-to-programmer, i.e. writing clear code.* Those ideas are from Implementation Patterns http://www.amazon.co.uk/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091. In the same book Beck has has an interesting section on flexibility: ...flexibility is the justification used for the most ineffective coding and design practices. e.g. ... Why all the complexity? Flexibility. Programs should be flexible, but only in ways they change. If ... never changes, all that complexity is cost without benefit. Since most of the cost of a program will be incurred after it is first deployed, programs should be easy to change. *The flexibility I imagine will be needed tomorrow, though, is likely to be not what I need when I change the code*. That's why *the flexibility of simplicity and extensive tests is more effective than the flexibility offered by speculative design.* *Choose patterns that encourage flexibility and bring immediate benefits. For patterns with immediate costs and only deferred benefits, often patience is the best strategy.* Put them back in the bag until they are needed. Then you can apply them in precisely the way they are needed. Flexibility can come at the cost of increased complexity. For instance, ... Simplicity can encourage flexibility. In the above example, if you can find a way to eliminate ... without losing value, you will have a program that is easier to change later. *Enhancing the communicability of software also adds to flexibility. The more people who can quickly read, understand, and modify the code, the more options your organization has for future change.* The patterns in Beck's book encourage flexibility by helping programmers create simple, understandable applications that can be changed Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different
Re: what do you think about this code?
Hi Colin, there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. yes, it seems to me that often (always maybe?) functional code speaks a lot about HOW, and not much about WHAT A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. Yes, that method was introduced by an application of the Explaining Message pattern. Here is how Kent Beck describes the pattern in Implementation Patterns http://www.amazon.com/Implementation-Patterns-Kent-Beck/dp/0321413091: The first example I saw of this was in Smalltalk. Transliterated [into Java], the method that caught my eye was this: *Explaining Message*The distinction between intention and implementation has always been important in software development. It is what allows you to understand a computation first in essence and later, if necessary, in detail. You can use messages to make this distinction by sending a message named after the problem you are solving which in turn sends a message named after how the problem is to be solved. highlight(Rectangle area) { reverse(area); } I thought, “Why is this useful? Why not just call reverse() directly instead of calling the intermediate highlight() method?” After some thought, though, I realized that while highlight() didn’t have a computational purpose, it did serve to communicate an intention. Calling code could be written in terms of what problem they were trying to solve, namely highlighting an area of the screen. Consider introducing an explaining message when you are tempted to comment a single line of code. When I see: flags|= LOADED_BIT; // Set the loaded bit I would rather read: setLoadedFlag(); Even though the implementation of setLoadedFlag() is trivial. The one-line method is there to communicate. void setLoadedFlag() { flags|= LOADED_BIT; } Sometimes the helper methods invoked by explaining messages become valuable points for further extension. It’s nice to get lucky when you can. However, my main purpose in invoking an explaining message is to communicate my intention more clearly. And here is a summary of how Beck originally described the pattern in Smalltalk Best Practice Patterns http://www.amazon.co.uk/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X : - How do you communicate your intent when the implementation is simple? - Probably the most frustrating part of learning Smalltalk - You see a message like highlight and think: this has to be something interesting ParagraphEditorhighlight:aRectangle self reverse:aRectangle - What is going on? Communication. Most importantly, one line methods are there to communicate. - Explaining Messages are the most extreme case of writing for readers instead of the computer - How do you communicate your intent when the implementation is simple? - Send a message to “self”. Name the message so that it communicates what is to be done rather than how it is to be done. Code a simple method for the message. - Three examples: CollectionisEmpty ^self size = 0 Numberreciprocal ^1 / self Object=anObject ^self == anObject My program constructs the diamond by putting the top half of the diamond on top of the bottom half. The implementation is simple: the top and bottom parts are sequences that just need to be concatenated. But the implementation is a detail, and may even change one day, so I encapsulate it behind Explaining Message put-one-on-top-of-the-other. Explaining Message allows us to separate intention (the WHAT) from implementation (the HOW): the method name tells us WHAT, and the method body tell us HOW. Is the distinction between intention and implementation considered unimportant, or not so important in functional programming? Philip On Saturday, 6 December 2014 18:40:16 UTC, Colin Yates wrote: Excellent question and I will be watching this thread with interest. Similar to David Della Costa, I find a bit difference between Clojure and Java for example is that there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the
Re: what do you think about this code?
That's right - idiomatic functional programming is very declarative (from what I gather). Thanks for the references, and yes, I had recognised the motivation that ;). You ask Is the distinction between intention and implementation considered unimportant, or not so important in functional programming? and I think the answer (at least my answer) is no, not at all, not in anyway, absolutely not :). The difference is that intention is often hidden behind a whole bunch of incidental complexity that Clojure (due to its higher level abstractions) just doesn't seem to have. When you have 40 lines of code to filter something, sort it and then transform the results, the message of what it is trying to achieve gets lost. When that same implementation is as elegant as (- col (filter my-pred) (sort-by :my-key) (map #(...)) then the HOW is right there. At worst you might have (defn do-it [col] (letfn [(interesting? [x] ) (sort-criteria [x] ...) (transformer [x] )] (- col (filter interesting?) (sort-by sort-criteria) (map transformer))) or (defn- interesting? [x]...) (defn- sort-criteria? [x]...) (defn- transformer [x]...) (defn do-it [col] (- col (filter interesting?) (sort-by sort-criteria) (map transformer)) The reason that do-it exists and is the right thing to do (i.e. the WHAT or the WHY)? Again, in Clojure, I don't know why (other than the reasons already given) but it is much easier to group related things together, so the domain those things are working in, the implicit objective of the cohesive group of function is transparent. In Java, if you stick to small classes then you tend to end up with a whole bunch of classes whose inter-relationship isn't particularly clear. Package names help but then you end up with very deep hierarchies. In Clojure, because of the brevity it feels less icky to have ns's with many more defs than the number of methods you would expect in a class, or indeed the number of classes in a package. It isn't unusual to find sub-groups within a ns, typically demarcated by a string of semi-colons: (ns ) ; ;; - some logical group (defn- ..) (defn- ..) (defn ..) ; ;; - some other logically cohesive group (defn- ..) (defn- ..) (defn ..) In summary, as David and I have said - good design is good design, the characteristics of which cross OO and FP (even things like immutability being good). The barriers to achieving that good design are local to every paradigm and then every implementation language. For me, Clojure opened my eyes to exactly how many best practices (particularly design patterns) were addressing incidental complexity. I dunno - it is all subjective and I am still working this out in my head (turns out a year isn't quite enough to kill decades of viewing the world through OO thinking ;)). I frequently cringe when I look at Clojure code I wrote a month ago. I am not sure the process of yeah, that is good, wait some period of time, wow, that is terrible, let me replace those 10 lines with a call to a few core APIs will ever end, and nor should it. As Dr Eli Goldratt said, Never say I know (https://www.toc-goldratt.com/tocweekly/2011/06/never-say-i-know-eli-goldratts-latest-development/). On 13 December 2014 at 08:43, Philip Schwarz philip.johann.schw...@googlemail.com wrote: Hi Colin, there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. yes, it seems to me that often (always maybe?) functional code speaks a lot about HOW, and not much about WHAT A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. Yes, that method was introduced by an application of the Explaining Message pattern. Here is how Kent Beck describes the pattern in Implementation Patterns: The first example I saw of this was in Smalltalk. Transliterated [into Java], the method that caught my eye was this: Explaining Message The distinction between intention and implementation has always been important in software development. It is what allows you to understand a computation first in essence and later, if necessary, in detail. You can use messages to make this distinction by sending a message named after the problem you are solving which in turn sends a message named after how the problem is to be solved. highlight(Rectangle area) { reverse(area); } I thought, “Why is this useful? Why not just call reverse() directly
Re: what do you think about this code?
David, - Stylistically, I found your naming conventions to be too verbose yes, in the programming culture I am part of, long names are not frowned upon when they help reveal intent. I like the following diagram that J.B Rainsberger has put together on the process of improving names: http://assets.jbrains.ca/ImprovingNames.pdf As you can see, he reckons that as names improve (become more precise, more intention-revealing, etc), they become longer. I also notice that he identifies a phase in the improvement process, when names are vague, i.e. imprecise, not intention-revealing, etc, e.g. 'compute', 'process', 'execute', 'calculate'. I think there may be a parallel between the vagueness of those names, and the vagueness of names like e.g. map, reduce, concatenate, reverse, compared to the names that they get hidden behind, when they are treated as implementation details in applications of Explaining Message, e.g. (defn *put-one-on-top-of-the-other* [top-half-of-diamond bottom-half-of-diamond] (*concat* top-half-of-diamond bottom-half-of-diamond)) By the way, I can fully understand why you might object to introducing the above method. I am conscious of the fact that a lot of people will find applications of Explaining Message extreme. As Kent Beck says: Explaining Messages are the most extreme case of writing for readers instead of the computer. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going
Re: what do you think about this code?
Hi Leif, if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon So your motivation for the Extract Method http://refactoring.com/catalog/extractMethod.html refactoring is sharing of logic. There are others. My motivation in this exercise was to separate intention from implementation. Here is Kent Beck in an excerpt from Refactoring: Improving the Design of Existing Code http://www.amazon.co.uk/Refactoring-Improving-Design-Existing-Technology/dp/0201485672: Given software engineers' infatuation with indirection, it may not surprise you to learn that most refactoring introduces more indirection into a program. Refactoring tends to break big objects into several smaller ones and big methods into several smaller ones. Indirection is a two-edged sword, however. Every time you break one thing into two pieces, you have more things to manage. It also can make a program harder to read as an object delegates to an object delegating to an object. So you'd like to minimize indirection. Not so fast, buddy. Indirection can pay for itself. Here are some of the ways. - *To enable sharing of logic. *For example, a submethod invoked in two different places or a method in a superclass shared by all subclasses. - *To explain intention and implementation separately.* Choosing the name of each class and the name of each method gives you an opportunity to explain what you intend. The internals of the class or methodexplain how the intention is realized. If the internals also are written in terms of intention in yet smaller pieces, you can write code that communicates most of the important information about its own structure. - *To isolate change.* I use an object in two different places. I want to change the behavior in one of the two cases. If I change the object, I risk changing both. So I first make a subclass and refer to it in the case that is changing. Now I can modify the subclass without risking an inadvertent change to the other case. - *To encode conditional logic. *Objects have a fabulous mechanism, polymorphic messages, to flexibly but clearly express conditional logic. By changing explicit conditionals to messages, you can often reduce duplication, add clarity, and increase flexibility all at the same time. Here is the refactoring game: Maintaining the current behavior of the system, how can you make your system more valuable, either by increasing its quality or by reducing its cost? The most common variant of the game is to look at your program. Identify a place where it is missing one or more of the benefits of indirection. Put in that indirection without changing the existing behavior. Now you have a more valuable program because it has more qualities that we will appreciate tomorrow. Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) The broad takeaway is: if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon :). This is somewhat a matter of taste, and again, the requirements history usually determines what
Re: what do you think about this code?
Hi Leif, I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. yes, in the programming culture I am part of, method extraction is quite aggressive. Here is Martin Fowler on the subject (in Refactoring, Improving the Design of Existing Code http://martinfowler.com/books/refactoring.html): You should be much more aggressive about decomposing methods. A heuristic we follow is that whenever we feel the need to comment something, we write a method instead. Such a method contains the code that was commented, but is *named after the intention of the code rather than how it does it*. We may do this on a group of lines or on as little as a single line of code. We do this even if the method call is longer than the code it replaces, *provided the method name explains the purpose of the code*. *The key here is not method length but the semantic distance between what the method does and how it does it.* I accept that that extraction of the following method is pretty aggressive: (defn reverse-every-row [sequence-of-sequences-of-chars] (map reverse sequence-of-sequences-of-chars)) What I am trying to find out is if this sort of practice is (or will ever be) used, or it use at least contemplated, by functional programmers. By the way, I guess if this was Scala then the overlong parameter name might be replaced with a something like 'rows : Seq[Seq[Char]]' Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) The broad takeaway is: if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon :). This is somewhat a matter of taste, and again, the requirements history usually determines what gets abstracted into functions, and history can be messy. :) Hope that helps, Leif On Saturday, December 6, 2014 5:48:02 AM UTC-5, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hi Leif, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers flip: which way? flip-vertically: yes, that may be good enough after all. I went for flip-bottom-up because I didn't want the reader to have to ask themselves: what does he mean by vertical flip? e.g. if you search google images for vertical flip you get both of the following images: https://lh5.googleusercontent.com/-dNAVKelygfo/VI0pMSemS9I/AOQ/J5fLWi_ACzI/s1600/Screen%2BShot%2B2014-12-14%2Bat%2B06.05.19.png https://lh5.googleusercontent.com/-HH-ZnujIaHM/VI0o_hOJQ9I/AOI/BrM10DB97Mc/s1600/Screen%2BShot%2B2014-12-14%2Bat%2B06.05.10.png beside: genius! that is what I looked for, but could not come up with. stack: yes, that was my first choice, but then I worried that a foreign reader might not be familiar with the word (which I don't hear that often), or that a developer might think about FILO, etc. I think I did consider 'above' (in the vein of your 'beside'), but discarded it. I think put-one-on-top-of-the-other is pretty irritating in some respects. I can see beside and above working well. Thanks, Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hi Leif, if I compare your suggestion (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) with mine (let [top-right-quadrant (create-top-right-quadrant-for letter) top-left-quadrant (drop-first-column-and-reverse-every-row-of top-right-quadrant) top-half-of-diamond (join-together-side-by-side top-left-quadrant top-right-quadrant) bottom-half-of-diamond (flip-bottom-up-and-drop-first-row-of top-half-of-diamond) diamond (put-one-on-top-of-the-other top-half-of-diamond bottom-half-of-diamond)] yours is more inviting, and mine just looks like a barrage of verbiage. But with some judicious spacing and syntax highlighting, I think mine regains IMHO its effectiveness (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(* *drop-first-column-and-reverse-every-row-of* *top-right-quadrant**)* *top-half-of-diamond* *(**join-together-side-by-side* *top-left-quadrant * * top-right-quadrant**)* *bottom-half-of-diamond* *(**flip-bottom-up-and-drop-first-row-of* *top-half-of-diamond)* *diamond* *(*put-one-on-top-of-the-other *top-half-of-diamond* *bottom-half-of-diamond**)*] even better if I adopt the 'beside' you suggested, and its 'above' counterpart: (let [*top-right-quadrant **(**create-top-right-quadrant-for * *letter**)* *top-left-quadrant * *(* *drop-first-column-and-reverse-every-row-of* *top-right-quadrant**)* *top-half-of-diamond* *(**beside* *top-left-quadrant * *top-right-quadrant**)* *bottom-half-of-diamond* *(**flip-bottom-up-and-drop-first-row-of* *top-half-of-diamond)* *diamond* *(*above *top-half-of-diamond* *bottom-half-of-diamond**)*] Do you see the value of hiding the HOW at all? Imagine if this was something more complicated, e.g. a financial application: wouldn't you be thankful for being spared the detail of HOW things are implemented until that time when you consider it useful to understand it? We talked elsewhere in this thread of separating intention from implementation by using the Extract Method refactoring and implementation patterns like Composed Method, Intention Revealing Method Name, Explaining Message, etc. But the above code also highlights that other simple technique we can use to separate WHAT from HOW: the Introduce Explaining Variable refactoring (http://c2.com/cgi/wiki?IntroduceExplainingVariable - AKA Extract Variable http://refactoring.com/catalog/extractVariable.html). Instead of forcing the reader to deal with the whole of a non-trivial expression which is all about the HOW, we can factor out one or more sub-expressions and give them a name that says WHAT the expression(s) do. In your 'let', you have two explaining variables, whereas I have four. Do you see the value of hiding the HOW in this way? Philip On Tuesday, 9 December 2014 05:06:22 UTC, Leif wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right))
Re: what do you think about this code?
HI David, - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. Makes perfect sense: isolating your pure functions from your side-effecting code as a sort of basic separation What do you mean by this: , and avoid monolithic functions like the one I linked to above. . I ask because I think there are no side effects in my code. Maybe I don't understand because it is 4.30 am and I am not fully awake, or maybe you intend a different meaning for side effect. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your
Re: what do you think about this code?
Hi David, a style like I used in my solution which aims for readable conciseness When I first looked at your code, just quickly scanning it, I felt that it was nice and concise, but I find parameter names like 'len' and 'idx' terse rather than concise. In Venkat Subramaniam's words (in Functional Programming in Java https://pragprog.com/book/vsjava8/functional-programming-in-java) *Does concise just mean less code?* Concise is short, devoid of noise, and boiled down to its essence to convey the intent effectively. The benefits are far reaching. Writing code is like throwing ingredients together; making it concise is like turning that into a sauce. It often takes more effort to write concise code. It’s less code to read, but effective code is transparent. A short code listing that’s hard to understand or hides details is terse rather than concise. I think 'len' and 'idx' are terse (fewer characters), but not concise. Every time I read them I can't help translating them into 'length' and 'index'. This is annoying, especially with 'idx' (with 'len' it is not too bad). This translation process is somewhat similar to what Robert Martin calls mental mapping (in Clean Code http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 ): *Avoid Mental Mapping*Readers shouldn't have to mentally translate your names into other names they already know... Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style,
Re: what do you think about this code?
Hi Dave, I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. the problem I set myself was not to find a/the natural way to work, or to write as little code as possible, but to write a Clojure program that builds a diamond by exploiting the symmetries present in diamonds, in the sense that the program first builds a part of the diamond, and then builds other parts by transforming existing parts using the idea of mirror images. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure!
Re: what do you think about this code?
Hi David, - Stylistically, I found your naming conventions to be too verbose Do you mean you find the method and variable names too long? Here was my first attempt at the diamond kata in Clojure (written in 40 minutes during a commute) (defn print-diamond [letter] (let [alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ position-of (fn [letter] (inc (- (int letter) (int \A number-of-letters (position-of letter) dashes (fn [n] (repeat n \-)) fixed-text-for (fn [letter] (concat (dashes (dec (position-of letter))) (list letter))) template (map fixed-text-for (take number-of-letters alphabet)) pad-with-trailing-dashes (fn [index line] (concat line (dashes (dec (- number-of-letters index) top-right-quadrant (map-indexed pad-with-trailing-dashes template) top-left-quadrant (map reverse (map rest (take number-of-letters top-right-quadrant))) top-half (map concat top-left-quadrant top-right-quadrant) diamond (concat top-half (drop 1 (reverse top-half)))] (doseq [line (map #(apply str %) diamond)] (println line Do you find that concise? Do you find it readable? Ron Jeffries' reaction to that was: can people read that and figure out what it does? i can't but not a closure person I thought one reason why people might find it difficult to read it is that they are confronted with a lot of detail about HOW the code is solving the problem, rather than WHAT the code is doing. So what I did is take the above code and have a go at making it more understandable by rewriting it using the following implementation patterns: Decomposing Message, Composed Method, Intention Revealing Method, Explaining Message. With these patterns, we arrange the code so the the reader is mostly confronted with the WHAT rather than the HOW. Using the patterns in procedural and OO languages works well. I wanted to see if they work in functional programming languages. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as
Re: what do you think about this code?
Philip, one clarification--re: function with side-effects, I meant to link here, which I followed up with in a later post, but I think it got lost in the shuffle: https://github.com/philipschwarz/diamond-problem-in-clojure/blob/7efbc472632dced5e173084672ad76687e39dd1f/src/diamond_problem_in_clojure/core.clj#L68-L74 The function print-diamond is both generating the diamond data structure (which is just a series of pure functions) but then at the end it prints out the diamond via display--this is a side effect. The function itself returns nil. So my point was that I would prefer a separate pure function to handle generating the entire diamond, which would return that data structure at the end. Then I could use this in conjunction with a side-effecting function to print, to save to a file, etc. Dave 2014-12-13 13:40 GMT+09:00 Philip Schwarz philip.johann.schw...@googlemail.com: HI David, - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. Makes perfect sense: isolating your pure functions from your side-effecting code as a sort of basic separation What do you mean by this: , and avoid monolithic functions like the one I linked to above. . I ask because I think there are no side effects in my code. Maybe I don't understand because it is 4.30 am and I am not fully awake, or maybe you intend a different meaning for side effect. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code
Re: what do you think about this code?
I think reasonable people can disagree on the details here--I think the names I chose were good enough and would be understood by Clojure programmers familiar with the standard data structures and core functions. I should point out that some of these names are conventional in Clojure land, for example idx: https://clojuredocs.org/clojure.core/map-indexed, https://clojuredocs.org/clojure.core/amap, etc. DD 2014-12-13 15:00 GMT+09:00 Philip Schwarz philip.johann.schw...@googlemail.com: Hi David, a style like I used in my solution which aims for readable conciseness When I first looked at your code, just quickly scanning it, I felt that it was nice and concise, but I find parameter names like 'len' and 'idx' terse rather than concise. In Venkat Subramaniam's words (in Functional Programming in Java https://pragprog.com/book/vsjava8/functional-programming-in-java) *Does concise just mean less code?* Concise is short, devoid of noise, and boiled down to its essence to convey the intent effectively. The benefits are far reaching. Writing code is like throwing ingredients together; making it concise is like turning that into a sauce. It often takes more effort to write concise code. It’s less code to read, but effective code is transparent. A short code listing that’s hard to understand or hides details is terse rather than concise. I think 'len' and 'idx' are terse (fewer characters), but not concise. Every time I read them I can't help translating them into 'length' and 'index'. This is annoying, especially with 'idx' (with 'len' it is not too bad). This translation process is somewhat similar to what Robert Martin calls mental mapping (in Clean Code http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882 ): *Avoid Mental Mapping*Readers shouldn't have to mentally translate your names into other names they already know... Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one
Re: what do you think about this code?
I forgot to mention but https://github.com/bbatsov/clojure-style-guide is a pretty good resource. On 9 Dec 2014 00:24, Philip Schwarz philip.johann.schw...@googlemail.com wrote: Hello David, I had set myself the constraint that I wanted the solution to exploit two symmetries: (1) The top left and top right of the diamond are mirror images (2) The top half and bottom half of the diamond are also mirror images I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to) I was on a train commuting back home, and what I did was sit in a loop where I wrote some code and then tweaked it until executing it in the REPL gave me the part of the diamond that I wanted, by eyeballing the console output. What a coincidence that in your gist you linked to http://blog.jayfields.com/2014/01/repl-driven-development.html . I was looking at exactly that blog post on Sunday to determine if what I had been doing could be classified as REPL-based? Still not sure. Thoughts? My first version of the code was this https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf: (defn print-diamond [letter] (let [alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ position-of (fn [letter] (inc (- (int letter) (int \A number-of-letters (position-of letter) dashes (fn [n] (repeat n \-)) fixed-text-for (fn [letter] (concat (dashes (dec (position-of letter))) (list letter))) template (map fixed-text-for (take number-of-letters alphabet)) pad-with-trailing-dashes (fn [index line] (concat line (dashes (dec (- number-of-letters index) top-right-quadrant (map-indexed pad-with-trailing-dashes template) top-left-quadrant (map reverse (map rest (take number-of-letters top-right-quadrant))) top-half (map concat top-left-quadrant top-right-quadrant) diamond (concat top-half (drop 1 (reverse top-half)))] (doseq [line (map #(apply str %) diamond)] (println line I showed it to Extreme Programming and Agile Guru Ron Jeffries, and the following conversation ensued: @philip_schwarz 1st stab at Clojure print-diamond using symmetries identified by @TotherAlistair @RonJeffries @gdinwiddie @sebrose https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf @RonJeffries @philip_schwarz *can people read that and figure out what it does? *i can't but not a closure person. @totheralistair @gdinwiddie @sebrose @philip_schwarz @RonJeffries @TotherAlistair @gdinwiddie @sebrose *I like defns of top-half diamond think they r graspable-ish; top-left-quadrant less so* @philip_schwarz one interesting Q for us all is *if one didn't know the prob could one grok the prog* @totheralistair @gdinwiddie @sebrose @gdinwiddie .@RonJeffries I think *the program is generally easier to grok if you've got the tests, too.* @philip_schwarz @TotherAlistair @sebrose @philip_schwarz Dec 3 @gdinwiddie @RonJeffries @TotherAlistair @sebrose agree - I have added tests: https://github.com/philipschwarz/diamond-problem-in-clojure/blob/master/test/diamond_problem_in_clojure/core_test.clj I notice you did not write tests. I also notice that you added comments to your methods. I like your comments. Find them useful. I am not saying the following applies to your comments, but it will give you an idea of the programming culture I am part of. In that culture, comments are looked at with suspicion: e.g. 1: https://twitter.com/nzkoz/status/538892801941848064 https://pbs.twimg.com/media/B3qIJLFCcAEJLWm.jpg e.g. 2: The proper use of comments is to compensate for our failure to express ourself in code. - Robert C. Martin e.g. 3: Comments often are used as a deodorant... often comments are there because the code is bad. - Martin Fowler e.g. 4: - Primary Rule: Comments are for things that *cannot* be expressed in code. - Redundancy Rule: Comments which restate code must be deleted. - Single Truth Rule: If the comment says what the code *could* say, then the code must change to make the comment redundant. In that culture, we aim to use certain implementation patterns that make comments unnecessary. Also, where possible, the tests act as (executable, more reliable) documentation. Moving on, after writing the terse first version of the code, I set out to *make my code more readable*. Are you familiar with Robert Martin's dictum?: The Three Functions of a s/w module: * The function it performs while executing * To afford change. A module that is difficult to change is broken and needs fixing, even though it works * *To communicate to its readers. A module that does not communicate is broken and needs fixing.* The rationale for making code more readable is an economic one. Here is a brief summary of Ken't Beck's thoughts on the matter: o Economics is the underlying driver of software design o Software should be designed to reduce its overall
Re: what do you think about this code?
Identifying the requirements for maintainable is the key and as far as I know we as a software industry aren't close to solving it. Whilst programs are written by those bags opinionated, subjective and finicky bags of water known as people it will also be elusive as maintenance has to be at least easy to the current skill set. And that is the crux of the problem - easy changes over time based on resource, market trends, flavour of the month, corporate policy etc. I think there are some excellent resources to help; Rich Hickey's Simple made easy, SOLID, DDD and so on, but in the large, nope. The closest solution I have seen is in those large corporate enterprises where everything is nailed down. In other words, maintainability and creativity are in a very unhelpful inverse relationship. Oh, and as you say the fact nobody knows exactly what they meant until they have seen what you have built :). In terms of REPL and TDD, I find a really interesting property in my code, which may just be because I have been missing the point for the last decade of TDD (I know some people will claim that ;)), but I find that TDD can produce code that is very normalised to the problem at hand, where-as REPL driven code may be more generic and expressive of the problem domain. I find that sometimes REPL driven code contains more helpful context where-as TDD code can produce almost the minimal amount of code to solve a given problem. As I say, this is more to do with my particular style, but I would be interested if others found that. On 9 Dec 2014 05:06, Leif leif.poor...@gmail.com wrote: Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) The broad takeaway is: if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon :). This is somewhat a matter of taste, and again, the requirements history usually determines what gets abstracted into functions, and history can be messy. :) Hope that helps, Leif On Saturday, December 6, 2014 5:48:02 AM UTC-5, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to a topic in the Google Groups Clojure group. To unsubscribe from this topic, visit https://groups.google.com/d/topic/clojure/zR5Ny7aoBM0/unsubscribe. To unsubscribe from this group and all its topics, send an email to
Re: what do you think about this code?
picking up from my e-mail below... In Smalltalk Best Practice Patterns http://www.amazon.co.uk/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X (STBPP) Kent Beck describes a 'good programming' style guide, a system or language of 92 patterns. Five of them stand out as being: - Fundamental – key to achieving good style - Interrelated – they form their own subsystem - Very simply stated – but have far reaching effects Here are some basic slides I put together on these five patterns: https://lh4.googleusercontent.com/-bejlDZw4H50/VIdxKZOHTsI/ANE/7QfdiJsqAYY/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.55.55.png === https://lh3.googleusercontent.com/-P8AyATDblt0/VIdxTwxcnBI/ANM/t1JCk6BgMUY/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.09.png === https://lh5.googleusercontent.com/-EMibDIQA6dk/VIdxv9YO6nI/ANU/4J98YeGMqSQ/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.21.png === https://lh6.googleusercontent.com/-OXoEpnjXllI/VIdx9sQgfyI/ANc/GUVyOsp9SZ8/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.32.png === https://lh5.googleusercontent.com/-fM7PwQFOyFM/VIdyGv53KxI/ANk/MS9UM2ODQMc/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.44.png === If you find these slides insufficient, I have a whole presentation on the five patterns here https://github.com/philipschwarz/presentations/blob/master/Four%20Patterns%20at%20the%20Heart%20of%20Good%20Programming%20Style.pdf?raw=true (make sure you read the notes for each slide, otherwise you'll just see eye candy). The key about Intention Revealing Method is that instead of getting you to name a method after “how” it accomplishes its task, it gets you to name the method after “what” it is supposed to accomplish, and to leave “how” to the method's body. The effort of moving the name of methods from “how” to “what” is worth it, both in the short term and the long term. The resulting code will be easier to read and understand. A Composed Method is a small, simple method that you can understand in seconds. When you can't rapidly understand a method's logic, transform the logic into a small number of intention-revealing steps at the same level of detail. The key about Composed method is that although it is true that a Composed Method's name communicates what it does, while its body communicates how it does what it does (which is usually what slows down readers), it consists purely or primarily of calls to methods with Intention Revealing names, and so it actually reveals only a little bit of the ‘how’, hiding the rest behind said calls. So composed method reveals implementation (how) only a little bit at a time (which is what makes reading and understanding composed methods so easy/quick). I found this fact mentioned in Alan Shalloway’s (et al.) ‘Essential Skills For The Agile Developer’ (chapter 1 Programming by Intention http://www.netobjectives.com/system/files/essential-skills-programming-by-intention.pdf ). The four patterns we have looked at are part of what in Extreme Programming is called Intentional Programming. The key organizing principle in (composed) methods written in the Intentional Programming style is that their body contains all the steps (the what), but very little of the actual implementation (the how). What Intentional Programming (and composed method) do is allow us to *separate the process by which something is done from the actual accomplishing of the thing.* And here is a good example of composed method from the book: https://lh6.googleusercontent.com/-JhpDq75d_0k/VId5_XHhOmI/AN0/Gc8RGKL6TCU/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B22.38.13.png We can clearly see the focus on the WHAT, and the minimal amount of HOW that the method reveals: this is what makes the method easy to quickly read and understand. So, https://github.com/philipschwarz/diamond-problem-in-clojure/blob/master/src/diamond_problem_in_clojure/core.clj is the result of refactoring https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf to a style informed by the five patterns described above. Is this separation of WHAT from HOW something that is practiced in the Clojure community? The separation of WHAT from HOW seems to have a parallel in the [design by] *wishful thinking* approach described in the following section of the LISP bible, Structure and Interpretation of Computer Programs: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-14.html#%_idx_1306 Philip On Tuesday, 9 December 2014 00:24:42 UTC, Philip Schwarz wrote: Hello David, I had set myself the constraint that I wanted the solution to exploit two symmetries: (1) The top left and top right of the diamond are mirror images (2) The top half and bottom half of the diamond are also mirror images
Re: what do you think about this code?
That sounds interesting, but ... either disable all the security in my browser or download a 50 megabyte pdf? Ouch. :( -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Nice presentation (although I didn't see anything about comments. ?.). As I mentioned before, there seem to be significantly less examples of capturing semantic knowledge in names. I think a significant reason is the higher level abstractions you get to play with in FP and Clojure. This leads to a much smaller set of idiomatic solutions to common problems, or to put it another way, I frequently found my journey from OO to FP paved with large chunks of handwritten code which were then reduced with clojure.core functions. The composition of those core functions were then replaced by other existing functions. At the end you frequently realise that what required lots of custom code in Java (for example) could be expressed incredibly succinctly just using the core API. The succinctness of Clojure compared to Java is also important as those 4 lines of Clojure might well be 20 or so lines of Java. The other significant fact I think is the lack of ceremony in capturing data models. The vehicle is usually just a map, but I have noticed a significant reduction in the things I want to model. The number of types I have is much smaller in Clojure than java (or groovy or scala etc.). To put it another way, looking back I can see in some of my old projects a non-trivial amount of incidental complexity which just isnt there in the Clojure implementations. For me, a large part of getting Clojure was realising that it already has its own ubiquitous language and where as in java most problems were unique (or at least ended up with uniqueish implementations), in Clojure most problems can be expressed in terms of a few powerful abstractions. Intention revealing happens because of the sufficiency of the core API/abstractions. Somebody once wrote something along the lines of if you end up writing your own Clojure code you are probably doing it wrong. :). I wouldn't call myself a Clojurian (because of experience, but that not withstanding i don't think I would ever call myself that:)) but it wouldn't surprise me if the claim was made that all of those long labels actually made it less maintainable as they just got in the way of allowing the natural shapes to emerge. Don't get me wrong, in OO land I write code very close to that so I am not challenging the merit, merely suggesting it is solving a problem that isn't so prevelant and isn't the best solution to that problem. In summary, I at least have found Clojure has a much higher signal to noise ratio, provides a much larger set of design paterns if you will (or has many more idiomatic solutions than Java), and can provide a significant reduction in incidental complexity, thus reducing the problem that some of these approaches are solving. (It is late in the UK and I hate typing on a tablet horizontally so I hope that made sense! ;)). On 9 Dec 2014 22:56, Philip Schwarz philip.johann.schw...@googlemail.com wrote: picking up from my e-mail below... In Smalltalk Best Practice Patterns http://www.amazon.co.uk/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X (STBPP) Kent Beck describes a 'good programming' style guide, a system or language of 92 patterns. Five of them stand out as being: - Fundamental – key to achieving good style - Interrelated – they form their own subsystem - Very simply stated – but have far reaching effects Here are some basic slides I put together on these five patterns: https://lh4.googleusercontent.com/-bejlDZw4H50/VIdxKZOHTsI/ANE/7QfdiJsqAYY/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.55.55.png === https://lh3.googleusercontent.com/-P8AyATDblt0/VIdxTwxcnBI/ANM/t1JCk6BgMUY/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.09.png === https://lh5.googleusercontent.com/-EMibDIQA6dk/VIdxv9YO6nI/ANU/4J98YeGMqSQ/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.21.png === https://lh6.googleusercontent.com/-OXoEpnjXllI/VIdx9sQgfyI/ANc/GUVyOsp9SZ8/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.32.png === https://lh5.googleusercontent.com/-fM7PwQFOyFM/VIdyGv53KxI/ANk/MS9UM2ODQMc/s1600/Screen%2BShot%2B2014-12-09%2Bat%2B21.56.44.png === If you find these slides insufficient, I have a whole presentation on the five patterns here https://github.com/philipschwarz/presentations/blob/master/Four%20Patterns%20at%20the%20Heart%20of%20Good%20Programming%20Style.pdf?raw=true (make sure you read the notes for each slide, otherwise you'll just see eye candy). The key about Intention Revealing Method is that instead of getting you to name a method after “how” it accomplishes its task, it gets you to name the method after “what” it is supposed to accomplish, and to leave “how” to the method's body. The effort of moving the name of methods from “how” to “what” is worth it, both in
Re: what do you think about this code?
Hi Philip, I think Colin gave a good response further down the thread, in particular I think his statement I at least have found Clojure has a much higher signal to noise ratio...snip...and can provide a significant reduction in incidental complexity, thus reducing the problem that some of these approaches are solving is pertinent here. I'll expand on my interpretation of that a bit. But first let me say that I'm pretty familiar with Uncle Bob, extreme programming and Agile development and the set of practices associated with those labels. I have been, in fact, a passionate advocate of extreme programming practices at times in the past. I do think there is a lot of value there, and I think every professional developer who has to work on teams and maintain code should seriously engage with that set of practices to try to understand the value. That said, there is also a lot of dogma and unquestioned convention in that community. I find Uncle Bob in particular to be frustrating in his rigidity, even when I agree with many specific points he makes. More relevant to the discussion at hand, since I've been using functional programming approaches, I've developed a more flexible attitude to what it means to do development The Right Way. So first off, I would like to point out that I had no comments in my code--but I did document my functions with doc strings. I suppose the point about fragility stands, but on the other hand I am consistently frustrated when developers fail to document their public-facing libraries, and I think good documentation is a hallmark of high-quality software. So I guess what I'm saying is that I've accepted there is value in writing about your code vs. (or in addition to) simply letting your code speak for itself, despite its cost; the value outweighs this cost. The analogy image of the mislabeled container you attached, while clever, breaks down for me here: someone hasn't met all of their responsibilities. At the same time I do not disagree with the essence of what Uncle Bob says regarding comments: code that isn't clear and needs heavy commenting is *probably* problematic. However, I think the solution in functional languages is to lean heavily on the core persistent data structures and associated functions, use pure functions as much as possible and make it clear when you are not, specify types (in Clojure we can use schema or core.typed for this), and finally let the data do the talking. Regarding TDD: as I said I do use TDD in a professional setting, but not consistently: I don't think it is consistently necessary, and more than anything, the central argument of a lot of TDD apologists--that it helps guide design--seems much less compelling when using a functional approach. I haven't gotten enough clarity in my own mind as to why exactly this is yet, so I'll leave it at that--but let it suffice to say that I think TDD's biggest value in my day-to-day work in Clojure is in automatically providing a suite of regression tests, not providing design guidance. Finally, I would add that I agree with Kent Beck's points you listed at the end--I would simply argue that it's not necessarily the case that following Uncle Bob's stringent guidelines (for example) are the way to achieve those goals when using Clojure or doing functional programming in general. Thanks for making me think hard about this--I haven't tried to crystallize what I've learned since starting down this path a few years ago, and it's really valuable to think hard on it! Making high quality, maintainable software is challenging and deserves careful thought. Best, Dave (2014/12/09 9:24), Philip Schwarz wrote: Hello David, I had set myself the constraint that I wanted the solution to exploit two symmetries: (1) The top left and top right of the diamond are mirror images (2) The top half and bottom half of the diamond are also mirror images I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to) I was on a train commuting back home, and what I did was sit in a loop where I wrote some code and then tweaked it until executing it in the REPL gave me the part of the diamond that I wanted, by eyeballing the console output. What a coincidence that in your gist you linked to http://blog.jayfields.com/2014/01/repl-driven-development.html . I was looking at exactly that blog post on Sunday to determine if what I had been doing could be classified as REPL-based? Still not sure. Thoughts? My first version of the code was this https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf: (defn print-diamond [letter] (let [alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ position-of (fn [letter] (inc (- (int letter) (int \A number-of-letters (position-of letter) dashes (fn [n] (repeat n \-)) fixed-text-for (fn [letter] (concat (dashes (dec (position-of letter))) (list letter))) template (map fixed-text-for (take number-of-letters alphabet))
Re: what do you think about this code?
TIL: butlast Nice. Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.joh...@googlemail.com javascript:: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find
Re: what do you think about this code?
Hello David, I had set myself the constraint that I wanted the solution to exploit two symmetries: (1) The top left and top right of the diamond are mirror images (2) The top half and bottom half of the diamond are also mirror images I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to) I was on a train commuting back home, and what I did was sit in a loop where I wrote some code and then tweaked it until executing it in the REPL gave me the part of the diamond that I wanted, by eyeballing the console output. What a coincidence that in your gist you linked to http://blog.jayfields.com/2014/01/repl-driven-development.html . I was looking at exactly that blog post on Sunday to determine if what I had been doing could be classified as REPL-based? Still not sure. Thoughts? My first version of the code was this https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf: (defn print-diamond [letter] (let [alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ position-of (fn [letter] (inc (- (int letter) (int \A number-of-letters (position-of letter) dashes (fn [n] (repeat n \-)) fixed-text-for (fn [letter] (concat (dashes (dec (position-of letter))) (list letter))) template (map fixed-text-for (take number-of-letters alphabet)) pad-with-trailing-dashes (fn [index line] (concat line (dashes (dec (- number-of-letters index) top-right-quadrant (map-indexed pad-with-trailing-dashes template) top-left-quadrant (map reverse (map rest (take number-of-letters top-right-quadrant))) top-half (map concat top-left-quadrant top-right-quadrant) diamond (concat top-half (drop 1 (reverse top-half)))] (doseq [line (map #(apply str %) diamond)] (println line I showed it to Extreme Programming and Agile Guru Ron Jeffries, and the following conversation ensued: @philip_schwarz 1st stab at Clojure print-diamond using symmetries identified by @TotherAlistair @RonJeffries @gdinwiddie @sebrose https://gist.github.com/philipschwarz/c7e3be1ac97e482d04bf @RonJeffries @philip_schwarz *can people read that and figure out what it does? *i can't but not a closure person. @totheralistair @gdinwiddie @sebrose @philip_schwarz @RonJeffries @TotherAlistair @gdinwiddie @sebrose *I like defns of top-half diamond think they r graspable-ish; top-left-quadrant less so* @philip_schwarz one interesting Q for us all is *if one didn't know the prob could one grok the prog* @totheralistair @gdinwiddie @sebrose @gdinwiddie .@RonJeffries I think *the program is generally easier to grok if you've got the tests, too.* @philip_schwarz @TotherAlistair @sebrose @philip_schwarz Dec 3 @gdinwiddie @RonJeffries @TotherAlistair @sebrose agree - I have added tests: https://github.com/philipschwarz/diamond-problem-in-clojure/blob/master/test/diamond_problem_in_clojure/core_test.clj I notice you did not write tests. I also notice that you added comments to your methods. I like your comments. Find them useful. I am not saying the following applies to your comments, but it will give you an idea of the programming culture I am part of. In that culture, comments are looked at with suspicion: e.g. 1: https://twitter.com/nzkoz/status/538892801941848064 https://pbs.twimg.com/media/B3qIJLFCcAEJLWm.jpg e.g. 2: The proper use of comments is to compensate for our failure to express ourself in code. - Robert C. Martin e.g. 3: Comments often are used as a deodorant... often comments are there because the code is bad. - Martin Fowler e.g. 4: - Primary Rule: Comments are for things that *cannot* be expressed in code. - Redundancy Rule: Comments which restate code must be deleted. - Single Truth Rule: If the comment says what the code *could* say, then the code must change to make the comment redundant. In that culture, we aim to use certain implementation patterns that make comments unnecessary. Also, where possible, the tests act as (executable, more reliable) documentation. Moving on, after writing the terse first version of the code, I set out to *make my code more readable*. Are you familiar with Robert Martin's dictum?: The Three Functions of a s/w module: * The function it performs while executing * To afford change. A module that is difficult to change is broken and needs fixing, even though it works * *To communicate to its readers. A module that does not communicate is broken and needs fixing.* The rationale for making code more readable is an economic one. Here is a brief summary of Ken't Beck's thoughts on the matter: o Economics is the underlying driver of software design o Software should be designed to reduce its overall cost o COST(total) = COST(develop) + COST(maintain) o The cost of maintenance is much higher than the initial cost of development o Maintenance is expensive because understanding existing code is time-consuming and
Re: what do you think about this code?
btw, my first impression when first looking at your solution is positive - the feeling I get is that I probably won't have problems understanding how it works Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.joh...@googlemail.com javascript:: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would
Re: what do you think about this code?
Hi, Philip. I had the same urge as David--I tried it out, glossing over any formal rules. Here's what I came up with: https://gist.github.com/leifp/ae37c3b6f1b497f13f1e In truth, I think David's solution is more readable and maintainable. But I think maintainability is a pretty tricky concept: My code makes a seq of maps describing rows, and then turns them into strings at the end. This is probably more work to understand than David's solution. But is it less maintainable? Well, currently, the answer is yes, but what if I need to output a diamond in several different formats? What if marketing wants each row to be a different color and font? I would start to favor my solution in that case. My point is that the difference between maintainable and horrible is evident, but the difference between maintainable and easily maintainable depends on predicting the future somewhat. I also favor a slightly less verbose style. A function is an abstraction, and you seem to be writing functions for very concrete steps. I think you have most of the correct abstractions for your solution method, you just need to consolidate the more concrete steps. Something like: flip-bottom-up - flip (or vertical- and horizontal-flip) join-together-side-by-side - beside put-one-on-top-of-the-other - stack (or ontop, or ...) reverse-every-row - (map reverse rows) ; very readable to clojure programmers (let [top-right (create-top-right-quadrant-for letter) right (stack top-right (flip top-right)) diamond (beside (map reverse (drop-first-col right)) right)] (display diamond)) The broad takeaway is: if I write a function I only use once, I usually just inline it. Unless of course I believe deep in my heart I'll have need of it somewhere else soon :). This is somewhat a matter of taste, and again, the requirements history usually determines what gets abstracted into functions, and history can be messy. :) Hope that helps, Leif On Saturday, December 6, 2014 5:48:02 AM UTC-5, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hey David, thank you for taking the time to review my code and come up with suggestions. I look forward to chewing over your reply soon (job and daughter permitting). Philip On Saturday, 6 December 2014 13:36:47 UTC, David Della Costa wrote: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.joh...@googlemail.com javascript:: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what
Re: what do you think about this code?
Hi David thanks for you reply. I'll get back to you as soon as possible. Philip On Saturday, 6 December 2014 18:40:16 UTC, Colin Yates wrote: Excellent question and I will be watching this thread with interest. Similar to David Della Costa, I find a bit difference between Clojure and Java for example is that there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. I am on the fence, and fall down frequently either side (you wouldn't believe the chaffing :)) - the more Clojure I write the more comfortable I am with dense calls to core.clj functions. But I also feel the loss of the info captured in variable names/function names as well. Another point worth mentioning is that the more Clojure you write the more you start to realise that the same shapes of functions come up time and time again - the structural shape of the code imparts knowledge sometimes. As David says, if you haven't looked at Prismatic Schema then have a look. I find the definition of the schema is also an excellent place to capture this extra layer of info in the names of those structures. Good question. On Saturday, 6 December 2014 10:48:02 UTC, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
what do you think about this code?
Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.johann.schw...@googlemail.com: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google
Re: what do you think about this code?
Excellent question and I will be watching this thread with interest. Similar to David Della Costa, I find a bit difference between Clojure and Java for example is that there is much less naming-of-concepts. Clojure code tends to be much more about the shape of transformations than the semantics of those transformations. A case in point, you wrote [code](defn put-one-on-top-of-the-other [top-half-of-diamond bottom-half-of-diamond] (concat top-half-of-diamond bottom-half-of-diamond))[/code]. I think most people would inline that. Extracting it however, give helpful information about the structure which isn't captured by the call to concat, namely the vertical nature (top/bottom). Of course, if the variable names were retained then is also sufficient but they almost certainly wouldn't be. I am on the fence, and fall down frequently either side (you wouldn't believe the chaffing :)) - the more Clojure I write the more comfortable I am with dense calls to core.clj functions. But I also feel the loss of the info captured in variable names/function names as well. Another point worth mentioning is that the more Clojure you write the more you start to realise that the same shapes of functions come up time and time again - the structural shape of the code imparts knowledge sometimes. As David says, if you haven't looked at Prismatic Schema then have a look. I find the definition of the schema is also an excellent place to capture this extra layer of info in the names of those structures. Good question. On Saturday, 6 December 2014 10:48:02 UTC, Philip Schwarz wrote: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better algorithm for solving the kata. I am learning Clojure and what I want to know is what YOU would do to make the code more readable/understandable/maintainable, or just to make it follow Clojure idioms and/or conventions that YOU find effective, or to follow a coding style that YOU find more effective. Thanks, Philip [1] https://github.com/philipschwarz/diamond-problem-in-clojure -- You received this message because you are subscribed to the Google Groups Clojure group. To post to this group, send email to clojure@googlegroups.com Note that posts from new members are moderated - please be patient with your first post. To unsubscribe from this group, send email to clojure+unsubscr...@googlegroups.com For more options, visit this group at http://groups.google.com/group/clojure?hl=en --- You received this message because you are subscribed to the Google Groups Clojure group. To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.
Re: what do you think about this code?
Whoops, re-reading my post I realized that I simply linked to my own gist again when talking about separating out pure from side-effecting code. I meant to link here: https://github.com/philipschwarz/diamond-problem-in-clojure/blob/7efbc472632dced5e173084672ad76687e39dd1f/src/diamond_problem_in_clojure/core.clj#L68-L74 2014-12-06 22:36 GMT+09:00 David Della Costa ddellaco...@gmail.com: Hi Philip, I read your message and immediately wanted to try it myself--I intended to leave it at that but I realized I would be remiss if I did not give you a little bit of feedback based on my experience. I should add that I was kind of fast and loose with my solution (that is, I didn't really read the instructions), but it does print out the diamond shape according to what I saw in the blog post examples. First of all, here's what I came up with: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 As you said, you weren't looking for alternative algorithms and I recognize that that's not the point. But there are a few things that I think are good and/or common Clojure practice that I think I've internalized, and writing out an alternative solution helped me to see them. - I'm assuming you used a TDD process to write this (correct me if wrong--basing that on the articles you linked to), but I think a repl-driven process may be more common for working through a problem like this--i.e. something you can wrap your head around as a whole and solve iteratively. That's not to say I and others don't use TDD in Clojure dev, but just that it's also quite common to do a lot of this kind of development in the repl. - you're grouping your side-effecting code w/the code that generates the diamond data structure here: https://gist.github.com/ddellacosta/ba7e03951ba1bafd3ec9 While of course the diamond kata is a bit contrived and the point is to print stuff out in the end, it also looks like you are trying to be thoughtful about how you structure your code. So I would suggest isolating your pure functions from your side-effecting code as a sort of basic separation, and avoid monolithic functions like the one I linked to above. This gives you the freedom to apply the data structure to other processes if need be, rather than having to refactor that code later on as soon as you need to do something other than printing to the final diamond data structure. That is a more compositional approach that is good to follow as part of functional programming practice in general. And otherwise it seems like you are following this approach--I think you can see this in the shape of your code overall. - Stylistically, I found your naming conventions to be too verbose, with not enough information about the actual input and output--I would prefer a style like I used in my solution which aims for readable conciseness, while documenting what is going in and coming out of my functions. I assume Clojure developers reading my code will have a good understanding of the core data structures and functions available to manipulate them, and so I want to leverage that as much as possible in how I write and document my code. In fact, at this point I prefer using Prismatic's schema ( https://github.com/Prismatic/schema) to document as well as provide further safety for my functions, and am of the opinion that Clojure's one glaring weakness is its approach to typing--but that's another discussion and I recognize this is not necessarily a widely-held opinion. More generally, I think reasonable people could disagree on naming conventions and so I would hesitate to say you're doing something wrong here--I would rather say: the more Clojure code you read the more you'll get a sense of how people tend to write. You'll figure out what you want to adopt in your own style, and what Clojure devs are going to expect. - I don't want to get too deep into the algorithm itself but I think you would find it more natural to work line by line vs. the way you constructed blocks and flipped them right/left, and you'd have less code overall. I will boldly claim that my solution may be closer to how other developers familiar with Clojure (or functional programming in general) may approach it--not that I'm claiming it's the best approach. I do think it is more concise without sacrificing readability (which is subjective, I fully appreciate). - I don't know if I've ever once used a main function, and you don't see them in libraries, certainly. But that is minor--there's no reason *not* to use it, just that I wouldn't expect to see it. I hope this is useful feedback--good luck in your journey and enjoy Clojure! Dave 2014-12-06 19:48 GMT+09:00 Philip Schwarz philip.johann.schw...@googlemail.com: Hello, can you please review my first solution to the diamond kata [1] and tear it to bits: let me know all the ways in which YOU would improve the code. I am not so interested in a better