The Holy Java

Building the right thing, building it right, fast

Posts Tagged ‘CleanCode’

Most interesting links of Mars ’13

Posted by Jakub Holý on March 31, 2013

Recommended Readings

A lot of stuff this month since I have finally got time to review some older articles. Quite a few articles by Fowler. Few really great (yet short) talks on agile & SW development.

Top

  • Agile in a Nutshell (originally Agile Product Ownership in a Nutshell) by Henrik Kniberg – the best explanation of the agile development process ever, in just 15 minutes and with wonderful animation; every developer should see this. Some highlights: the most important task of product owner is to say NO so that backlog doesn’t grow infinitely; at start, the estimates of size and value will suck and that’s OK because the value is in the conversation, not in the numbers (that are anyway just relative); the goal is to maximize outcome (value), not output (# features). Compromises between short-term vs. long-term goals, knowledge vs. customer value building etc. Build the right thing (PO) x build it right (devs) x build it fast (SM). Technical debt x sustainable pace. As I said – you MUST see it.
  • Martin Fowler: The Value of Software Design (talk, 22 min, from 0:45:00 til 1:07; Feb 2013) – a balanced argument for the value of good software design and internal code quality based on paying off by enabling us to keep our development speed. Discusses the DesignStaminaHypothesis (bad design => rapid decline of development speed), TechnicalDebt, TechnicalDebtQuadrant (Prudent x Reckless, Deliberate x Inadvertent), TradableQualityHypothesis. According to the experience of Fowler and others, the good design payoff point “it’s weeks, not months.”
  • What Does It Take To Become A Grandmaster Developer? – great post about cognition and learning, valuable references, quotes from an interesting study of good vs. mediocre developers. We have mental capacity for ~7 chunks of information => great performers recognize patterns and see and understand thus higher-level chunks and have many “chunks” (patterns encountered previously) readily available. You need deliberate effort to learn more chunks – especially initially but you must always try to get out of your comfort zone to grow. Experienced collegues can help a lot in acending the learning curve.

Agile, organization, innovation, project management

  • How to Prioritize a User Story Map – we all know that we should prioritize features by their value, risk, and lack of knowledge and that we should slice the features thin so that they fit into short iteration and can be deployed soon to produce feedback, right? Here we see a nice example of what happens if not done so and how to do feature slicing better.
  • Bob Marshall: Rightshifting – according to the author, 80% of knowledge work organizations are very ineffective, wasting resources on non-value-adding activites; only few are effective, even fewer highly effective. Rightshifting is the attempt at shiting them to the right, towards higher effectiveness. Links to a few videos explaining it more. Related: Steve McConnell’s Business Case for Better Software Practices, referring to a study by SEI; “The actual distribution of software effectiveness is asymmetric. Most organizations perform much closer to the worst practice than to the best.” – the best performing 10 times better then the worst/average (productivity, speed, defects, value)
  • On Antifragility in Systems and Organizational Architecture – introduces the concept of antifragility, based on Nassim Taleb’s book Antifragile that compares fragile, robust, and antifragile systems and organizational structures (which is also applicable to SW systems); robust = resists change (unless too large); antifragile: learn, adapt; closely related to DevOps and continous delivery
  • M. Fowler: PurposeOfEstimation – many Agilist disdain estimation, this is a balanced view: “estimation is valuable when it helps you make a significant decision.” (F.ex. when deciding what we (don’t) have resources for or when in need of coordinating related activities.) It is evil when used as commitments that people are forced to stick to and blamed for not managing to do so. “Above all be wary of anyone who tells you they [estimates] are always needed, or never needed.” A. Ferguson: “[..] it is poor project management (whether by project managers or other team members) that results in a client who thinks estimates are fixed, or that raw estimates = actual effort/duration”.
  • Ron Jeffries: Estimation is Evil – discusses the problems estimates can cause, issues with requirements gathering up front and their volatility, transparency and politics. Very valuable, highly recommended. See the “favorite quotes” at the bottom of this post. Also contains an interesting lesson learnt from the failed Chrysler C3 project: don’t try to build a grand new system to replace and fix the old one, fix one problem at a time – worth reading for this alone.
  • Interview with Steve Blank: Why Big Companies Can’t Innovate – the 2013 list of the world’s 50 most innovative companies has only a few large, established firms (those that have built innovation into its DNA such as Apple and Google). Established companies are less innovative because they focus in their existing business model, have risk-aversion (while there are many failures on the way to a new business model); finally “the people who are best suited to search for new business models and conduct iterative experiments usually are not the same managers who succeed at running existing business units.” – and thus aren’t given the chance. “[..]  the process of starting a new business [..] is fundamentally different from running an existing one. So if you want your company to grow organically, then you need to organize your efforts around these differences.”

Architecture & Ops

  • M. Fowler: Schemalessness + NoSQL and Consistency (20 + 20 min) two short, very good, balanced talks about NoSQL. He explains schemalessness and consistency and points out common misunderstanding about them so if you are into NoSQL, watch it.
  • What Powers Instagram: Hundreds of Instances, Dozens of Technologies (2012) – interesting high-level overview of the Instagram infrastructure based on AWS and Python (25 XL instances running Django/Gunicorn behind ELB with 3 Nginxes, sharded PostgreSQL with streaming replication on 12 QXL mem instances with software raid and XFS to freeze when snapshoting, media in S3, Redis, Solr for geo-search, Memcached. Gearman for task queues, pyapns for notifications. Munin for monitoring.)
  • The Netflix API Optimization Story – how Netflix redesigned its APIs to improve performance, reduce chattiness, and power product development and experimentation. The common REST API has become a development bottleneck and a lowest common denominator solution (w.r.t. supporting various clients). The main changes were: usage Hystrix for fault tolerance, each device team managing their own end-points in any JVM languges (primarily Groovy) and re-using common APIs (i.e. pushing some device-specific code to the server) => able to experiemnt more quickly, using the Functional Reactive Programming Model and asynchronous APIs (to abstract away thread-safety and parallel execution implementation details from the device teams so that code can execute sync. or async. without them needing to know).
  • Me: Overview of current monitoring libs for Java – Netflix’ Servo, Yammer’s Metrics, JavaMelody, JavaSimon.
  • Debug Servlets, or ‘HTTP Won; Use It’ – expose all debugging info of your services over HTTP – it makes debugging much simpler. We do a part of it and it really helps. Expose config (values, where they come from), logs, log configuration, JMX (setting it up otherwise not trivial), version, build number, git hash, server time (timezones tricky), metrics, stack dumps, app-specific status (Hadoop: live nodes, data size etc.). The author recommends JavaMelody to collect & visualize many common metrics. Not on security: Make sure to hide passwords and make the endpoints visible only internally. (Tip: consider Jolokia for exposing JMX over HTTP, see below.)
  • JVM Crash/Core Dump Analysis – 3 common categories of  JVM crash causes (JVM/JIT/JNI) and how to recognize and troubleshoot them

Other

  • How to lose wight in the browser:  The definitive front-end performance guide – a site by a number of experts from Twitter, Opera, Google, and other places with best practices for performant web sites (HTML, CSS, JS, jQuery, images). Ex.: styles up top, scripts down bottom; minify your html, css and JS; async script loading; combine css/JS files into one; cache array lengths while looping; use css sprites for icons.
  • Luke Stevens: The harsh truth about HTML5′s structural semantics (part 1) – “HTML’s structural elements — article, section, nav and aside — are, at first glance, some of the easiest parts of the HTML5 specification to understand and implement. However, they’re actually some of the most poorly specified, poorly understood, and poorly implemented parts of HTML5.” Interesting: The “research” leading to their establishment was quite random, ignoring a crucial source of information (css IDs).
  • Marco Emmanuel Patiño: Six non-technical books every programmer should read – 1. Team Geek: A Software Developer’s Guide to Working Well with Others (-> effective communication and collaboration), 2. The Pragmatic Programmer: From Journeyman to Master, 3. The Passionate Programmer: Creating a Remarkable Career in Software Development, 4. Clean Code: A Handbook of Agile Software Craftsmanship, 5. 97 Things Every Programmer Should Know: Collective Wisdom from the Experts (online), 6. Code Simplicity: The Fundamentals of Software.
    • Related: Top 5 Java programming books – Best of lot (actually 8) – 1) Head First Java, 2) Effective Java, 3) Thinking in Java, 4) Head First Design Pattern, 5) Concurrency Practice in Java, 6)Java performance, 7) Java Puzzlers, 8) Head First Object Oriented Analysis and Design.
  • Humans as slaves of chemistry: America’s Real Criminal Element – Lead – a fascinating article about how whole nations can be seriously influenced by a single chemical substance. Aside of that it is also fascinating to observe how we tend to search for causes in our domain of expertise (police, sociologists, …) and of interest while denying other possible causes, no matter how strong are the proofs. If the facts presented are true, then the fivefold increase in serious crimes in (not only) America since 60s has been caused by the increase of lead in the environment (pushing many people over the edge of ocassional violent loss of control). How many social problems in the world have similar industrial causes? Are we careful enough with what we let into our air and bodies?

Languages

  • newcoder.io: Learning more Python via projects – an excellent next step when you have learned Python syntax via LPHW or similar; in this tutorial series you will be building real-world apps while learning more of Python. You will play with, Data Visualization, APIs, Web Scraping, Networks, GUI.
  • Brian McCallister: Go is PHP for the Backend – a very good explanation why you might want to use Go and that you have to first learn “the Go way” to avoid insanity, since it is very opinionated and different from what you might be used to. Some pros: “native code, UNIX friendly, higher level then C, lower level then Python or Ruby, garbage collected, strongly typed, good performance, good concurrency support, etc.”
  • The Neophyte’s Guide to Scala 1 to 15 (list) – a good follow-up on the Cursera FP in Scala course, a series of blog posts exploring some topics more in depth. F.ex.: extracotrs (unapply, for pattern-matching), the broad applicability of pattern matching, pattern matching anonymous functions & partial functions #4, usiong Option idiomaticly #5, nice FP error handling with the Try type #6, Futures, etc. Higly recommended! Thx to Jakob Lind

Libs

  • Jolokia is remote JMX with JSON over HTTP: a REST API bridged to JMX, with support for security, fine-grained access control, bulk operations. Especially useful if you either 1)  need to perform bulk operations (e.g. get multiple values) or 2) want to access them from something that doesn’t support JMX. JSON is in general very easy to use and navigate. You can install Jolokia as a WAR (or mebedd its Servlet), a JVM agent, or attach it on-the-fly to a running JVM.
  • The Appeal and Controversy of ZeroMQ – why to use 0MQ? It is a messaging library that focuses on performance, decentralization and simplicity, solving some really hard problems (sending async. messages w/o locks, distribuing to specific subscribers) and providing a simple API. Main pros: decentralized (no central broker), many languages; cons: no security (but you can use it over SSH).

Talks

  • Tim O’Reilly: Create More Value Than You Capture (30 min + questions) – build apps that matter, that change how we do things. Thinking just about money is bad. Try to make the society better, smart, create more value than you capture, solve important problems, help people. Ex. startups: Uber, Square, Code for America.
  • TED: Bruce Feiler: Agile programming — for your family (20 min) – an inspirational talk, based on positive experience from multiple families, about applying the agile thinking and values to make our families happier by empowering the children (enlist them in their upbringing, deciding on goals, rewards, punishments), letting them know who they are, being adaptive, having regular “retrospectives” (that eventually become cherrished memories). Backed by research. Did you know that the #1 wish of children isn’t that parents spend more time with them but that they are less stressed?

Clojure Corner

  • What’s new in Clojure 1.5.x – reducers, new threading macros (cond->, as->, some->, ..), various improvements, improved performance, erro messages, doc strings, bug fixes
  • Stuart Sierra: On the Perils of Dynamic Scope – summary: don’t create macros like with-connection binding to a thread-local var; make all methods take the resource as a parameter – thus the user has the freedom to decide when to close the resource and isn’t limited to a single thread and can use lazy sequences
  • Logic programming is overrated – core.logic is essentially only a complex DSL for doing an exhaustive search and there is already a nice, clean tool for that: the for comprehension. A logic puzzle can be much more clearly and also efficiently using for. But it is not completely useless – logic programming is good e.g. for running programs backwards, unification is important for writing type checkers, and the new constraint programming piece has good potential. Read also Logic Programming is Underrated, which provides a faster core.logic solution than for-comprehension and provides some pointers rgarding the practical usefulness of core.logic.
  • Prismatic – Graph: Abstractions for Structured Computation – How to reduce the complexity overhead in large, real-world, FP systems by decoupling what is done from how it is executed. Graph is a Clojure library enabling a declarative way to describe how data flows between (mostly pure) functions => “It allows us to formalize the informal structure of good FP code, and enables higher-order abstractions over these structures that can help stamp out many persistent forms of complexity overhead.” By decoupling the description of how data flows and the actual execution, we can execute it in different ways (parallelized, with memoization, lazy/eager) and apply various interceptors (for logging etc.). See especially the part “Graph and complexity overhead.”
  • Mike Anderson: Game development in Clojure : Alchemy 7DRL post-mortem (and the previous 7 daily updates, Alchemy @ GitHub) – an interesting report about game making in Clojure during 7 days, in as functional and immutable style as possible while keeping it sufficiently fast. How do you represent & handle statuf game objects, the world map, game state? The design of the game, what was easy and what hard with Clojure. Tl;dr: search it for “Some parting thoughts” (Clojure productive, immutability hard but pays off, prototype objects great, more typing would have helped). “Making everything immutable in Clojure is harder than it would have been in an OOP language like Java where everything can be encapsulated in mutable classes. In particular, the state update functions are tricky to make both correct and performant. The payoff is big however: in terms of the simplicity and effectiveness later on, and in the conceptual clarity being able to treat the entire game state as an immutable value”. Having REPL is a big win.
  • Refactoring Java using Clojure with the Eclipse Java development tools (JDT) (operation on AST nodes, i.e. little too low level; the Eclipse Refactoring API might be better)
  • Clojure at a Bank – [Our] Clojure Code Immaturity – experiences with going from Java to Clojure: 1) too few comments, too short names => hard to learn the code; 2) not knowing clojure.core well enough => reimplementing (if-let, juxt, …); 3) structure, comment, split up your namespaces well, navigating more complicated then in Java IDEs; 4) reasonably used Macros, Protocols, Defrecords payed off;
  • Datomic for Five Year Olds – explaining the key characteristics of Datomic compared to relational and NoSQL DBs (schema, architecture, programmability/language); doesn’t go into details of how it works (e.g. how does Datomic determine what subset of the DB to cache locally and what if it is few GBs); Honey Badger’s 2012 talk Exploring Datomic: a database deconstructed explores the architecture and technical details much more

Tools

  • Vagrant 1.1.0 is out (what’s new?), with support for VMWare Fusion and AWS VM backends in addition to VirtualBox – use the same config to create, provision, stop, destroy and connect to a virtual machine locally or in the cloud (with limited support for shared folders, I’d suppose). V. 1.1 is backwards compatible aside of plugins, upgrade to new config optional.
  • Animated presentations: ArtRage (drawing program, also for iPad), Wacom Intuos 5 (drawing tablet), Screenflow (screen & audio capture) – used for the Agile in a Nutshell (Agile Product Ownership in a Nutshell) mentioned above
  • ckjm — Chidamber and Kemerer Java Metrics (via Neal Ford) – a command-line tool (also Maven/Ant plugin) to compute some metrics, outputting text or XML for further processing; the metrics: WMC: Weighted methods per class (cyclomatic complexity of its methods), DIT: Depth of Inheritance Tree, NOC: Number of Children, CBO: Coupling between object classes, RFC: Response for a Class, LCOM: Lack of cohesion in methods, NPM: Number of Public Methods, Ca: afferent coupling.
  • Bulletproof Demos: Record & Replay built into Chrome – ever got a failure while demonstrating a web app though it has worked moments ago? No more! You Chrome to record your requests and responses and let its cache handle them during the real demonstration. (Mac: stop Chrome, to record run open -a “Google Chrome” –args –record-mode, to replay run open -a “Google Chrome” –args –playback-mode. Linux: google-chrome –record-mode and –playback-mode. Win.: run chrome <arg>)
  • UserTesting.com (via Ash Maurya, the author of Running Lean) – on-demand usability testing; they have a large base of test users, can select those matching your criteria and unleash them upon your site guided by a script your provide, watch videos of their actions while they verbalize their thinking process, recieve written answers from them, talk to them.
  • MindMup.comopensource, free mind-mapping in the cloud by Gojko Adzic & co., with main focus on productivity. Store private maps in Goolge Drive, support for mobile devices, keyboard shortcuts. No registration needed.

Favorite Quotes

Once we estimated a project to require 9 man-months but were later told that we do not understand a thing and it may not take more then 4. At the end it took over 25 and still wasn’t done.

- paraphrasing my collegue Kim Leskovski

On collecting requirements up front:

At the very beginning, we know less about our project than we’ll ever know again. This is the worst possible moment to be making firm decisions about what we “require.”

- Ron Jeffries in Estimation is Evil: Overcoming the Estimation Obsession

On the estimate of project delivery date at its initial phase:

It’s based on an unrealistic list of requirements, using weak estimates, made at the moment of maximum ignorance, by people who are always optimistic about their own abilities.
- ibid

On planning and requirements (the Chrysler’s C3 payroll project, having a payroll expert and a team familiar with the domain):

This was one of the best-planned projects I’ve ever seen, and even so, at least one third of the requirements were added, removed, or substantially changed.
- ibid

[..] a line of code is a liability, not an asset [..]
- Jez Humble in Why Software Development Methodologies Suck

Agile is not something you do, it is something you are.
- Huib Schoots in Creating my own flow
with personal kanban, Agile Record Feb 2013

Posted in General, SW development, Tools, Top links of month | Tagged: , , , , , , , , , , , , , , , , | Comments Off

Most interesting links of February ’13

Posted by Jakub Holý on February 28, 2013

Recommended Readings

  • Øyvind Bakksjø: The inverse of IoC is Control – a well-founded criticism of the (over)use of inversion-of-control containers such as Spring and Guice. Bakksjø isn’t against dependency injection in general but he prefers to do it manually, instead of magically, in a main method, using Java instead of an obscure DSL/XML. The dependencies are typically known at compile time so why postpone assembling (and defect discovery) to runtime? Why hide how parts fit together into the non-transparent magic of IoC? He has many good points though I believe there are cases when some automation of the wiring process is valuable (think of scope-dependant beans, diff. deps in diff. environments etc.) Comment by B. Borud: “Explicit wiring you can read from start to finish beats vague declarative shit that you may be able to figure out if you pay close attention.” Check out also the comments at HN.
  • J. B. Rainsberger: Demystifying the Dependency Inversion Principle – a very good explanation of the value of dependency injection in the terms of general good code principles (promoting abstractions and postponing determination of details to the latest moment/client)
  • CodingHorror: Coding Without Comments (2008) – a very good explanation if how to treat comments (similar what Clean Code says): write code so that it is self-explanatory (using good method and variable names), if necessary, add comments that explain why (while the code shows what/how).
  • Frustrations and Aspirations of a Software Craftsman – what makes us happy or unhappy on a project? (I could add some too.) Bad: bureaucracy, old/unfit technology, lack of autonomy and credibility, uninteresting domain, demotivated people, blaming and highly competitive environment, arrogant and unskilled people, … => it is mostly about people. Good: projects where there is passion, craftsmanship, friendship and trust.
  • Jetty-9 goes fast with Mechanical Sympathy – interesting how the run-time behavior might differ from what we would expect and how knowing the hardware can improve performance. Here:  false sharing of a blocking queue’s head/tail pointers and locks (close => same CPU cache row => updating one invalidates the other), using trie backed directly by IO buffers for faster String lookups etc. Result (all microbenchmark disclaimers): jetty-9 out performs jetty-8 by 30% faster and 50% less YG garbage.

Czech

  • Daniel Kolman: Jak správně pojmenovat test – a good description of different approaches to name and organize tests w.r.t. the experience of the developer – starting with “testWorks1″ through one method-one test with “testMyMethodName” through a more thoughtful naming scheme such as Roy Osherove’s UnitOfWork_StateUnderTest_ExpectedBehavior (e.g. ndexOf_containsSearchedString_returnsCorrectIndex) to tests as a living documentation: tests represent a list of features of the class, each name is a sentence having the class under test as its subject (e.g. [list] holdsItemsInTheOrderTheyWereAdded). Advantages of the latter: readability, documentation, it forces us to think what actually is still the responsability of the class and what isn’t. “Stačí názvům testů věnovat dostatečnou pozornost a ony vám samy napoví, kdy už toho třída dělá moc a měli byste se zamyslet, jak kód lépe rozdělit.”

Non-IT

  • Why You Should Work With Someone You Hate – working with people we like and do not have conflicts with is nice but we are likely to have similar views and ideas and miss the broader picture. Working with somebody that drives you crazy while being able to respect each other is very valuable because it opens you to different views and forces you to really defend yours. Recommended!
  • Kent Beck: Focusing Talks: Three Questions – some good advices for performing technical talks and avoiding putting too much into the talk. Ask 1) Who is the audience? – be as specific and narrow as possible to be able to tune and cut the content; “Better to reach one person than zero.” 2) What is my one startling sentence? – one that makes the audience take notice; “Picking one sentence, I encourage focus and empathy in myself. Now I have one person’s attention. What do I say?” 3) What would I like the audience to do? “‘To what purpose?’ helps me discard interesting-but-tangential points, to, as Peter Jackson put it, move the ring.” “The more clear and uncompromising I can be with the three questions, though, the easier all the rest of it becomes.” “Talk about less. And less. Less than that.”

Clojure Corner

  • Clojure’s Reader is Unsafe (for untrusted strings) – don’t use read-string to read untrusted strings – even if you set *read-eval* to false, it can still be persuaded to execute arbitrary code (hopefully fixed in Clojure 1.5). The right, save way is to use clojure.tools.reader.edn/read-string.

Tools

Posted in General, Tools, Top links of month | Tagged: , , | Comments Off

What Is Clean Code? – In Quotes

Posted by Jakub Holý on December 15, 2012

What is actually good, clean code? Why does it matter?

Marry Poppendieck has, in her excellent talk Deliberate Practice in Software Development (slides), quoted a couple of leading figures of our industry on what is clean code.

(Emphasis is mine.)

Bjarne Stroustrup, inventor of C++:

I like my code to be elegant and efficient. The logic should be straightforward and make it hard for bugs to hide, the dependencies minimal to ease maintenance, error handling complete according to an articulated strategy, and performance close to optimal so as not to tempt people to make the code messy with unprincipled optimizations. Clean code does one thing well.

Grady Booch, author of Object-Oriented Analysis and Design with Applications:

Clean code is simple and direct. Clean code reads like well-written prose. Clean code never obscures the designers’ intent but rather is full of crisp abstractions and straightforward lines of control.

“Big” Dave Thomas, founder of OTI and godfather of the Eclipse strategy:

Clean code can be read, and enhanced by a developer other than its original author. It has unit and acceptance tests. It has meaningful names. It provides one way rather than many ways for doing one thing. It has minimal dependencies, which are explicitly defined, and provides a clear and minimal API. Code should be literate since, depending on the language, not all necessary information can be expressed clearly in code alone.

Michael Feathers, author of Working Effectively with Legacy Code:

I could list all of the qualities that I notice in clean code, but there is one overarching quality that leads to all of them. Clean code always looks like it was written by someone who cares. There is nothing obvious that you can do to make it better. All of those things were thought about by the code’s author, and if you try to imagine improvements, you are led back to where you are, sitting in appreciation of the code someone left for you—code written by someone who cared deeply about the craft.

Ward Cunningham, inventor of Wiki and Fit, co-inventor of Extreme Programming. The force behind Design Patterns. Smalltalk and OO thought leader. The godfather of all those who care about code.

You know you are working with clean code when each routine you read turns out to be pretty much what you expected. You can call it beautiful code when the code also makes it look like the language was made for the problem.

Summary

Clean code is

  • Easily accessible to others (straightforward, clear intent, good abstractions, no surprises, good names) – this is absolutely the most mentioned point
  • Is made for the real-world, i.e. has a clear error-handling strategy (my current project has been burnt a lot by the lack of this so my emphasis is little subjective :-))
  • The author clearly cares for the software and other developers (which implies both readability and maintainability)
  • Is minimal (does one thing, has minimal dependencies)
  • Is good at what it does

Posted in General | Tagged: , | 2 Comments »

Programming Like Kent Beck

Posted by Jakub Holý on September 12, 2012

Republished from blog.iterate.no with the permission of my co-authors Stig Bergestad and Krzysztof Grodzicki.

Three of us, namely Stig, Krzysztof, and Jakub, have had the pleasure of spending a week with Kent Beck during Iterate Code Camp 2012, working together on a project and learning programming best practices. We would like to share the valuable lessons that we have learnt and that made us better programmers (or so we would like to think at least).

Read the rest of this entry »

Posted in General, Languages, Testing | Tagged: , , , , , , | Comments Off

Help, My Code Isn’t Testable! Do I Need to Fix the Design?

Posted by Jakub Holý on September 9, 2012

Our code is often untestable because there is no easy way to “sense1” the results in a good way and because the code depends on external data/functionality without making it possible to replace or modify these during a test (it’s missing a seam2, i.e. a place where the behavior of the code can be changed without modifying the code itself). In such cases the best thing to do is to fix the design to make the code testable instead of trying to write a brittle and slow integration test. Let’s see an example of such code and how to fix it.

Read the rest of this entry »

Posted in Testing | Tagged: , , , | Comments Off

Book Review: Implementation Patterns

Posted by Jakub Holý on July 5, 2012

Implementation Patterns, Kent Beck, 2007, ISBN 0321413091.

Summary: Should you read the book? Yes, the chapter on principles and values is trully enlightening. The book in general contains pearls of wisdom hidden in the mud of “I know that already, man.” I would thus recommend skimming through the book and reading only the pieces matching your level and needs.

The book seems to be targeted a lot at Java beginners (especially the chapter on collections), going into otherwise unnecessary details, yet there are many valuable advises of which some can only be appreciated by somebody with multiple years of professional programming experience. It thus seems to me that the book isn’t a perfect match for anybody but everybody will find there many useful ideas. It would best be split in two.

An experienced developer will already know many of the patterns though it’s perhaps useful to see them named and described explicitly and listed next to each – it helps to be aware and clearer of what you do and why you do it.

I’d absolutely recommend everybody to read the chapter A Theory of Programming, explaining Kent’s style of programming and the underlying key values of communication, simplicity and flexibility as well as the more concrete principles (local consequence, minimize repetition, logic and data together, symmetry, declarative expression, co-locating data and logic having the same rate of change). Also in the rest of the book there are valuable ideas that it would be a pity to miss. I list below some of those that I found particularly interesting.

Posted in General | Tagged: , , , | 1 Comment »

Bad Code: Too Many Object Conversions Between Application Layers And How to Avoid Them

Posted by Jakub Holý on May 12, 2012

Have you ever worked with an application where you had to copy data from one object to another and another and so on before you actually could do something with it? Have you ever written code to convert data from XML to a DTO to a Business Object to a JDBC Statement? Again and again for each of the different data types being processed? Then you have encountered an all too common antipattern of many “enterprise” (read “overdesigned”) applications, which we could call The Endless Mapping Death March. Let’s look at an application suffering from this antipattern and how to rewrite it in a much nicer, leaner and easier to maintain form.

The application, The World of Thrilling Fashion (or WTF for short) collects and stores information about newly designed dresses and makes it available via a REST API. Every poor dress has to go through the following conversions before reaching a devoted fashion fan:

  1. Parsing from XML into a XML-specific XDress object
  2. Processing and conversion to an application-specific Dress object
  3. Conversion to a MongoDB’s DBObject so that it can be stored in the DB (as JSON)
  4. Conversion from the DBObject back to the Dress object
  5. Conversion from Dress to a JSON string

Uff, that’s lot of work! Each of the conversions is coded manually and if we want to extend WTF to provide information also about trendy shoes, we will need to code all of them again. (Plus couple of methods in our MongoDAO, such as getAllShoes and storeShoes.) But we can do much better than that!

Read the rest of this entry »

Posted in General, Languages | Tagged: , , , , | 2 Comments »

Quiz: What’s the Best Test Method Name?

Posted by Jakub Holý on December 13, 2011

Which of the following names of test methods do you think to be the best?

(Notice that we could leave out “payment_” from the last name if it is clear from the context, i.e. from the fixture [a fancy name for test class] name.)

According to the holy book of Clean Code, the code should make visible the intent as much as possible. According to the testing guru Kent B., a test should be telling a story to its reader – a story about how the code should be used and function. According to these two and my own experiences from reading a lot of (test) core written by other people, the last one is absolutely the best. However you have the right to disagree and discuss :-)

PS: I firmly believe that calling a test method “test()” should be punishable.

Posted in General, Languages, Testing | Tagged: , , | 3 Comments »

Most interesting links of September

Posted by Jakub Holý on September 30, 2011

Recommended Readings

  • J. Yip: It’s Not Just Standing Up: Patterns for Daily Standup Meetings - it isn’t easy to make stand-up meetings short, focused, energizing, and centered around continuous improvements and team spirit. This description of an example good standup, the meeting’s goals, and especially the “patterns” and “bad smells” can be pretty useful to get and keep on the track towards a brighter future. TBD: standup goals: GIFTs, team spirit, appreciation where we go and are.
  • M. Poppendieck: Don’t Separate Design from Implementation – according to Mary, (detailed) requirements – being it in the form of (backlog) user stories or any other – represent actually a design of the system, which shouldn’t be done by the amateur product owner/business analyst but by professionals, meaning the developers, based on high-level goals and clear specification of the desired business value. She writes about a project that her factory outsourced and which she could have designed but didn’t – yet it succeeded even though there were no detailed requirements. I’ve also read and unfortunately lost an interesting answer where the author argues that that is only possible if the developers are really experienced in the field. I tend to agree more with Mary though it is of course a question what “high” and “low” level goals/requirements are. But undeniably users/analysts tend to propose solutions disguised as requirements while often missing the technical insight to see possible other and better solutions. We also cannot expect the developers to produce a great SW if the true goals, needs, and business values behind the requested “features” aren’t clearly communicated to them. (The best example – lost source again – is where a developer proposes to the client a simple process change that will solve the problem without writing a single line of code.)
  • Mike Cohn: The Forgotten Layer of the Test Automation Pyramid – three levels of testing with increasing number of tests: UI/Service/Unit (or end-to-end instead of UI), each requiring a different approach. Unit tests are best because a failure points directly to its source (with higher level tests you don’t immediately know the cause). The higher in the pyramid, the less tests we should have (e.g. because of their redundancy). It’s important not to forget the middle, service layer – unit tests are too low-level, UI tests too difficult and brittle. Also Gojko in Specification by Examples says that acceptance/BDD tests should run mainly at the service layer because of the UI level issues.
    “Although automated unit testing is wonderful, it can cover only so much of an application’s testing needs. Without service-level testing to fill the gap between unit and user interface testing, all other testing ends up being performed through the user interface, resulting in tests that are expensive to run, expensive to write, and brittle.” [Emphasis JH.]
  • Technical Debt and the Lean Startup – Paul Dyson remarks that while quality is an essential concern for projects in established environments, in the case of lean startups the primary goal is to find out whether a product is viable and what it should be like and thus it’s reasonable to accept much higher technical debt by not spending too much time on ensuring scalability, de-duplication etc. – only when the product proves viable should we start to care for its long-evity by emphasizing the quality. But one thing can never miss and that is good test suite because this is the crucial factor that makes letter payment of the technical debt possible without ruining oneself.
  • Coding dojo – Real time coding competition with Extreme Startup – an inspiring report about a coding dojo lead by Johannes Brodwall in Bergen’s JUG, the task being the implementation of a server that can respond to questions send over HTTP (that’s all participants know at the beginning – they learn the rest during the iterations)
  • Using Code Katas to Improve Programming Skills – why to use code katas + links to different proposed katas
  • Kent Beck: Don’t Cross the Beams: Avoiding Interference Between Horizontal and Vertical Refactorings - when to do depth-first (more exploratory) refactoring and when to extend it into breadth (i.e. apply it to several similar objects)

Learning Clojure (maybe not so interesting for those not learning the language)

  • Phil Calçado: My Experience With TDD In Clojure (via planetclojure) – nice example of how to decompose a task in functional programming to make it easy to test (via Midje), including useful testing-related links and a discussion of side-effect isolation and the building blocks of functional programs, i.e. function composition using combinators (i.e. functions producing functions)
  • How to learn Clojure effectively (via planetclojure) – a very good description of how the task at  4Clojure (though I prefer Clojure koans) should be solved to benefit one’s learning the most plus some general tips on functional thinking
  • Clojure open source projects for learning how to code it

Posted in General, Testing, Top links of month | Tagged: , , , , , , | 1 Comment »

Code quality matters to the customers. A lot.

Posted by Jakub Holý on April 2, 2011

Some people argue that the main taks of a developer is to deliever working, value-bringing software to the customer and idealistic concepts such as code quality should not hinder that primary task. They acknowledge that it is good to strive for good code quality but say that sometimes code quality must give way to the quick deliverance of outcomes to the customer. After having worked on the code base so rotten that it drove less resistant programmers mad I have to strongly disagree. Code quality is not an abstract concept that has a value only in the developers’ world, it is a very real thing, which translates directly to money, namely if you are missing it, it translates into great financial losses over the time.

Read the rest of this entry »

Posted in General | Tagged: , , | Comments Off