Category: Other

  • In Search of the Elite Few – Finding and Hiring the Best Software Developers in the Industry

    The Challenge

    Hiring software developers can often be a daunting task with the whole world as your talent pool.
    Hiring software development talent – real talent – is a multi-faceted skill that lies at the crossroads of social networking, technical acumen, process management, and intuition. Anyone who has ever had hiring responsibility understands all-too-well the extent and depth of the hiring challenge.

    Hiring talent is a multi-faceted skill that lies at the crossroads of social networking, technical acumen, process management, and intuition.

    Particularly challenging is the fact that the hallmark qualities of exceptional software engineering candidates are extremely difficult to evaluate. How do you explore a candidate’s ability to innovate and think creatively? How do you determine if he’s a team player? How do you diagnose her ability to take constructive feedback? How do you investigate someone’s moral fiber?
    While evaluating these “soft” criteria is no easy task, doing so is essential in one’s quest to hire the very best. Yet all too often, attempts at evaluating these crucial, yet elusive, attributes consist of questions or challenges that are sufficiently transparent for the “correct” answers to be obvious to most candidates. Thus, nothing of substance is achieved by asking them.
    A common resulting pitfall is to instead focus too heavily on technical minutia, rather than evaluating the candidate’s ability to problem solve, to think creatively, and to work compatibly with the rest of the team.

    A common pitfall is to focus too heavily on technical minutia.

    Admittedly, effective interviewing and hiring of advanced software developers is as much of an art as it is a science. Nonetheless, approaches and methodologies do exist for evaluating the more subtle dimensions of a software engineer’s skills and abilities.
    When used collectively, these recruiting techniques yield a highly effective screening process with a proven track record of success for hiring salaried or freelance programming talent. That process is what this post is all about.

    Getting Started: Filling the Pipeline with the Best

    The process of finding and hiring the elite few begins long before the interview itself. In fact, a systematic approach to properly identifying potentially qualified candidates can streamline and increase the efficiency of your entire recruiting process significantly.
    Filling the hiring pipeline for software developer talent is crucial to recruiting the very best.
    Without a doubt, the single best source of qualified candidates is personal networking, as quality people tend to associate with quality people. Personal referrals dominate as the most productive source for successful new hires (source).
    Other valuable sources of top-notch technical talent include:

    The beauty of these resources is that they supply candidates who you have vetted, in one way or another, before even interviewing them.
    • Blogs and online technical postings. Developer blogs can be a great source of strong candidates. Technical posts often provide valuable insights into a developer’s technical acumen, approach to problem solving, and writing skills, all of which are important criteria for identifying cream-of-the-crop candidates.
    • Open source code contributors. Perusing open source projects on sites such as GitHub and SourceForge can yield highly qualified candidates. An added benefit of this approach is that it allows you to see and evaluate a candidate’s code samples before even deciding to make contact.
    • Conferences. Conference speakers and co-attendees at relevant technical conferences often provide a valuable resource for qualified candidates. If you are unable to attend, review the online program and consider contacting the presenters. You may just happen to contact them “at the right time”, or they may be able to refer you to someone else who is highly qualified.

    The beauty of these resources is that they supply engineering candidates who you have vetted, in one way or another, before even interviewing them. Either someone in your company, or someone you know, knows them and recommends them highly. Or you have reviewed their open source code and are duly impressed by it. Or their blog posts suggest a mature level of technical expertise and understanding (and ideally even a sense of humor 🙂 ). The key here is that, by the time you make contact, the candidate is already significantly more than “just another resume”.
    Additionally, consider using job description templates (like these for SEO, front-end web development, and back-end web development) that set a high expectation for the types of candidates you desire.

    Evaluating Software Developers’ Technical Acumen

    An effective determination of technical proficiency goes far beyond the nuances of a specific programming language or technology. While these technical details should certainly not be ignored, they typically are not the most important element of the evaluation process.

    An effective determination of technical proficiency goes far beyond the nuances of a specific programming language or technology…
    It is the candidate’s fundamental technical strength and understanding, creative thinking, and problem solving that are critical to evaluate.

    The best developers don’t waste time committing to memory that which can easily be found in a language specification or API document. Moreover, learning a new language, technology, or design pattern is a relatively trivial exercise for a strong developer (and is actually an essential skill given the accelerated rate at which new technologies are being introduced and gaining market share). It is therefore the candidate’s fundamental technical strength and understanding, creative thinking, and problem solving that are critical to evaluate.
    A proven method for accomplishing this is to pose a programming challenge unconstrained by language. Present the candidate with a problem and ask him or her to code a solution in the language of their choosing. The only requirements should be that the solution be thorough and correct, including addressing any edge conditions or potential errors. Remember, the goal here is to evaluate the candidate’s (a) ability to problem solve, (b) knowledge of computer science, and (c) coding style. You’re not at this point evaluating aptitude in a specific programming language. (An added benefit of this approach, incidentally, is that it avoids requiring the interviewer to be an expert in the language the candidate is coding in.)
    Numerous online resources exist from which you can select such programming challenges to incorporate into your interview process. Those that focus on algorithms (rather than knowledge of a specific programming language) facilitate evaluation of a candidate’s computer science foundation and problem solving capabilities. Some noteworthy examples include hackerrank.com, projecteuler.net, and beatmycode.com. Bear in mind, though, that you don’t need to use these sites to administer the tests; rather, you can simply use them as resources from which to select challenges and then have the candidate code a solution during the in person interview (on a white board, etc.).
    That said, online testing can be a valuable additional component of your interview process. When using online testing services, though, it is important to avoid the risk of focusing too heavily on a candidate’s site-generated scores rather than the specifics of their solutions. For one thing, you may not agree with the evaluation metrics employed by the testing service. Moreover, there may be aspects of a solution that you consider particularly clever or elegant, to which the automated evaluation process may be entirely oblivious.

    When using online testing services, it is important to avoid the risk of focusing too heavily on a candidate’s site-generated scores rather than the specifics of their solutions.

    There is also the potential for “false positives” or “false negatives” with ratings provided by online testing services. On the one hand, false positives can result in wasted time and resources interviewing unqualified candidates, while false negatives can disqualify candidates who were highly worthy of consideration. In the long-term, the latter has more serious ramifications and is therefore something that one must carefully monitor for.
    In general, tests administered in person are inherently more reliable than those administered online, since they reduce the potential for deception. Moreover, in-person testing provides the opportunity to observe how a software engineer candidate operates under pressure. Nonetheless, use of online testing services can be an effective component of the more comprehensive type of screening process advocated herein, which incorporates other techniques to help weed out either fraudulent or under-qualified candidates.
    Online development tests can also serve as a valuable preliminary filter to eliminate the staggeringly high percentage of candidates whose technical skills are far below par. Interestingly, many such candidates abandon the process without even trying to take the tests, due to a lack of confidence. That said, confidence is not always the best barometer of attitude, as attested to by the Dunning-Kruger effect.
    Another extremely valuable technique for evaluating technical acumen is to ask the candidate to provide a list of open source projects that they have authored, or at least contributed to, on sites such as GitHub and SourceForge (if they were only a contributor, ask them to indicate to you which portions of the code they personally authored). You can then come to the interview having reviewed their code, prepared to ask them about specific design decisions, coding styles, patterns employed, and so on. Such a discussion can be substantially more valuable than simply quizzing the candidate on the technical minutia of a language.

    Speaking of language…

    Members of the elite few are not just technologically savvy, they are consummate software development professionals who communicate clearly, effectively, and succinctly, both verbally and in writing.
    Verbal communication skills are easy to evaluate in the course of an interview, whether in-person or over the phone. While verbal skills are admittedly less critical in certain “back room” technical roles that don’t involve user contact, they are nonetheless still important for maximizing effective team interactions and interchange of ideas.

    Members of the elite few are consummate professionals who communicate clearly, effectively, and succinctly, both verbally and in writing.

    Written communication skills can best be evaluated by asking the candidate to provide writing samples. Technical writing samples are strongly preferred, since they demonstrate not only writing skills, but also technical clarity. Requesting these samples in advance of the interview can be particularly useful. For one thing, this provides the opportunity to review and analyze their writing ahead of time so that you can come to the interview prepared to discuss and critique their writing with them. In addition, some technical candidates will be “put off” by the request for writing samples which in itself can serve as a valuable filter.

    The Moral Dilemma

    There is an old joke about a father who wants to teach his son about ethics. The father tells his son that he and his partner have a dry cleaning business. “One day,” says the father, “a customer comes into our store to pick up her dry cleaning. As the customer turns around to leave, I realize that she’s overpaid by 10 dollars. OK, so here comes the ethics… do I or don’t I tell my partner?!”

    In contrast, real ethical dilemmas – moral dilemmas – can often be murky and complex and they most certainly present themselves in business. The strongest software developer can wreak untold havoc on a project if he or she lacks a properly calibrated moral compass. This dimension of a candidate is therefore critical to evaluate.

    The strongest software developer can wreak untold havoc on a project if he or she lacks a properly calibrated moral compass.

    A highly effective technique for accomplishing this is to present the candidate with a hypothetical moral dilemma and ask what they would do in the situation. For this to be effective, it is essential that the dilemma not have an obvious answer. Ideally, any possible answer should be imperfect and somewhat problematic. The answer the candidate provides to such a question can provide enormous insight into how they think, their ethical standards, and their priorities.
    Here’s an example:

    The company you work for has been hired to work on a project by another company. The project requires use of a particular subcontractor. You previously worked for that subcontractor and you therefore know first-hand that they often “pad” their hours and overcharge their customers for their time. If they do this on this project, though, it won’t hurt your company, since those costs will be passed on to your company’s customer. You’ve mentioned this to your boss and he has advised you not to say anything to the customer, especially since the subcontractor’s portion of the project only represents a small fraction of the overall budget. You have a very close friend who works for the customer though. One day over lunch, your friend asks you what you know about this subcontractor, since he knows you used to work there. How do you respond and what do you tell him?

    The beauty here is that there’s no clearly “right” answer and the situation mirrors the moral complexity of real life and the business world. If asked properly, the answer to such a “moral dilemma” question can be one of the most telling and valuable parts of the interview process for hiring software developers.

    Getting to Know You (Who are you really?)

    One of the inherent flaws of the interview process is that there is really no way to get to know what it will be like to work with a person until you actually work with them. Getting a realistic feel for a candidate’s personality and temperament is nonetheless crucial to a successful hire.
    The technical elite are not just technically superior, they are also highly professional. The search for them is therefore not limited to a strictly technical evaluation.

    The technical elite are not just technically superior, they are also highly professional.

    With that in mind, here are some interview techniques that can be beneficial for evaluating a candidate’s personality and professionalism…
    For one, consider intentionally beginning the interview process with a prescreen by a non-technical staff member (such as an administrative assistant). You can then ask this staff member how the candidate treated them once they realized that they were not technical. Were they demeaning, impatient, and condescending, or were they pleasant, patient, and respectful? What the staff member relays to you can be very telling indeed. You want to know if the candidate treats others with respect, regardless of who they are.
    Throughout the interview, look for opportunities to provide the candidate with constructive feedback.Observe carefully the reaction that this elicits. Is the feedback appreciated or does the candidate appear to become at all defensive?
    Engage in non-technical “chit chat” for the first 5 or 10 minutes of an interview as a means of obtaining insight into the candidate’s personality. The candidate may think this is simply a prelude to the actual interview and will therefore be more likely to “let their hair down”. You may thereby be able to discern a surprising amount about their personality during this time. And of course, if they exhibit a sense of humor, that’s always a good sign. 🙂
    In addition to these general techniques for hiring engineers, here are some sample questions to help assess a candidate’s personality, confidence, honesty, and professionalism:

    • As you look back on your career, what it is a specific difficult situation you’ve been faced with that stands out in your mind? Describe the challenge and how you dealt with it in detail. What do you feel you handled particularly well? What might you do differently if you had the opportunity to do it over again?
    • What is the biggest mistake you think you ever made in your career?
    • What do you enjoy the most about software development? What do you enjoy the least?
    • If you could paint the ideal position for yourself, what would it be? What would it look like in terms of your role and responsibilities, size and type of company, the work environment and so on?
    • What are your greatest strengths? What would we gain by hiring you?
    • None of us are perfect. What are some aspects of your personality that you’re working on improving?
    • If I called your current boss and asked him about you, what would he or she tell me?
    • What should we be concerned about in hiring you?

    Collectively, these questions and techniques have been proven to foster a much stronger and deeper understanding of who the candidate really is, which is a vital to making a successful hiring decision.

    Is the Feeling Mutual?

    So, you’ve found an A+ candidate. Highly skilled. Positive, upbeat personality. Excellent cultural fit. That’s great! But…
    There’s still one pivotal question that remains to be answered: To what extent is the candidate specifically interested in your available position and in working for your company? The answer to this is of paramount importance in ensuring a successful hire. One-sided relationships work no better in business than they do in any other aspect of our lives.
    Once again, simply asking the question directly is of minimal value since, in the context of the interview process, one must be suspicious of a candidate’s candor in answering such a question. Rather, this is something that one must attempt to ascertain through other, less direct, means.

    One-sided relationships work no better in business than they do in any other aspect of our lives.

    For starters, the way the candidate approaches you from the onset is a fairly reliable gauge of interest. Does the candidate offer a cogent, compelling explanation of why he or she is particularly interested in your company and the available opportunity? If so, this not only displays real interest, but also a level of professional maturity and sophistication. Such a candidate has clearly done at least some level of prior research into your company, and the opportunity, before contacting you (rather than simply “shotgunning their resume around town”).
    Candidates who enter the developer hiring process having done their homework on the company, and its products or services, provide a useful indicator of both their interest and their savvy. Candidates who have gone as far as doing advance research on the interviewer (e.g., reading his or her bio, LinkedIn profile, blog posts, and so on) are particularly noteworthy. More sophisticated candidates will make a point of revealing this information in the course of the interview. For others, simple open-ended questions such as “What do you know about our company?” and “What in particular interests you about our company and this position?” can elicit very telling responses indeed.
    Finally, a candidate who is genuinely interested will likely be asking questions throughout the interview process. That notwithstanding, it’s always a good idea to close the interview by asking if the candidate has any questions. A lack of any questions at all can be a red flag, even with someone who would otherwise have been considered an A+ candidate.

    Wrap Up

    The techniques described herein can serve as a valuable core process for finding and hiring software developers that are the best in the industry. Yet it is important to remember that effective hiring is not a destination, it’s a journey. One must continually re-evaluate and tweak their process, as a static process is destined to become a dead process.

    Effective hiring is not a destination, it’s a journey.

    Every company’s journey will be different, based on its own culture and priorities. Find the path that’s right for your organization and execute on it. You will have successes and you will have failures, but as long as you learn from the latter, you can be assured that you’re on the right path.
    This article originally appeared on Toptal.

  • Why Should Java Developers Give Grails a Chance?

    Java has an ecosystem that has matured through years of development, establishing it as one of the most reliable platforms out there. Yet it lacks the means necessary to get the job done quickly, especially for things like web applications. In an attempt to avoid frustrations with these types of issues, developers often opt instead for implementation languages and their modern web frameworks, such as Ruby with Ruby on Rails, Python with Django, and so on. Unlike Java, these provide a much more streamlined path to building a web application.
    Fortunately, for Java developers wanting to build web applications, there is a better way, and it involves Grails. In this article, we will see how Grails with Groovy is a viable alternative in the JVM realm. We will look at some examples where Grails is appealing to us as Java developers and might tempt someone else to give it a shot as well.

    The Story

    In a startup I worked for, we had this exact problem. We had a Spring application which was becoming a pain to work with. With it growing larger and larger, we soon found that refactoring and adding functionality was taking us way longer than it should. Combining that with some other motivations led us to decide to rewrite our core application. We were also open to changing or replacing existing technology stack. Grails looked like a viable choice since it runs in the JVM and is built on top of technologies we already knew. It uses the Groovy programming language but at the same time allows you to mix it with Java. So we took the plunge.

    Full Speed Ahead

    One thing Grails really excels at is making it easy to start a new project. It is as simple as running a command which creates the project structure with all the folders needed for the classes you will add later. Adding model classes, controllers, services and web pages takes a similarly minimal amount of effort. The only thing you need to take care of is naming and placing stuff correctly. Unlike Java, there is virtually no boilerplate code that needs to be there just because it needs to be. This is partially made possible by using Spring and Hibernate which are two of the pillars of Grails, as well as the concept of coding by convention. To run the project, Grails comes bundled with Apache Tomcat as a development server. All we have to do is run the project in our IDE and the server will be fired up with our code deployed. Also, the Grails’ Object Relational Mapping (GORM)with Hibernate will take care of creating the database for us. To use an existing database, we need to configure the JDBC connection properties or just leave it by default to use an in-memory instance. Once the server with Grails is running (takes a little bit more than a Spring MVC application), we can modify the code and the hot deploy functionality will keep our debug session equipped with the latest version. The only classes that cannot get reloaded this way are the entity classes.
    Populating the database can be done by using SQL scripts, but that can get tedious. All Grails projects contain a Bootstrap class which will be run when our application is run. In this class, we can store or modify data and thus initialize our application state. This proved very useful for us so we have some test cases in development version right away.

    Manipulating Data

    One of the things that immediately caught our attention with Grails was the ease of working with data. Reading from the database is a task that needs to be done over and over. And many times it is simple. Like fetching one or more entities which meet certain criteria and then aggregating them. Why not use a dynamic finder for that? It is a way of querying data where methods are dynamically created at runtime. All you have to do is follow a naming convention.

    def users = User.findAllByLastNameLikeOrAgeGreaterThan(‘Doe%’, 30)
    

    The line above line will fetch all User objects with last name starting with “Doe” or age greater than 30. Yes, not a very sophisticated case but you get the gist.
    What if we wanted to filter this list additionally for the ones that have the “failedLogins” property greater than 10? And what if we wanted to sort them by their date created? And what if we wanted to get their first names concatenated or find the maximum age of the users returned?

    users = users.findAll() { it.failedLogins > 10 }
    users = users.sort { it.dateCreated }
    def firstNamesString = users.firstName.join(‘, ‘)
    def maximumAge = users.age.max()
    

    The above examples may look simple, but they show how powerful Grails can be for querying, filtering, and manipulating data. In Java 8, you can achieve similar results for some of these cases, but it will still require more code than Grails.

    Sometimes I Want to Create Differently

    A dynamic constructor or named argument constructor is a feature that many of us wanted to have in Java. It’s nice to define which constructors a certain class allows, but in many cases you just want to set some properties and get the darn instance. Groovy adds a special constructor for each entity which basically takes the elegance of a map as input and sets the properties with the map entries.

    def Person = new Person(name: 'Batman', age: 57)
    

    This approach leads to code that is much more expressive and avoids the need for all the constructor boilerplate code.
    And BTW, here are some examples of the awesomeness and elegance of Groovy’s maps:

    def emptyMap = [:]
    def map = [bread:3, milk:5, butter:2]
    map[‘bread’] = 4
    map.milk = 6
    

    This is another example of how the code can be short and simple, yet powerful. It shows how inline initialization can be used and how map values can be manipulated in a way similar to object properties. No need to call traditional Java methods for basic manipulation, unless you really want to.

    We Need More Power!

    Of course, there is no framework that can do everything, but when we’re filling in the gaps, we should see what else might already be available before trying to implement our own solution. To expand our arsenal of Grails-based functionality, we can use Grails Plugins. Installing a plugin is simply done by adding another line in the BuildConfig class that is present in every Grails project (code convention strikes again!).

    compile ':spring-security-core:2.0-RC4'
    

    The line above adds the Spring security core to our application and there is virtually no more configuration needed to incorporate this functionality.

    It’s similar to using Maven dependencies (which you can also reference in the same config class), but the plugins are usually larger blocks that contain the whole functionality.

    That being said, let me tell you about a case we had to deal with. We needed to implement a search spanning across several data entities. Grails has an Elasticsearch plugin which is a breeze to use. As mentioned before, we only need to reference the plugin in the config file and we’re good to go. If we want to search for entities of a certain class, we just need to add a static “searchable” property to that class. And if we want, we can even limit the properties that will be allowed to be searched.

    class User {
        static searchable = { only = name }
        String name
        Double salary
    }
    

    It is so little code, but under the hood, Grails and the Elasticsearch plugin will automatically index all users by name and enable us to search by name. The actual search call is also very concise:

    User.search("${params.query}")
    

    If we don’t want to, we will never have to touch the Lucene index. All will be done auto-magically for us. The plugin even has an API for displaying search results – it can highlight the match found inside searched text. This is just an example how a plugin can provide a huge bundle of functionality which can make us that much more efficient by avoiding the need for us to implement it ourselves.

    We Still Need More Power

    Plugins are great, but sometimes we don’t need a whole plugin, we just want something extra. Do you remember the last time you wanted to have an additional method on an existing Java class but you didn’t want tp (or couldn’t) extend/override them? In Groovy, you can add methods and properties to existing classes, or even just certain instances of them. For instance, you can add a formatting method to the java.util.Date class which is awesome when you want to format dates consistently and just don’t want to write static util classes or define various filters.

    Date.metaClass.formatDate = { delegate.format("dd.MM.yyyy") }
    

    What if you want to sort a list of users by a computed value and you only need this in one case (i.e. adding a new method in User class would be polluting)? You could add a property on each of those instances and then just sort or filter the collection by that property:

    user.metaClass.computedProp = 312 * 32 * 3
    

    Groovy authors have already added a lot of enhancements to some of the core Java classes, so we don’t have to. Below are some examples.
    Using “minus” to remove all elements from a collection that are present in another collection.

    assert [1, 2, 3, 4, 4, 5] - [2, 4] == [1, 3, 5]
    

    Additional methods for manipulating java.util.Date objects which come in handy so many times, such as adding/subtracting days from dates or getting/setting a certain field of the date without converting it to Calendaror using additional libraries.

    def yesterdayAllMyTroublesSeemedSoFarAway = new Date() - 1
    def myAwesomeAnniversaryYear = myAwesomeDate[Calendar.YEAR] + 1
    myAwesomeDate.set(year: myAwesomeAnniversaryYear, second: 0)
    

    When you want to really get descriptive with date manipulation, you can simply use the Groovy added TimeCategory class:

    use (TimeCategory) {
    println 1.minute.from.now
    	println 10.hours.ago
    	def someDate = new Date()
    	println someDate - 3.months
    }
    

    A Hammer and a Nail

    Then there are the IDEs. Eclipse-based GGTS and IntelliJ IDEA are set-up for working with Grails. They understand the project structure (and will help you navigate through folders and resources) and have shortcuts for the commands you will most often use (e.g., add controller, add a page, run a project, etc.). With Grails you will execute commands (to run a project or set-up a new plugin functionality) and you will need different configurations, which is also covered by the IDEs. Code completion works nicely in Grails web template pages where you will often reference controllers and actions.There are also other IDEs that can be used with Grails such as Netbeans, TextMate, Emacs and others.

    What About the Dark Side?

    Just as with everything in life, there are caveats with Grails also. There is a lot of magic being done under the hood which can often be a good thing, but sometimes the result will not be what you expected. Bugs will happen just because of not using typing (yes, types are optional in Groovy) and not being careful enough. And maybe you won’t notice an error until it’s too late. Also, it’s very tempting to write one-liners to impress your coworkers. And yourself. But these powerful lines of code might not be as self-explanatory to your coworkers. Or even to yourself in a couple of months. That’s why I think Grails demands more programming discipline than some of the more traditional frameworks.

    Time is Money

    Coding shouldn’t take more time just because your current framework demands it to. Especially with the increasingly huge number of startups these days, it’s important to focus on the tasks that really matter and to be as efficient as possible. Time is indeed money and time to market is critical. You need to be able to act quickly and implement the solution before time runs out and your competition beats you to it.
    My friends working with Ruby on Rails or Python/Django have long been telling me how cool those technologies are. And it really felt silly to think how much more time it took me in Java to write code that stores something in database and displays it in a web page. Grails may indeed be a useful answer. It’s not that you couldn’t do this with pure Java, Spring MVC, and Hibernate. You could. Your application might even run a little faster. But you will get the job done faster with Grails.
    This post originally appeared in Toptal Engineering blog

  • Clean Code and The Art of Exception Handling

    Exceptions are as old as programming itself. Back in the days when programming was done in hardware, or via low-level programming languages, exceptions were used to alter the flow of the program, and to avoid hardware failures. Today, Wikipedia defines exceptions as:

    anomalous or exceptional conditions requiring special processing – often changing the normal flow of program execution…

    And that handling them requires:

    specialized programming language constructs or computer hardware mechanisms.

    So, exceptions require special treatment, and an unhandled exception may cause unexpected behavior. The results are often spectacular. In 1996, the famous Ariane 5 rocket launch failure was attributed to an unhandled overflow exception. History’s Worst Software Bugs contains some other bugs that could be attributed to unhandled or miss-handled exceptions.
    Over time, these errors, and countless others (that were, perhaps, not as dramatic, but still catastrophic for those involved) contributed to the impression that exceptions are bad.
    The results of improperly handling exceptions have led us to believe that exceptions are always bad.
    But exceptions are a fundamental element of modern programming; they exist to make our software better. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable.

    Exception Handling: It’s a Good Thing

    With the rise of object-oriented programming (OOP), exception support has become a crucial element of modern programming languages. A robust exception handling system is built into most languages, nowadays. For example, Ruby provides for the following typical pattern:

    begin
      do_something_that_might_not_work!
    rescue SpecificError => e
      do_some_specific_error_clean_up
      retry if some_condition_met?
    ensure
      this_will_always_be_executed
    end
    

    There is nothing wrong with the previous code. But overusing these patterns will cause code smells, and won’t necessarily be beneficial. Likewise, misusing them can actually do a lot of harm to your code base, making it brittle, or obfuscating the cause of errors.
    The stigma surrounding exceptions often makes programmers feel at a loss. It’s a fact of life that exceptions can’t be avoided, but we are often taught they must be dealt with swiftly and decisively. As we will see, this is not necessarily true. Rather, we should learn the art of handling exceptions gracefully, making them harmonious with the rest of our code.
    Following are some recommended practices that will help you embrace exceptions and make use of them and their abilities to keep your code maintainable, extensible, and readable:

    • maintainability: Allows us to easily find and fix new bugs, without the fear of breaking current functionality, introducing further bugs, or having to abandon the code altogether due to increased complexity over time.
    • extensibility: Allows us to easily add to our code base, implementing new or changed requirements without breaking existing functionality. Extensibility provides flexibility, and enables a high level of reusability for our code base.
    • readability: Allows us to easily read the code and discover it’s purpose without spending too much time digging. This is critical for efficiently discovering bugs and untested code.

    These elements are the main factors of what we might call cleanliness or quality, which is not a direct measure itself, but instead is the combined effect of the previous points, as demonstrated in this comic:
    "WTFs/m" by Thom Holwerda, OSNews
    With that said, let’s dive into these practices and see how each of them affects those three measures.
    Note: We will present examples from Ruby, but all of the constructs demonstrated here have equivalents in the most common OOP languages.

    Always create your own ApplicationError hierarchy

    Most languages come with a variety of exception classes, organized in an inheritance hierarchy, like any other OOP class. To preserve the readability, maintainability, and extensibility of our code, it’s a good idea to create our own subtree of application-specific exceptions that extend the base exception class. Investing some time in logically structuring this hierarchy can be extremely beneficial. For example:

    class ApplicationError < StandardError; end
    # Validation Errors
    class ValidationError < ApplicationError; end
    class RequiredFieldError < ValidationError; end
    class UniqueFieldError < ValidationError; end
    # HTTP 4XX Response Errors
    class ResponseError < ApplicationError; end
    class BadRequestError < ResponseError; end
    class UnauthorizedError < ResponseError; end
    # ...
    

    Example of an application exception hierarchy.
    Having an extensible, comprehensive exceptions package for our application makes handling these application-specific situations much easier. For example, we can decide which exceptions to handle in a more natural way. This not only boosts the readability of our code, but also increases the maintainability of our applications and libraries (gems).
    From the readability perspective, it’s much easier to read:

    rescue ValidationError => e
    

    Than to read:

    rescue RequiredFieldError, UniqueFieldError, ... => e
    

    From the maintainability perspective, say, for example, we are implementing a JSON API, and we have defined our own ClientError with several subtypes, to be used when a client sends a bad request. If any one of these is raised, the application should render the JSON representation of the error in its response. It will be easier to fix, or add logic, to a single block that handles ClientErrors rather than looping over each possible client error and implementing the same handler code for each. In terms of extensibility, if we later have to implement another type of client error, we can trust it will already be handled properly here.
    Moreover, this does not prevent us from implementing additional special handling for specific client errors earlier in the call stack, or altering the same exception object along the way:

    # app/controller/pseudo_controller.rb
    def authenticate_user!
      fail AuthenticationError if token_invalid? || token_expired?
      User.find_by(authentication_token: token)
    rescue AuthenticationError => e
      report_suspicious_activity if token_invalid?
      raise e
    end
    def show
      authenticate_user!
      show_private_stuff!(params[:id])
    rescue ClientError => e
      render_error(e)
    end
    

    As you can see, raising this specific exception didn’t prevent us from being able to handle it on different levels, altering it, re-raising it, and allowing the parent class handler to resolve it.
    Two things to note here:

    • Not all languages support raising exceptions from within an exception handler.
    • In most languages, raising a new exception from within a handler will cause the original exception to be lost forever, so it’s better to re-raise the same exception object (as in the above example) to avoid losing track of the original cause of the error. (Unless you are doing this intentionally).

    Never rescue Exception

    That is, never try to implement a catch-all handler for the base exception type. Rescuing or catching all exceptions wholesale is never a good idea in any language, whether it’s globally on a base application level, or in a small buried method used only once. We don’t want to rescue Exception because it will obfuscate whatever really happened, damaging both maintainability and extensibility. We can waste a huge amount of time debugging what the actual problem is, when it could be as simple as a syntax error:

    # main.rb
    def bad_example
      i_might_raise_exception!
    rescue Exception
      nah_i_will_always_be_here_for_you
    end
    # elsewhere.rb
    def i_might_raise_exception!
      retrun do_a_lot_of_work!
    end
    

    You might have noticed the error in the previous example; return is mistyped. Although modern editors provide some protection against this specific type of syntax error, this example illustrates how rescue Exception does harm to our code. At no point is the actual type of the exception (in this case a NoMethodError) addressed, nor is it ever exposed to the developer, which may cause us to waste a lot of time running in circles.

    Never rescue more exceptions than you need to

    The previous point is a specific case of this rule: We should always be careful not to over-generalize our exception handlers. The reasons are the same; whenever we rescue more exceptions than we should, we end up hiding parts of the application logic from higher levels of the application, not to mention suppressing the developer’s ability to handle the exception his or herself. This severely affects the extensibility and maintainability of the code.
    If we do attempt to handle different exception subtypes in the same handler, we introduce fat code blocks that have too many responsibilities. For example, if we are building a library that consumes a remote API, handling a MethodNotAllowedError (HTTP 405), is usually different from handling an UnauthorizedError (HTTP 401), even though they are both ResponseErrors.
    As we will see, often there exists a different part of the application that would be better suited to handle specific exceptions in a more DRY way.
    So, define the single responsibility of your class or method, and handle the bare minimum of exceptions that satisfy this responsibility requirement. For example, if a method is responsible for getting stock info from a remote a API, then it should handle exceptions that arise from getting that info only, and leave the handling of the other errors to a different method designed specifically for these responsibilities:

    def get_info
      begin
        response = HTTP.get(STOCKS_URL + "#{@symbol}/info")
        fail AuthenticationError if response.code == 401
        fail StockNotFoundError, @symbol if response.code == 404
        return JSON.parse response.body
      rescue JSON::ParserError
        retry
      end
    end
    

    Here we defined the contract for this method to only get us the info about the stock. It handles endpoint-specific errors, such as an incomplete or malformed JSON response. It doesn’t handle the case when authentication fails or expires, or if the stock doesn’t exist. These are someone else’s responsibility, and are explicitly passed up the call stack where there should be a better place to handle these errors in a DRY way.

    Resist the urge to handle exceptions immediately

    This is the complement to the last point. An exception can be handled at any point in the call stack, and any point in the class hierarchy, so knowing exactly where to handle it can be mystifying. To solve this conundrum, many developers opt to handle any exception as soon as it arises, but investing time in thinking this through will usually result in finding a more appropriate place to handle specific exceptions.
    One common pattern that we see in Rails applications (especially those that expose JSON-only APIs) is the following controller method:

    # app/controllers/client_controller.rb
    def create
      @client = Client.new(params[:client])
      if @client.save
        render json: @client
      else
        render json: @client.errors
      end
    end
    

    (Note that although this is not technically an exception handler, functionally, it serves the same purpose, since @client.save only returns false when it encounters an exception.)
    In this case, however, repeating the same error handler in every controller action is the opposite of DRY, and damages maintainability and extensibility. Instead, we can make use of the special nature of exception propagation, and handle them only once, in the parent controller class, ApplicationController:

    # app/controllers/client_controller.rb
    def create
      @client = Client.create!(params[:client])
      render json: @client
    end
    
    # app/controller/application_controller.rb
    rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity
    def render_unprocessable_entity(e)
      render \
        json: { errors: e.record.errors },
        status: 422
    end
    

    This way, we can ensure that all of the ActiveRecord::RecordInvalid errors are properly and DRY-ly handled in one place, on the base ApplicationController level. This gives us the freedom to fiddle with them if we want to handle specific cases at the lower level, or simply let them propagate gracefully.

    Not all exceptions need handling

    When developing a gem or a library, many developers will try to encapsulate the functionality and not allow any exception to propagate out of the library. But sometimes, it’s not obvious how to handle an exception until the specific application is implemented.
    Let’s take ActiveRecord as an example of the ideal solution. The library provides developers with two approaches for completeness. The save method handles exceptions without propagating them, simply returning false, while save! raises an exception when it fails. This gives developers the option of handling specific error cases differently, or simply handling any failure in a general way.
    But what if you don’t have the time or resources to provide such a complete implementation? In that case, if there is any uncertainty, it is best to expose the exception, and release it into the wild.
    Sometimes the best way to handle an exception is to let it fly free.
    Here’s why: We are working with moving requirements almost all the time, and making the decision that an exception will always be handled in a specific way might actually harm our implementation, damaging extensibility and maintainability, and potentially adding huge technical debt, especially when developing libraries.
    Take the earlier example of a stock API consumer fetching stock prices. We chose to handle the incomplete and malformed response on the spot, and we chose to retry the same request again until we got a valid response. But later, the requirements might change, such that we must fall back to saved historical stock data, instead of retrying the request.
    At this point, we will be forced to change the library itself, updating how this exception is handled, because the dependent projects won’t handle this exception. (How could they? It was never exposed to them before.) We will also have to inform the owners of projects that rely on our library. This might become a nightmare if there are many such projects, since they are likely to have been built on the assumption that this error will be handled in a specific way.
    Now, we can see where we are heading with dependencies management. The outlook is not good. This situation happens quite often, and more often than not, it degrades the library’s usefulness, extensibility, and flexibility.
    So here is the bottom line: if it is unclear how an exception should be handled, let it propagate gracefully. There are many cases where a clear place exists to handle the exception internally, but there are many other cases where exposing the exception is better. So before you opt into handling the exception, just give it a second thought. A good rule of thumb is to only insist on handling exceptions when you are interacting directly with the end-user.

    Follow the convention

    The implementation of Ruby, and, even more so, Rails, follows some naming conventions, such as distinguishing between method_names and method_names! with a “bang.” In Ruby, the bang indicates that the method will alter the object that invoked it, and in Rails, it means that the method will raise an exception if it fails to execute the expected behavior. Try to respect the same convention, especially if you are going to open-source your library.
    If we were to write a new method! with a bang in a Rails application, we must take these conventions into account. There is nothing forcing us to raise an exception when this method fails, but by deviating from the convention, this method may mislead programmers into believing they will be given the chance to handle exceptions themselves, when, in fact, they will not.
    Another Ruby convention, attributed to Jim Weirich, is to use fail to indicate method failure, and only to use raise if you are re-raising the exception.

    “An aside, because I use exceptions to indicate failures, I almost always use the “fail” keyword rather than the “raise” keyword in Ruby. Fail and raise are synonyms so there is no difference except that “fail” more clearly communicates that the method has failed. The only time I use “raise” is when I am catching an exception and re-raising it, because here I’m not failing, but explicitly and purposefully raising an exception. This is a stylistic issue I follow, but I doubt many other people do.”

    Many other language communities have adopted conventions like these around how exceptions are treated, and ignoring these conventions will damage the readability and maintainability of our code.

    Logger.log(everything)

    This practice doesn’t solely apply to exceptions, of course, but if there’s one thing that should always be logged, it’s an exception.
    Logging is extremely important (important enough for Ruby to ship a logger with its standard version). It’s the diary of our applications, and even more important than keeping a record of how our applications succeed, is logging how and when they fail.
    There is no shortage of logging libraries or log-based services and design patterns. It’s critical to keep track of our exceptions so we can review what happened and investigate if something doesn’t look right. Proper log messages can point developers directly to the cause of a problem, saving them immeasurable time.

    That Clean Code Confidence

    Proper exception handling allows for clean code and successful software.

    Clean exception handling will send your code quality to the moon!

    Exceptions are a fundamental part of every programming language. They are special and extremely powerful, and we must leverage their power to elevate the quality of our code instead of exhausting ourselves fighting with them.
    In this article, we dived into some good practices for structuring our exception trees and how it can be beneficial for readability and quality to logically structure them. We looked at different approaches for handling exceptions, either in one place or on multiple levels.
    We saw that it’s bad to “catch ‘em all”, and that it’s ok to let them float around and bubble up.
    We looked at where to handle exceptions in a DRY manner, and learned that we are not obligated to handle them when or where they first arise.
    We discussed when exactly it is a good idea to handle them, when it’s a bad idea, and why, when in doubt, it’s a good idea to let them propagate.
    Finally, we discussed other points that can help maximize the usefulness of exceptions, such as following conventions and logging everything.
    With these basic guidelines, we can feel much more comfortable and confident dealing with error cases in our code, and making our exceptions truly exceptional!
    Special thank to Avdi Grimm and his awesome talk Exceptional Ruby, which helped a lot in the making of this article.
    The author of this post is Ahmed AbdelRazzak & the originally published on Toptal.

  • Gulp: A Web Developer's Secret Weapon for Maximizing Site Speed

    Many of us have to handle web based projects that are used in production, which provide various services to the public. When dealing with such projects, it is important to be able to build and deploy our code quickly. Doing something quickly often leads to errors, especially if a process is repetitive, therefore it’s a good practice to automate such a process as much as possible.
    Gulp: A Web Developer's Secret Weapon for Maximizing Site Speed

    My fellow developers: There is no excuse for serving junk to your browser.

    In this post, we will be looking at a tool that can be a part of what will allow us to achieve such automation. This tool is an npm package called Gulp.js. In order to become familiar with the basic Gulp.js terminology used in this post, please refer to “An Introduction to JavaScript Automation with Gulp” that was previously published on the blog by Antonios Minas, one of our fellow Toptal developers. We will assume basic familiarity with the npm environment, as it is used extensively throughout this post to install packages.

    Serving Front-End Assets

    Before we continue, let’s take a few steps back to get an overview of the problem that Gulp.js can solve for us. Many web-based projects feature front-end JavaScript files that are served to the client in order to provide various functionalities to the web page. Usually there’s also a set of CSS stylesheets that are served to the client as well. Sometimes when looking at the source code of a website or a web application, we can see code like this:

    <link href="css/main.css" rel="stylesheet">
    <link href="css/custom.css" rel="stylesheet">
    <script src="js/jquery.min.js"></script>
    <script src="js/site.js"></script>
    <script src="js/module1.js"></script>
    <script src="js/module2.js"></script>
    

    There are a few problems with this code. It has references to two separate CSS stylesheets and four separate JavaScript files. This means that the server has to make a total of six requests to the server, and each request has to separately load a resource before the page will be ready. This is less of an issue with HTTP/2 because HTTP/2 introduces parallelism and header compression, but it’s still an issue. It increases the total volume of traffic that is required to load this page, and reduces the quality of user experience because it takes longer to load the files. In case of HTTP 1.1, it also hogs the network and reduces the number of request channels that are available. It would have been much better to combine the CSS and JavaScript files into a single bundle for each. That way, there would be only a total of two requests. It would also have been nice to serve minified versions of these files, which are usually much smaller than the originals. Our web application might also break if any of the assets are cached, and the client would receive an outdated version.
    Overload
    One primitive approach to solving some of these problems is to manually combine each type of asset into a bundle using a text editor, and then run the result through a minifier service, such as https://jscompress.com/. This proves to be very tedious to do continuously during the development process. A slight but questionable improvement would be to host our own minifier server, using one of the packages available on GitHub. Then we could do things that would look somewhat similar to the following:

    <script src="min/f=js/site.js,js/module1.js"></script>
    

    This would serve minified files to our client, but it would not solve the problem of caching. It would also cause additional load on the server, since our server would essentially have to concatenate and minify all the source files repetitively on every request.

    Automating with Gulp.js

    Surely we can do better than either of these two approaches. What we really want is to automate bundling and include it in the build phase of our project. We want to end up with pre-built asset bundles that are already minified and are ready to serve. We also want to force the client to receive the most up to date versions of our bundled assets on every request, but we still want to leverage caching if possible. Luckily for us, Gulp.js can handle that. In the remainder of the article, we will be building a solution that will leverage the power of Gulp.js to concatenate and minify the files. We will also be using a plugin to bust the cache when there are updates.
    We will be creating the following directory and file structure in our example:

    public/
    |- build/
       |- js/
          |- bundle-{hash}.js
       |- css/
          |- stylesheet-{hash}.css
    assets/
    |- js/
       |- vendor/
       |- jquery.js
       |- site.js
       |- module1.js
       |- module2.js
    |- css/
       |- main.css
       |- custom.css
    gulpfile.js
    package.json
    
    npm makes package management in Node.js projects a bliss. Gulp provides tremendous extensibility by taking advantage of npm’s simple packaging approach to deliver modular and powerful plugins.

    The gulpfile.js file is where we will define the tasks that Gulp will perform for us. The package.json is used by npm to define our application’s package and track the dependencies that we will be installing. The public directory is what should be configured to face the web. The assets directory is where we will store our source files. To use Gulp in the project, we will need to install it via npm, and save it as a developer dependency for the project. We will also want to start with the concat plugin for Gulp, which will allow us to concatenate multiple files into one.
    To install these two items, we will run the following command:

    npm install --save-dev gulp gulp-concat
    

    Next, we will want to begin writing the content of gulpfile.js.

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    gulp.task('pack-js', function () {
    	return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
    		.pipe(concat('bundle.js'))
    		.pipe(gulp.dest('public/build/js'));
    });
    gulp.task('pack-css', function () {
    	return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
    		.pipe(concat('stylesheet.css'))
    		.pipe(gulp.dest('public/build/css'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    Here, we are loading the gulp library and its concat plugin. We then define three tasks.

    The first task (pack-js) defines a procedure to compress multiple JavaScript source files into one bundle. We list the source files, which will be globbed, read, and concatenated in the order specified. We pipe that into the concat plugin to get one final file called bundle.js. Finally, we tell gulp to write the file to public/build/js.
    The second task (pack-css) does the same thing as above, but for the CSS stylesheets. It tells Gulp to store the concatenated output as stylesheet.css in public/build/css.
    The third task (default) is the one Gulp runs when we invoke it with no arguments. In the second parameter, we pass the list of other tasks to execute when the default task is ran.
    Let’s paste this code into gulpfile.js using any source code editor that we normally use, and then save the file to the application root.
    Next, we will open the command line and run:

    gulp
    

    If we look at our files after running this command, we will find two new files: public/build/js/bundle.js and public/build/css/stylesheet.css. They are concatenations of our source files, which solves part of the original problem. However, they are not minified, and there is no cache busting yet. Let’s add automated minification.

    Optimizing Built Assets

    We will need two new plugins. To add them, we will run the following command:

    npm install --save-dev gulp-clean-css gulp-minify
    

    The first plugin is for minifying CSS, and the second one is for minifying JavaScript. The first one uses the clean-css package, and the second one uses the UglifyJS2 package. We will load these two packages in our gulpfile.js first:

    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    

    We will then need to use them in our tasks just before we write the output to disk:

    .pipe(minify())
    .pipe(cleanCss())
    

    The gulpfile.js should now look like this:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    gulp.task('pack-js', function () {
    	return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
    		.pipe(concat('bundle.js'))
    		.pipe(minify())
    		.pipe(gulp.dest('public/build/js'));
    });
    gulp.task('pack-css', function () {
    	return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
    		.pipe(concat('stylesheet.css'))
    		.pipe(cleanCss())
       .pipe(gulp.dest('public/build/css'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    Let’s run gulp again. We will see that the file stylesheet.css is saved in minified format, and the file bundle.js is still saved as is. We will notice that we now also have bundle-min.js, which is minified. We want only the minified file, and we want it saved as bundle.js, so we will modify our code with additional parameters:

    .pipe(minify({
    	ext:{
    		min:'.js'
    	},
    	noSource: true
    }))
    

    As per gulp-minify plugin documentation (https://www.npmjs.com/package/gulp-minify), this will set the desired name for the minified version, and tell the plugin not to create the version containing the original source. If we delete the content of the build directory and run gulp from the command line again, we will end up with just two minified files. We have just finished implementing the minification phase of our build process.

    Cache Busting

    Next, we will want to add cache busting, and we will need to install a plugin for that:

    npm install --save-dev gulp-rev
    

    And require it in our gulp file:

    var rev = require('gulp-rev');
    

    Using the plugin is a bit tricky. We have to pipe the minified output through the plugin first. Then, we have to call the plugin again after we write the results to disk. The plugin renames the files so that they are tagged with a unique hash, and it also creates a manifest file. The manifest file is a map that can be used by our application to determine the latest filenames that we should refer to in our HTML code. After we modify the gulp file, it should end up looking like this:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    var rev = require('gulp-rev');
    gulp.task('pack-js', function () {
        return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
            .pipe(concat('bundle.js'))
            .pipe(minify({
                ext:{
                    min:'.js'
                },
                noSource: true
            }))
            .pipe(rev())
            .pipe(gulp.dest('public/build/js'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('public/build'));
    });
    gulp.task('pack-css', function () {
        return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
            .pipe(concat('stylesheet.css'))
            .pipe(cleanCss())
            .pipe(rev())
                .pipe(gulp.dest('public/build/css'))
            .pipe(rev.manifest())
            .pipe(gulp.dest('public/build'));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    
    With proper cache busting in place, you can go nuts with long expiry time for your JS and CSS files and reliably replace them still with newer versions whenever necessary.

    Let’s delete the contents of our build directory and run gulp again. We will find that we now have two files with hash tags affixed to each of the filenames, and a manifest.json saved to public/build. If we open the manifest file, we will see that it only has a reference to one of our minified and tagged files. What is happening is that each task writes a separate manifest file, and one of them ends up overwriting the other. We will need to modify the tasks with additional parameters that will tell them to look for the existing manifest file, and to merge the new data into it if it exists. The syntax for that is a bit complicated, so let’s look at what the code should look like and then go over it:

    var gulp = require('gulp');
    var concat = require('gulp-concat');
    var minify = require('gulp-minify');
    var cleanCss = require('gulp-clean-css');
    var rev = require('gulp-rev');
    gulp.task('pack-js', function () {
        return gulp.src(['assets/js/vendor/*.js', 'assets/js/main.js', 'assets/js/module*.js'])
            .pipe(concat('bundle.js'))
            .pipe(minify({
                ext:{
                    min:'.js'
                },
                noSource: true
            }))
            .pipe(rev())
            .pipe(gulp.dest('public/build/js'))
            .pipe(rev.manifest('public/build/rev-manifest.json', {
                merge: true
            }))
            .pipe(gulp.dest(''));
        });
    gulp.task('pack-css', function () {
        return gulp.src(['assets/css/main.css', 'assets/css/custom.css'])
            .pipe(concat('stylesheet.css'))
            .pipe(cleanCss())
            .pipe(rev())
            .pipe(gulp.dest('public/build/css'))
            .pipe(rev.manifest('public/build/rev-manifest.json', {
                merge: true
            }))
            .pipe(gulp.dest(''));
    });
    gulp.task('default', ['pack-js', 'pack-css']);
    

    We are piping the output to rev.manifest() first. This creates tagged files instead of the files that we had before. We are providing the desired path of our rev-manifest.json, and telling rev.manifest() to merge into the existing file, if it exists. Then we are telling gulp to write the manifest to the current directory, which at that point will be public/build. The path issue is due to a bug that is discussed in more detail on GitHub.
    We now have automated minification, tagged files, and a manifest file. All of this will allow us to deliver the files more quickly to the user, and bust their cache whenever we make our modifications. There are just two remaining problems though.
    The first problem is that if we make any modifications to our source files, we will get new tagged files, but the old ones will remain there as well. We need some way to automatically delete old minified files. Let’s solve this problem using a plugin that will allow us to delete files:

    npm install --save-dev del
    

    We will require it in our code and define two new tasks, one for each type of source file:

    var del = require('del');
    gulp.task('clean-js', function () {
    	return del([
    		'public/build/js/*.js'
    	]);
    });
    gulp.task('clean-css', function () {
    	return del([
    		'public/build/css/*.css'
    	]);
    });
    

    We will then make sure that the new task finishes running before our two main tasks:

    gulp.task('pack-js', ['clean-js'], function () {
    gulp.task('pack-css', ['clean-css'], function () {
    

    If we run gulp again after this modification, we will have just the latest minified files.
    The second problem is that we don’t want to keep running gulp every time we make a change. To solve this, we will need to define a watcher task:

    gulp.task('watch', function() {
     gulp.watch('assets/js/**/*.js', ['pack-js']);
     gulp.watch('assets/css/**/*.css', ['pack-css']);
    });
    

    We will also change the definition of our default task:

    gulp.task('default', ['watch']);
    

    If we now run gulp from the command line, we will find that it no longer builds anything upon invocation. This is because it now calls the watcher task that will watch our source files for any changes, and build only when it detects a change. If we try changing any of our source files, and then look at our console again, we will see that the pack-js and pack-css tasks run automatically along with their dependencies.
    Now, all we have to do is load the manifest.json file in our application and get the tagged filenames from that. How we do that depends on our particular back-end language and technology stack, and would be quite trivial to implement, so we will not go over it in detail. However, the general idea, is that we can load the manifest into an array or an object, and then define a helper function that will allow us to call versioned assets from our templates in a manner similar to the following:

    gulp(‘bundle.js’)
    

    Once we do that, we will not have to worry about changed tags in our filenames ever again, and we will be able to focus on writing high quality code.
    The final source code for this article, along with a few sample assets, can be found in this GitHub repository.

    Conclusion

    In this article, we went over how to implement Gulp based automation for our build process. I hope that this proves helpful to you and allows you to develop more sophisticated build processes in your own applications.
    Please keep in mind that Gulp is just one of the tools that can be used for this purpose, and there are many others such as Grunt, Browserify, and Webpack. They vary in their purposes and in the scope of problems that they can solve. Some can solve problems that Gulp cannot, such as bundling JavaScript modules with dependencies that can be loaded on demand. This is referred to as “code splitting”, and it is an improvement over the idea of serving one big file with all parts of our program on every page. These tools are quite sophisticated, but might be covered in the future. In a following post, we will go over how to automate the deployment of our application.
    This post was originally published on Toptal Engineering blog

  • Getting Started with Elixir Programming Language

    If you have been reading blog posts, hacker news threads, your favorite developers tweets or listening to podcasts, at this point you’ve probably heard about the Elixir programming language. The language was created by José Valim, a well known developer in the open-source world. You may know him from the Ruby on Rails MVC framework or from devise and simple_form ruby gems him and his co-workers from the Plataformatec have been working on in the last few years.
    According the José Valim, Elixir was born in 2011. He had the idea to build the new language due the lack of good tools to solve the concurrency problems in the ruby world. At that time, after spending time studying concurrency and distributed focused languages, he found two languages that he liked, Erlang and Clojure which run in the JVM. He liked everything he saw in the Erlang language (Erlang VM) and he hated the things he didn’t see, like polymorphism, metaprogramming and language extendability attributes which Clojure was good at. So, Elixir was born with that in mind, to have an alternative for Clojure and a dynamic language which runs in the Erlang Virtual Machine with good extendability support.
    Getting Started with Elixir Programming Language
    Elixir describes itself as a dynamic, functional language with immutable state and an actor based approach to concurrency designed for building scalable and maintainable applications with a simple, modern and tidy syntax. The language runs in the Erlang Virtual Machine, a battle proof, high-performance and distributed virtual machine known for its low latency and fault tolerance characteristics.
    Before we see some code, it’s worth saying that Elixir has been accepted by the community which is growing. If you want to learn Elixir today you will easily find books, libraries, conferences, meetups, podcasts, blog posts, newsletters and all sorts of learning sources out there as well as it was accepted by the Erlang creators.
    Let’s see some code!

    Install Elixir:

    Installing Elixir is super easy in all major platforms and is an one-liner in most of them.

    Arch Linux

    Elixir is available on Arch Linux through the official repositories:

    pacman -S elixir
    

    Ubuntu

    Installing Elixir in Ubuntu is a bit tidious. But it is easy enough nonetheless.

    wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
    apt-get update
    apt-get install esl-erlang
    apt-get install elixir
    

    OS X

    Install Elixir in OS X using Homebrew.

    brew install elixir
    

    Meet IEx

    After the installation is completed, it’s time to open your shell. You will spend a lot of time in your shell if you want to develop in Elixir.
    Elixir’s interactive shell or IEx is a REPL – (Read Evaluate Print Loop) where you can explore Elixir. You can input expressions there and they will be evaluated giving you immediate feedback. Keep in mind that your code is truly evaluated and not compiled, so make sure not to run profiling nor benchmarks in the shell.

    The Break Command

    There’s an important thing you need to know before you start the IEx RELP – how to exit it.
    You’re probably used to hitting CTRL+C to close the programs running in the terminal. If you hit  CTRL+C in the IEx RELP, you will open up the Break Menu. Once in the break menu, you can hit CTRL+C again to quit the shell as well as pressing a.

    I’m not going to dive into the break menu functions. But, let’s see a few IEx helpers!

    Helpers

    IEx provides a bunch of helpers, in order to list all of them type: h().
    And this is what you should see:

    Those are some of my favorites, I think they will be yours as well.

    • h as we just saw, this function will print the helper message.
    • h/1 which is the same function, but now it expects one argument.

    For instance, whenever you want to see the documentation of the String strip/2 method you can easily do:

    Probably the second most useful IEx helper you’re going to use while programming in Elixir is the c/2, which compiles a given elixir file (or a list) and expects as a second parameter a path to write the compiled files to.
    Let’s say you are working in one of the https://exercism.io/ Elixir exersices, the Anagram exercise.
    So you have implemented the Anagram module, which has the method match/2 in the anagram.exs file. As the good developer you are, you have written a few specs to make sure everything works as expected as well.
    This is how your current directory looks:

    Now, in order to run your tests against the Anagram module you need to run/compile the tests.

    As you just saw, in order to compile a file, simply invoke the elixir executable passing as argument path to the file you want to compile.
    Now let’s say you want to run the IEx REPL with the Anagram module accessible in the session context. There are two commonly used options. The first is you can require the file by using the options -r, something like iex -r anagram.exs. The second one, you can compile right from the IEx session.

    Simple, just like that!
    Ok, what about if you want to recompile a module? Should you exit the IEx, run it again and compile the file again? Nope! If you have a good memory, you will remember that when we listed all the helpers available in the IEx RELP, we saw something about a recompile command. Let’s see how it works.

    Notice that this time, you passed as an argument the module itself and not the file path.
    As we saw, IEx has a bunch of other useful helpers that will help you learn and understand better how an Elixir program works.

    Basics of Elixir Types

    Numbers

    There are two types of numbers. Arbitrary sized integers and floating points numbers.

    Integers

    Integers can be written in the decimal base, hexadecimal, octal and binary.
    As in Ruby, you can use underscore to separate groups of three digits when writing large numbers. For instance you could right a hundred million like this:

    100_000_000
    

    Octal:

    0o444
    

    Hexdecimal:

    0xabc
    

    Binary:

    0b1011
    

    Floats

    Floare are IEEE 754 double precision. They have 16 digits of accuracy and a maximum exponent of around 10308.
    Floats are written using a decimal point. There must be at least one digit before and after the point. You can also append a trailing exponent. For instance 1.0, 0.3141589e1, and 314159.0-e.

    Atoms

    Atoms are constants that represent names. They are immutable values. You write an atom with a leading colon : and a sequence of letters, digits, underscores, and at signs @. You can also write them with a leading colon : and an arbitrary sequence of characters enclosed by quotes.
    Atoms are a very powerful tool, they are used to reference erlang functions as well as keys and Elixir methods.
    Here are a few valid atoms.

    :name, :first_name, :"last name",  :===, :is_it_@_question?
    

    Booleans

    Of course, booleans are true and false values. But the nice thing about them is at the end of the day, they’re just atoms.

    Strings

    By default, strings in Elixir are UTF-8 compliant. To use them you can have an arbitrary number of characters enclosed by " or '. You can also have interpolated expressions inside the string as well as escaped characters.

    Be aware that single quoted strings are actually a list of binaries.

    Anonymous Functions

    As a functional language, Elixir has anonymous functions as a basic type. A simple way to write a function is fn (argument_list) -> body end. But a function can have multiple bodies with multiple argument lists, guard clauses, and so on.
    Dave Thomas, in the Programming Elixir book, suggests we think of fn…end as being the quotes that surround a string literal, where instead of returning a string value we are returning a function.

    Tuples

    Tuple is an immutable indexed array. They are fast to return its size and slow to append new values due its immutable nature. When updating a tuple, you are actually creating a whole new copy of the tuple self.
    Tuples are very often used as the return value of an array. While coding in Elixir you will very often see this, {:ok, something_else_here}.
    Here’s how we write a tuple: {?a,?b,?c}.

    Pattern Matching

    I won’t be able to explain everything you need to know about Pattern Matching, however what you are about to read covers a lot of what you need to know to get started.
    Elixir uses = as a match operator. To understand this, we kind of need to unlearn what we know about = in other traditional languages. In traditional languages the equals operator is for assignment. In Elixir, the equals operators is for pattern matching.
    So, that’s the way it works values in the left hand side. If they are variables they are bound to the right hand side, if they are not variables elixir tries to match them with the right hand side.

    Pin Operator

    Elixir provides a way to always force pattern matching against the variable in the left hand side, the pin operator.

    Lists

    In Elixir, Lists look like arrays as we know it from other languages but they are not. Lists are linked structures which consist of a head and a tail.

    Keyword Lists

    Keyword Lists are a list of Tuple pairs.
    You simply write them as lists. For instance: [{:one, 1}, 2, {:three, 3}]. There’s a shortcut for defining lists, here’s how it looks: [one: 1, three: 3].
    In order to retrieve an item from a keyword list you can either use:

    Keyword.get([{:one, 1}, 2, {:three, 3}], :one)
    

    Or use the shortcut:

    [{:one, 1}, 2, {:three, 3}][:one]
    

    Because keyword lists are slow when retrieving a value, in it is an expensive operation, so if you are storing data that needs fast access you should use a Map.

    Maps

    Maps are an efficient collection of key/value pairs. The key can have any value you want as a key, but usually should be the same type. Different from keyword lists, Maps allow only one entry for a given key. They are efficient as they grow and they can be used in the Elixir pattern matching in general use maps when you need an associative array.
    Here’s how you can write a Map:

    %{ :one => 1, :two => 2, 3 => 3, "four" => 4, [] => %{}, {} => [k: :v]}
    

    Conclusion

    Elixir is awesome, easy to understand, has simple but powerful types and very useful tooling around it which will help you when beginning to learn. In this first part, we have covered the various data types Elixir programs are built on and the operators that power them. In later parts we will dive deeper into the world of Elixir – functional and concurrent programming.
    This post originally appeared in Toptal

  • An Introduction to Robot Operating System: The Ultimate Robot Application Framework

    The Robot Operating System (ROS) is not an actual operating system, but a framework and set of tools that provide functionality of an operating system on a heterogeneous computer cluster. Its usefulness is not limited to robots, but the majority of tools provided are focused on working with peripheral hardware.
    ROS is split up in more than 2000 packages, each package providing specialized functionality. The number of tools connected to the framework are probably its biggest power.

    Why Should I Use Robot OS?

    ROS provides functionality for hardware abstraction, device drivers, communication between processes over multiple machines, tools for testing and visualization, and much more.
    An Introduction to Robot Operating System: The Ultimate Robot Applications Framework
    The key feature of ROS is the way the software is run and the way it communicates, allowing you to design complex software without knowing how certain hardware works. ROS provides a way to connect a network of processes (nodes) with a central hub. Nodes can be run on multiple devices, and they connect to that hub in various ways.
    The main ways of creating the network are providing requestable services, or defining publisher/subscriber connections with other nodes. Both methods communicate via specified message types. Some types are provided by the core packages, but message types can be defined by individual packages.
    Developers can assemble a complex system by connecting existing solutions for small problems. The way the system is implemented, it allows us to:

    • Replace components with similar interfaces on the fly, removing the need of stopping the system for various changes
    • Multiplexing outputs of multiple components into one input for another component, allowing parallel solving of various problems
    • Connect components made in various programming languages by just implementing the proper connectors to the messaging system, making it easy to develop software by connecting existing modules from various developers
    • Create nodes over a network of devices, without worrying about where code is run and implementing Interprocess communication (IPC) and Remote Procedure Call (RPC) systems
    • Directly connect to feeds on demand from remote hardware without writing any extra code, by employing the previous two bullet points

    We plan on demonstrating how useful that is by iteratively developing a simple solution. There are several key advantages compared to other approaches. ROS has multi platform support and allows connections between processes over multiple devices via peer-to-peer connections that are handled behind the scene. The design allows support for any language by wrapping the C++ communication classes, or manually developing classes for the language interface.
    ROS is made by its own community, meant for its community. After several years, that resulted in a great amount of reusable packages that are simple to integrate, thanks to the architecture of the system.
    Alternative approaches like https://www.mrpt.org/, https://carmen.sourceforge.net/intro.html, https://lcm-proj.github.io/, https://playerstage.sourceforge.net/, https://msdn.microsoft.com/en-us/library/bb648760.aspxand others provide some of those features, but not all. Most of the time, the design downfalls are language support limitations, unoptimized communication between processes, or the lack of support for various devices which is arguably the hardest problem to fix.

    What Are We Going to Build?

    Since our focus is the framework and not the actual algorithms for particular problems, the given problem will be fairly simple. Our goal is to build software for an onboard computer that allows us to remotely control and monitor a robot, connected to us via Wi-Fi, by using a gamepad on our computer and a feed from the camera mounted on the robot.
    First of all, we’ll make a simple program connect to a simple simulation, just to demonstrate basic principles of ROS. We will attach a gamepad to a computer and try to design a good control scheme for turning gamepad input into control signals for a robot.
    The main languages for writing ROS code are C++ and Python, C++ being preferred due to better performance. We will explain our examples in Python due to less boilerplate in code and no need for explicit building.

    Installation and Configuration

    ROS versions are referred to by name. As of this date, the latest release is Jade Turtle, and the latest LTS version Indigo Igloo. Going for the LTS version is preferable, and backwards compatibility isn’t guaranteed in ROS, so all the examples will be written for Indigo.
    ROS is available on various *NIX platforms. The officially supported version is on Ubuntu. The OS X, Arch Linux, Debian, Raspbian and Android versions are supported by the community.
    We will go through the installation process for Ubuntu 14.04 on desktop. The processes for all supported versions and platforms are available on the official website. Virtual machines with ROS installed are also available.
    Installation is platform dependent (and most platforms have packages provided), but workspace configuration is the same for all platforms.

    Installation on Ubuntu

    ROS provides its own repositories. The first step is adding them.

    sudo sh -c 'echo "deb https://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'
    sudo apt-key adv --keyserver hkp://pool.sks-keyservers.net --recv-key 0xB01FA116
    sudo apt-get update
    

    After that you’ll have all hosted packages for all ROS versions available for your Ubuntu version. For example, Ubuntu 14.04 supports indigo and jade.
    Installing the base packages on desktop has one of three options:

    • sudo apt-get install ros-indigo-ros-base for a minimal installation
    • sudo apt-get install ros-indigo-desktop for having the basic additional GUI tools
    • sudo apt-get install ros-indigo-desktop-full for having all official features, including various simulators and libraries for navigation and perception

    For the best working experience, the full option is recommended. For installation on devices that will only be used to run nodes, the base version is sufficient. No matter what option you choose, you can install any needed package named package_name by running:

    sudo apt-get install ros-indigo-<package-name>
    

    Underscores are replaced by hyphens in the final name, so stage_ros will be in the package ros-indigo-stage-ros.
    The next step is to initialize rosdep. Packages in ROS can declare what components they depend on. rosdep allows you to compile those packages without too much manual dependency handling. To initialize it, call:

    sudo rosdep init
    rosdep update
    

    ROS has several environment variables used by its tools. With the default installation, the bash script to initialize them is located in /opt/ros/indigo/setup.bash. Variables need to be initialized within every bash session, so the best solution is to add them to ~/.bashrc.

    echo "source /opt/ros/indigo/setup.bash" >> ~/.bashrc
    source ~/.bashrc
    

    Some packages install external dependencies via rosinstall, which is available as a package and installed via sudo apt-get install python-rosinstall.
    This is the end of the installation on Ubuntu. What follows is a short introduction to installing workspaces.

    Configuration

    Ever since Groovy Galapagos, ROS workspaces are managed via catkin. We need to define a directory for all packages that we host. Within the directory we create a src folder, and call catkin_init_workspace form inside it. That will create various symbolic links to the currently sourced ROS version. The next step is to add this workspace to environment variables as well.
    To perform this whole workspace configuration, choose an empty directory and execute the following commands:

    mkdir src
    cd src
    catkin_init_workspace
    cd ..
    catkin_make
    echo "source $(pwd)/devel/setup.bash" >> ~/.bashrc
    source ~/.bashrc
    

    You have now created a workspace within which you can create your own ROS packages.

    Getting Familiar with the Tools

    Creating any code is a big jump. Let’s first get familiar with some of the systems running behind the scene. Our first step will be running the basic GUI and seeing what messages it generates.
    To run anything in ROS, a core process needs to be launched. It’s as easy as opening a new terminal window and typing:

    roscore
    

    In your whole connected network of devices, roscore needs to be launched only once, on the device that will host the central hub for communication dispatching.
    The main role of roscore is to tell nodes which other nodes they should connect to, and in which way (whether via a network port or shared memory). The goal is to allow nodes to only care about what data they want to know, rather than what node they want to connect to, while minimizing the time and bandwidth needed to perform all communication.

    rqt

    After running roscore, we can launch the main GUI tool for ROS: rqt. What we see is very underwhelming – an empty window. rqt hosts a wide variety of plugins that can be configured into any visual configuration and any number of predefined views.

    For a start, let’s run the Robot Steering plugin, by choosing it in Plugins > Robot Tools > Robot Steering. What we get is two sliders, representing the linear and rotational motion we want our robot to have. At the top of the plugin we see a text box with /cmd_vel in it. We can rename it to anything we want. It represents the name of the topic to which the steering is publishing. The terminal tools are the best place to see what’s going on in the background.

    Terminal Tools

    ROS has several powerful tools for inspecting what is happening in the system. The first tool we’ll introduce is rostopic. It allows us to inspect topics that nodes can subscribe and publish to. Running rostopic list will yield:

    /cmd_vel
    /rosout
    /rosout_agg
    

    The latter 2 topics are always running and are related to central ROS systems. The /cmd_vel topic is being published by our steering. Renaming the topic in the steering will rename it here as well. Now, we are interested in what’s going on within the topic. Running rostopic echo /cmd_vel will show us nothing (unless you tinkered with the sliders). The process runs until we cancel it. Let us now move the vertical slider to 20 m/s. Looking at the echo, we can see the following repeated over and over again:

    linear:
      x: 0.2
      y: 0.0
      z: 0.0
    angular:
      x: 0.0
      y: 0.0
      z: 0.0
    

    How often does it spam this message? rostopic hz /cmd_vel says at an average rate of 10 Hz. Well, how many topics like this can I run through my slow Wi-Fi connection? rostopic bw /cmd_vel detects an average of 480 B/s.
    Now that’s all well and good, but we talked about message types. This data is good for a human, but an application will need the raw data, and will need to know the message type so it can interpret the data. The type can be determined with rostopic type /cmd_vel, telling us it’s a geometry_msgs/Twist. All of ROS terminal tools called without any arguments return a standard help message.
    The ROS Wiki is good enough to make a web search for this string result in a Wiki explanation to what it contains and how it’s structured. But we don’t have to rely on it. rosmsg is the general tool for message types. Running rosmsg show geometry_msgs/Twist will return:

    geometry_msgs/Vector3 linear
      float64 x
      float64 y
      float64 z
    geometry_msgs/Vector3 angular
      float64 x
      float64 y
      float64 z
    

    The message consists of two 3D vectors, representing linear and angular velocity in 3D space.
    If we want what topics a node is connected to, rosnode info <node-name> will give us detailed data about the node. The tools rostopic, rosmsg and rosnode are the main tools for inspecting raw ROS functionality. ROS has a lot more GUI and terminal tools, but those are out of our scope for this introduction.
    The main tools for running ROS nodes are rusrun and roslaunch. rosrun can run nodes via rosrun <package_name> <node_name>, and roslaunch runs nodes based on launch files, which we’ll get familiar with to a tiny extent since they are the most complex element of the ROS automation.
    We can shut down everything we ran to start working on our first code. For future reference, it will go without saying that running anything ROS related requires an active instance of roscore. A lot of issues you run into can be resolved by closing the terminal window that roscore is run within, and opening a new one to relaunch it. This updates all dependencies that needed to be reloaded, both in bash and in roscore.

    Creating Gamepad Teleoperation

    Our first goal is to imitate the functionality of Robot Steering by creating a node that publishes geometry_msgs/Twist data to /cmd_vel based on gamepad input. Our first stop is the joy package.

    The joy Package

    The joy package provides generic ROS drivers for joysticks and gamepads. It is not included in the default installation, so it needs to be installed via:

    sudo apt-get install ros-indigo-joy
    

    After the installation, we can run rosrun joy joy_node. This will connect us to the default joystick or gamepad. Running rostopic list shows us that we have a topic called /joy. Listening to it via rostopic echo shows us messages of the following format (note that you have to interact with the gamepad or joystick for messages to be published).

    header:
      seq: 4156
      stamp:
        secs: 1450707466
        nsecs: 204517084
      frame_id: ''
    axes: [0.0, 0.0, 0.0, -0.0, 0.0, 0.0, 0.0, 0.0]
    buttons: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    

    You can ignore headers for now. Other than that, we have axes and buttons, explaining nicely what they represent. Moving axes and pushing buttons on the controller will result in these numbers changing. Using our tools, we can determine that the message type is sensor_msgs/Joy and the format is:

    std_msgs/Header header
      uint32 seq
      time stamp
      string frame_id
    float32[] axes
    int32[] buttons
    

    Creating Our Teleoperation

    The first step to writing code is making a package. Within the src folder of the workspace, run:

    catkin_create_pkg toptal_tutorial rospy joy geometry_msgs sensor_msgs
    

    Here we state the name of the package we’re creating, followed by packages we plan to depend upon. No worries, dependencies can be updated manually later on.
    We now have a toptal_tutorial folder. Within the folder, create a scripts folder that will house all our Python scripts.
    Let’s create a file called teleop.py, and within it we’ll set:

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    def joy_callback(data):
        print data
    def main():
        rospy.init_node('teleop')
        rospy.Subscriber('joy', Joy, joy_callback)
        while not rospy.is_shutdown():
            pass
    if __name__ == '__main__':
        main()
    

    We’ll also need to set chmod +x teleop.py so the script becomes runnable. Running rosrun joy joy_node in one terminal and rosrun toptal_tutorial teleop.py in another will result in teleop.py’s terminal output being filled with Joy messages.
    Let’s examine what the code does.
    First, we import rospy, which hosts the library for interacting with the ROS framework. Each package that defines messages has a msg subpackage with message definitions in it. We are importing Joy to handle the input. There is no need to import embedded message types (like Header from std_msgs.msg that is in the Joy message) unless we want to explicitly mention them.
    Our first step is initializing a node with a specific name (in this case, we call it “teleop”). After that we create a subscriber that subscribes to the “joy” topic of type sensor_msgs.msg.Joy, and that handles each message by calling the joy_callback function. Callbacks receive one parameter, the data from the message. Accessing members of the data is simple. If we wanted to print the state of the first axis, if we recall the message type, we would call print data.axes[0], and it will be a float. The loop at the end loops until ROS is shut down.
    Our next step would be to handle our data somehow. We should create a Twist message that changes depending on the input, and then we would publish it to the cmd_vel topic.

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    from geometry_msgs.msg import Twist  # new
    from functools import partial  # new
    def joy_callback(pub, data):  # modified
        cmd_vel = Twist()  # new
        cmd_vel.linear.x = data.axes[1]  # new
        cmd_vel.angular.z = data.axes[0]  # new
        pub.publish(cmd_vel)  # new
    def main():
        rospy.init_node('teleop')
        pub = rospy.Publisher('cmd_vel', Twist, queue_size=1000)  # new
        rospy.Subscriber('joy', Joy, partial(joy_callback, pub))  # modified
        while not rospy.is_shutdown():
            pass
    if __name__ == '__main__':
        main()
    

    First, we add the Twist message, and we add support for binding function arguments via functools.partial. We create a publisher, pub, that publishes to cmd_vel a message of type Twist. We bind that publisher to the callback, and make it publish a Twist message on every input with the speeds being represented by the first two axes. This code does what we expect it to, and we can see the resulting output via rostopic echo /cmd_vel.
    We still have one issue. The /joy topic can publish at great rates. If we monitor the rostopic hz /cmd_veland move the analog stick in circles, we can see great numbers of messages. Not only does that result in a great amount of communication, but the processes that receive these messages have to process each one of them. There is no need to publish that data so frequently, and we are better off just publishing at a stable rate of 10 Hz. We can accomplish that with the following code.

    #!/usr/bin/env python
    import rospy
    from sensor_msgs.msg import Joy
    from geometry_msgs.msg import Twist
    from functools import partial
    def joy_callback(cmd_vel, data):  # modified
        cmd_vel.linear.x = data.axes[1]
        cmd_vel.angular.z = data.axes[0]
        # moved pub.publish(cmd_vel) to main loop
    def main():
        rospy.init_node('teleop')
        cmd_vel = Twist()  # new
        pub = rospy.Publisher('cmd_vel', Twist, queue_size=1000)
        rospy.Subscriber('joy', Joy, partial(joy_callback, cmd_vel))  # modified
        rate = rospy.Rate(10)  # new
        while not rospy.is_shutdown():
            pub.publish(cmd_vel)  # new
            rate.sleep()  # new
    if __name__ == '__main__':
        main()
    

    We modified the callback to receive the mutable Twist object and modify it within the loop. The sleepfunction from rospy.Rate maintains a stable output frequency.
    The final code will result in the /cmd_vel topic getting velocity commands at 10 Hz, imitating the output of the Robot Steering rqt plugin.

    Running a Simulated System

    Simulating the World

    Our first goal is to create an environment in which we can simulate a scenario we want to achieve. The node stageros within the stage_ros package allows us to run one robot within a 2D stage defined via an image. There is a whole syntax, described within the stage_ros package for world files and how to generate them. It’s fairly simple, but outside of our scope. Luckily, the package comes with several demo world. First, let’s go to the files’ directory by running:

    roscd stage_ros
    cd world
    

    Within the folder there are several files. Let’s run one.

    rosrun stage_ros stageros willow-erratic.world
    

    This created several topics. The meaning of each of them is also documented with the package. The important part is that it has cmd_vel.

    Within the displayed stage, there is a blue square, representing the robot you control. By using either our code or Robot Steering, we can control this robot. Try it out.

    Setting up our system via launch files

    let’s create a launch folder within our package, and within it create a file called teleop.launch. The final folder structure should look like this:

    toptal_tutorial/
    ├── CMakeLists.txt
    ├── launch
    │   └── teleop.launch
    ├── package.xml
    ├── scripts
    │   └── teleop.py
    └── src
    

    Within the teleop.launch file we will define a set of nodes and their interconnections.

    <launch>
      <arg name="world_file" default="$(find stage_ros)/world/willow-four-erratics-multisensor.world" />
      <node pkg="stage_ros" type="stageros" name="simulated_world" args="$(arg world_file)"></node>
      <group ns="robot_0">
        <node pkg="joy" type="joy_node" name="joy_input"></node>
        <node pkg="toptal_tutorial" type="teleop.py" name="joy_convert"></node>
      </group>
    </launch>
    

    The new world consists of four robots, and each of their topics has a prefix of robot_<n>. So, the robot number 0 has a velocity command topic called robot_0/cmd_vel. That is why we put our control within a namespace called robot_0, to adjust their names to the new form. In that sense, you can think of topic names as folders in a filesystem.

    To run launchfiles, no roscore is needed. In a sense, roscore is just a special case of a launchfile that does nothing. If a roscore is missing, only the first launchfile launched will run a core, while the rest will connect to it. Now, we run the launch with:

    roslaunch toptal_tutorial teleop.launch
    

    If all is correct, this will result in a simulator with 4 robots, one of which is controlled with our gamepad or joystick. This world has a lot more under the hood than the previous one. Each of the four robots has:

    /robot_<n>/base_pose_ground_truth
    /robot_<n>/base_scan_0
    /robot_<n>/base_scan_1
    /robot_<n>/camera_info_0
    /robot_<n>/camera_info_1
    /robot_<n>/cmd_vel
    /robot_<n>/depth_0
    /robot_<n>/depth_1
    /robot_<n>/image_0
    /robot_<n>/image_1
    /robot_<n>/odom
    

    We replace <n> with 0, 1, 2, or 3. This brings us to our last topic.

    Viewing Our Data with rqt

    We didn’t go too deep into rqt, but it is the perfect tool for viewing more complex data. You can experiment with all the topics, but we’ll focus on the image_0, image_1, depth_0, and depth_1 topics.
    Let’s launch rqt and remove any opened plugins. Now we’ll open 4 image visualizers (Plugins > Visualization > Image View), and place them in a 2×2 grid formation. Finally, in the top left corner of each of the views, let’s choose one of the four stated topics for robot_0.

    What we get is stereo vision with depth perception, with low resolution cameras. Bear in mind that we could have even gotten this result without our input system. If we just run this (from within the stage_ros/worldfolder):

    rosrun stage_ros stageros willow-four-erratics-multisensor.world
    

    and add the Robot Steering plugin with a topic called /robot_0/cmd_vel, we would have gotten the same results with the controls being on-screen sliders.

    Applying the Results to a Real System

    A lot of hardware has full support for ROS, very often provided by third party volunteers. Many robot platforms have drivers that generate these types of messages, and ROS has nodes that take a webcam and publish an image feed.
    While the last result was a simulation of what we want to achieve, the same can be achieved with the following modifications:

    • Install ROS on the onboard computer of your robot
    • Create a launchfile for the onboard computer that connects ROS to the underlying platform and all high level sensors like cameras, laser range finders and others. The needed nodes can already exist, or can be implemented by creating a publisher/subscriber to ROS on one side, and a driver for serial communications on the other
    • Have the launchfile run at startup
    • On your remote computer add export ROS_MASTER_URI=https://<robot_hostname>:11311/ to your bash startup, making the remote computer look for roscore on that given hostname and port
    • Launch rqt and/or any scripts for monitoring and controlling the robot

    What this really comes down to is just exporting the proper environment variable on the remote device, and the rest handles itself. Running ROS on a computer cluster only needs that one step being done for every machine.

    Conclusion

    We have demonstrated how, with very little coding, you can have a complex system of variables that you can manipulate at your whim. The simple publisher/subscriber system allows you to quickly develop software pipeline that processes data in a cluster of computers, while not worrying about the underlying implementation of certain elements.
    While we used a simple simulator, more complex simulators like gazebo (also included in the full desktop version) allow you to create 3D worlds with physics and complex sensors, and can give you an experience of the final results and product long before it’s developed.
    This introduction was a very basic one, but the hope is that you became more interested in working with this versatile framework.
    This post originally appeared in Toptal Engineering Blog

  • Guide: Software Release Management For Small Teams

    ormalizing The Release Management Process (If There’s Any)

    In some team configurations, especially ones that are found in startups, there are no DevOps, nor infrastructure engineers, to provide support when releasing a new version of the product.
    Moreover, unlike large bureaucratic companies with defined formal processes, the CTO or Head of Software Development team in a startup is often not aware of the complexities of the software release management process; a few developers in the company may be aware of the complex details of the process, but not everyone. If this knowledge is not documented thoroughly, I believe it could result in confusion.
    In this article, I’ll try to provide some tips about how to formalize the release process, particularly from the developer’s point of view.

    Enter The Software Release Checklist

    You may be familiar with the idea of a checklist for some operations, as per the Checklist Manifesto, a book by Atul Gawande. I believe a formal release process (like many other tasks in the software development world) provides developers with an opportunity to implement this protocol. A release process checklist should be kept in a shared document, preferably in the form of a collaborative wiki, or a spreadsheet on Google Drive.
    By sharing this vital document with the team, and by granting editing permissions, every member has access to the formally defined release process. This allows them to understand how the process works. Moreover, following discussions with other team members, it empowers the team to improve upon it every now and then. This should bring transparency and allow the entire team to have real-time access to what’s going on during the release, what steps have been completed, and by whom.
    By looking at this spreadsheet, the stakeholders can decide on a ‘GO’ vs ‘NO GO,’ based on the outcome of the steps. For example, if a stress test goes wrong in a test environment, based on the event the project manager might decide to call off the production release.
    A simple, well thought out spreadsheet checklist can make a big difference in your software release management process.

    A simple, well-thought-out spreadsheet checklist can make a big difference in your software release management process.

    Suggested Steps To Use As A Foundation

    In this section, I’ll propose some steps you can use to build your own checklist for your release process. Some of these steps are by no means mandatory. Each app is different and each organization works in a different way, so feel free to adapt and make changes that will fit better into your workflow.

    1. Create A Release Branch

    It’s likely that you are familiar with the concept of Git Workflow, or with the idea of release branches, a topic that has been explained in a previous blog post.
    Ideally, you should have at least three branches:

    • master: this should reflect the current state of what is in the production environment. Every new commit on master should comprise a new release only.
    • develop: this branch should contain the completed (and tested) upcoming features. It is common to create a separate branch for each feature and then merge it to develop when the feature is ready.
    • release: release branches are a collection of commits that are ready to be sent to production, plus some additional minor bug fixes related to the release.

    Notice the release branches should be removed once the release is completed, therefore these branches are created and destroyed all the time, unlike master or develop, which are always the same.
    In order to create a new release branch, from the develop branch in your git terminal, type:
    $ git checkout -b release/x.y.z
    It is convenient to use a naming convention, such as the one defined above, replacing x.y.z by the major.minor.patch version number according to your needs (it is a policy that you should define within your team and stick to it).
    It is important to say, as well, that if you code some bug fixes into the release branch, you should not forget to merge them back to develop. The main purpose of the release branch is to have a preview snapshot of how the app should behave after it goes into production.
    Organizing and keeping track of different release branches is a crucial aspect of release management.

    Organizing and keeping track of different release branches is a crucial aspect of release management.

    2. Bump Version

    The next step would be to bump (modify or increase) the version number on the release branch.
    You should open the AndroidManifest.xml / package.json / pom.xml / or wherever the app’s version is stored in your project (YMMV), update the version number, and then commit the changes to the current releasebranch.
    It is important to update the version number for two reasons.
    First, you can track and map the features that were introduced in each version, and second, you will be aware of the version they are using should they need to do some troubleshooting or to contact you for support. If you are building a mobile app, the version number you are updating in this step is usually displayed on the user end, in the About section or in Google Play or Apple App Store.This step is also a good opportunity to update environment-dependent-configuration files (although I’d suggest keeping those in a separate repository), such as making the branch point to the production database, or any other tweaks needed on the build process.
    Finally, it is recommended that you push the release branch to origin, so it is available for your other developers:
    $ git push -u origin release/x.y.z

    3a. Merge release branch to master and tag it

    Only the master branch should be deployed for production, thus in this step, we need to merge the releasebranch into master.

    $ git checkout master
    $ git merge --no-ff release/x.y.z
    $ git push
    

    The --no-ff flag is optional, however, its use is recommended in order to force the creation of a new commit object, even though the merge can be completed using the fast-forward technique.
    Next, it is time to tag the release on master branch:
    $ git tag -a x.y.z -m 'description of new version, features or fixes included'
    Tags are useful because you are persisting this specific point in history in the git repository, and you can come back later to recreate a separate branch off a particular tag.

    3b. Use a pull request to merge the release branch

    Another alternative used often, is to use a pull request to merge the release branch into master.
    There are numerous advantages to this approach. A new space is created for collaboration, which the team can use to discuss various release-related issues. This point is a good time to add an extra gate for incorporating a code review process, while having more eyeballs to monitor the code that will be introduced, and to discuss potential modifications.
    Some tools that allow you to implement pull requests into your workflows are GitHub,  Bitbucket and GitLab(merge request as they call it on the latter). With these tools, you don’t type the git commands manually, instead, you use a web interface to set the source branch (release) and the destination branch (master), and then you add one or more reviewers, all of whom will be able to write inline comments on these new changes, suggest improvements, and so on.
    After all the reviewers approve the pull request, you can automatically merge the changes into master by pressing a button on the UI.

    4. Deploy Master To Production Environment

    It is good practice, at this stage, to have a tester on your team do a smoke test (this could be defined on a separate checklist) before deploying the app. A good suggestion is to deploy the master branch into a separate testing environment as done by professional automation testing companies. The tester can then perform some basic actions to make sure nothing went wrong after the merge on the latest build. How to conduct a smoke test is beyond the scope of this article, but you can find a lot of material on the web about it. The result of the smoke test can be integrated into the release checklist/spreadsheet, documenting anything that went wrong.
    At this point, you are ready to deploy the changes and make them live. Go ahead and deploy master branch. This step will depend on the infrastructure stack you are using. It might involve connecting to your Amazon EC2 instance to upload your app, or pushing to a Heroku remote, or connecting via ssh to your VPS to copy the new version, or any other process.
    Do a smoke test, deploy the master branch into a separate testing environment, make sure the deployment was successful.

    Do a smoke test, deploy the master branch into a separate testing environment, make sure the deployment was successful.

    After the app is uploaded, make sure it was deployed successfully and that it works as expected.

    5. Merge Back Into Develop And Delete Release Branch

    Now the release is almost completed, you’ll want to merge the release branch into develop, to update the version number on the latter and to transfer all the bug fixes made to the main development branch:

    $ git checkout develop
    $ git merge release/x.y.z
    

    Now it is time to remove the release branch:
    $ git branch -d release/x.y.z

    6. Changelog Generation

    There should be a file at the root of your project named CHANGELOG.md (or an equivalent) where you should add a new entry whenever there is a new release in order to document everything that’s included in it, like bug fixes, new features, known issues, and any other relevant information in the form of release notes. This is really useful for users and contributors to see what changes have been made between each release (or version) of the project.
    The changelog entry includes the date, version number and some notes about the release. The entries should be kept in reverse chronological order. Here’s a simple template I’ve been using that you can adapt to your project:

    <app's name or component released> <version x.y.z> | <date>
    <developer's name in charge of release> | <developer's email>
    Features:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Bugs fixed:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Enhancements:
    * <ticket/issue number>: <ticket/issue summary> (<link to issue tracker>)
    * ...
    Optional: known issues plus other release notes.
    

    In addition, this step can be completely automated by either coding a basic script that traverses the git log and automatically generates the changelog entry, or by using a tool that does the same, such as:

    Keep in mind though, that the degree of automation you get is directly proportional to the strictness of your commit message format. I believe it is always good practice to agree on a specific format for commit messages with the team. By following guidelines on the style of the commit messages, they will be easier to parse and hence more likely that you will be able to automate the generation of the changelog.

    7. Communicate With Stakeholders

    This is where you would usually do some of the following:

    • Let the team know via an internal messaging tool (e.g.: Slack) that a new release has been completed. I recommend creating a new channel (i.e.: #releases) for the sole purpose of communicating release related events. It is easy to add hooks in a Slack channel to post a message after an action has been taken.
    • Alternatively, send an email to the stakeholders with a link to the changelog, or the changelog file attached.
    • Write a blogpost (if you have a blog for your app or product) or a tweet.

    More actions can be taken depending on the nature of your organization. The important thing is not forgetting to communicate that a new version of your product is available.

    8. Grooming The Issue Tracker

    After a release is executed, you will probably need to update the status of some of your tickets to keep track of the bug fixes, or features, currently in production. Generally, this involves changing some tags (for small projects I use a release-pending tag, which I remove after the release is completed).
    If you use milestones for each new version you’ll probably need to update their status or mark them as completed. Some issue trackers even let you plan the release and align it with sprints, track whether a bug is blocking a release, and other useful information.
    It all depends on how you use the tool. I simply want to point out that the task of updating the information in the issue tracker should be included in your release checklist.

    About Automating The Release Process

    The reader might have noticed that, apart from the changelog step outlined above, many of the aforementioned steps can be automated, too.
    The ability to automate some parts of the release process is a huge win and saves a lot of time. I suggest creating scripts, or figuring out how to automate individual steps and then work towards a continuous deliverygoal. Continuous delivery can reduce risk, reduce costs, and reduce the time developers need to spend in managing the release. Consequently, you’ll be able to release more often and be more productive in terms of the hours allocated for development.
    The holy grail of DevOps is to be able to launch a new version by pressing a button (or running a command) that would trigger the release process automatically, or even better, a system that would release a new version of your software at a designated time. Of course, this is difficult to achieve because you also need to automate a lot of the testing process, but it is not impossible.
    A fully automated software release? It’s not as farfetched as some believe.

    A fully automated software release? It’s not as farfetched as some believe.

    Embracing Best Practices

    In this section I’ll describe a couple of recommended practices that I’ve found convenient, either to make the release process smoother or for taking safety measures in case something goes wrong.

    Find the most suitable day to carry out the release

    I usually release apps I am working on on Thursdays, between noon and close of business.
    If you work Monday to Friday, it is not a good idea to launch on a Friday. If something breaks down after the release, you won’t have time to fix it until Monday (unless you want to work during the weekend). That’s why it is more convenient to do releases on Thursday, because you have Friday to monitor the new version after being deployed, fix any problems, or do a rollback.
    Another important thing to mention if you are managing a web app, is to know the time zone the majority of your users are located. You should time the release during a low traffic period to minimize the potential damage if something fails. Sometimes, this can be tricky when your user-base is spread across the whole world, but anyway, you should do some research and decide on the best time.

    Backup Your Database Before A New Release

    If you don’t have periodical backups of your DB scheduled, I strongly suggest you add a step into your release process to perform a backup before starting the release.

    Staged Rollouts

    Ever wonder why, when a publisher announces they’ve launched a new feature, it takes days, or even weeks, for that feature to be available on your phone? That’s because many companies use staged rollouts.
    Facebook has been doing this for a long time. It tests a new feature on five or 10 percent of its users, gradually increasing it until they reach 100 percent of the user-base. During the staged rollout phase, you’ll need to look closely at user feedback and crash reports. With this information, you can then postpone the release, or fix errors, before they affect every user.
    There’s a nice tool on the Android’s Developer Console that implements staged rollouts for your Android apps.
    In a staged rollout, propagation is incremental. As time goes by, the number of users with the latest version goes up.

    In a staged rollout, propagation is incremental. As time goes by, the number of users with the latest version goes up.

    Continuous Integration

    Continuous Integration is a practice worth embracing for many reasons. Firstly, it allows you to detect mistakes early, increasing the rate of successful releases. Secondly, it is the first logical step before implementing Continuous Delivery and full automation as previously described.
    Martin Fowler is a big advocate of Continuous Integration. He describes a huge amount of benefits that can be added to your release process when using this practice. This is a large topic and there are many books and blog posts about it, and I am mentioning it here because I believe it will give you much more confidence in your operations. Amongst the many advantages of using CI, you will find: reduced risk, increased visibility to be aware what is working and what not, earlier detection of bugs, increased frequency of deployments, and many more.
    The starting point to implementing CI is to set up a “continuous integration server;” some nice tools to try are: CruiseControl, Bamboo, Jenkins and Travis.

    Exitlude: It Will All Work Out

    Aggressively, we all defend the role we play Regrettably, times come to send you on your way We’ve seen it all, bonfires of trust, flash floods of pain It doesn’t really matter, don’t you worry, it’ll all work out
    Exitlude, The Killers
    To wrap up, I would say that it’s very important to have a well-defined release process for your app, regardless of its complexity, userbase, or how small your organization is.
    If you don’t, I suggest you start thinking about some basic steps, using this guide and others like it, and brainstorming with your team to come up with a first draft. Try it out on your next release, then iterate. Eventually, you’ll end up building your own release process.
    After that, start thinking about how to automate parts of the process. Think about areas that can be improved. Explore ways of reducing the release time by incorporating small optimizations. Automation should be your ultimate goal; however, don’t plan that from the start, or you will fail by attempting such a big leap. As with with every process, it is better to improve it gradually.
    Do you have any other tricks or guidelines you use for launching new versions of your app? If so, let me know. I don’t come from the DevOps world, I am just a developer who happens to be quite organized and structured, but compared to many veterans, I am still a novice in this respect, so feel free to comment or contact me if you have something to add.
    This post originally appeared in the Toptal Engineering blog

  • Agile, Scrum, and Kanban: What the Heck Do These Words Really Mean?

    When a software developer hears news about a “new JavaScript framework” or a “new IDE,” he doesn’t need to ask more questions to clarify what it’s about. But if he hears about a “new agile framework,” he will likely do the Homer-Simpsonian nodding, pretending that he knows what it’s about, but he will have one, and only one, question: What the heck does “agile framework” mean?
    In the modern software development environment, we increasingly hear words like “agile,” “scrum,” and “kanban,” and they are often used improperly. In this article, I’ll try to explain and to clarify some of these terms.
    Agile methods are designed to help development teams kick butt.

    Agile

    If you want to be the smartass of the crowd, you should use the word “agile” in every other sentence when you are talking about the work process. It has a pretty wide range, does not obligate you to know much about the subject you are talking about, and it is a really nice adjective or adverb: “thinking agile,” “agile approach,” “according to agile principles.” But what does “agile” really mean?
    “Agile” refers to “agile software development,” the approach to development that follows agile principles. But what the heck are “agile principles?” Take a look at the Agile Manifesto and at the 12 principles of agile, which lay the foundations of agile development. From the Manifesto:

    Individuals and interactions over processes and tools
    Working software over comprehensive documentation
    Customer collaboration over contract negotiation
    Responding to change over following a plan

    Agile principles encourage continuous delivery of functioning software, close communication among teams, and high adaptability to changing needs. If you follow these values and principles in your work, you can say that you are working in an agile environment. So, agile software development is not a methodology, it is just a set of different methodologies, frameworks, and techniques that follow the same principles. It can be said that “agile” is a framework for thinking and making decisions.

    Agile is a framework for thinking and making decisions.

    But why is it so important to follow these principles in our work?
    The Manifesto and principles are the result of searching for the best solutions that have evolved over the decades in response to the challenges of software development. Throughout the 70s, 80s, and 90s, different developers and teams all over the world had been experimenting with methods of working and approaches to problem solving, inventing different frameworks and techniques (such as scrum and Extreme Programming), and even coming to the same ideas in parallel. Finally, in February 2001, seventeen developers got together and found the common denominators for all these diverse ideas and experiences. That is how the manifesto was created.

    The Agile Manifesto is the result of different experiences and practical solutions that emerged over the decades.

    Scrum

    If you talk about “agile” methods without knowing what they mean, you may slip up and say things that will uncover you in front of the interlocutor who knows the subject: “Scrum and other agile methodologies.”
    Scrum is not a methodology, though we’ve all heard it called such more often than the number of killings in Game of Thrones. Scrum won’t give an answer to every question, and it won’t provide you with the precise procedure for responding to every situation you face. And probably as a result of this incorrect interpretation, most scrum implementations are also wrong: Teams don’t get value. This results in probably the most foolish statement about scrum: “Scrum doesn’t work.”
    What is scrum? The Scrum Guide defines scrum as:

    “A framework within which people can address complex adaptive problems, while productively and creatively delivering products of the highest possible value.”

    So it’s a framework, and like any other framework it can be, and regularly is, used the wrong way. Using scrum effectively requires not merely adopting the structure set out by scrum, but having a deep understanding and appreciation for agile principles across the entire team.
    Scrum consists of three roles: Product Owner, Scrum Master, and Development Team; four ceremonies: Planning Meeting, Daily Scrum, Sprint Review, and Sprint Retrospective; and three artifacts: Product Backlog, Sprint Backlog, and Product Increment. It is organized into regular time frames, which we call sprints. Sprints should last between one and four weeks.
    The Product Owner, or PO, is responsible for guiding the project’s direction. As new tasks and features are determined, the PO adds them to the Product Backlog. A sprint starts with a Planning Meeting where the Development Team selects the tasks from the Product Backlog to work on and plans how they will be implemented. That is followed by development, during which the Dev Team uses the Sprint Backlog to track progress and meets for the Daily Scrum in order to synchronize activities and adjust the plan, if needed. The result of development should be a Product Increment, something that can be applied to the product and released immediately. At the end of the sprint, the Product Increment is presented to the Product Owner at the Sprint Review, where the product backlog is augmented if further changes are needed. Afterwards, the whole team attends the Sprint Retrospective (also known as the Pub Meeting) where they talk about the work process and how it can be improved.
    The basic Scrum framework.
    That’s it in a few sentences, but if you need a detailed explanation of how scrum works, check out this articlewritten by your truly.
    It is easy to learn and understand scrum, but it’s hard to adopt. There are many reasons this framework may or may not be a good fit for a project. It often requires a lot of changes, not only in everyday development, but also culturally. Scrum fits best with development of complex products, ones that last a long time and that include different kinds of specialists.
    Why is scrum so popular, and why does it have an advantage over the traditional waterfall model? Simply put, because it delivers more value to a product and customers. With “heavyweight” methods such as waterfall, horror stories abound in which nobody sees anything of the project for months. With scrum, that is not possible.
    Scrum is all about the value that is delivered to end users. If you really utilize scrum, you need to deliver something of value every sprint. The value can be measured, and the team is also forced to inspect impediments and adapt, with the goal of delivering more value in the next iteration.
    In most software development we are not building a skyscraper; we don’t need to have the whole plan ready before we start, and stick to that plan until the end. We are developing software, and we have the ability to adapt to different situations and to change the product requirements during development. For a long time, many developers saw this as the eighth deadly sin, but from the product perspective it is a huge benefit for optimizing predictability and controlling risk. Scrum is developed around this ability, and its implementation gives a reliable and efficient way of dealing with necessary changes.
    Many techniques are used in conjunction with scrum: planning poker, pair programming, test-driven development (TDD), behavior-driven development (BDD), and others. They are not really a part of scrum, but rather compatible techniques. One method often mentioned at the same time as scrum is kanban, and there is a lot of confusion about what these two things mean in relationship to each other.

    Kanban

    When you talk about scrum and kanban, one frequently asked question from the crowd will be, “Which is better, scrum or kanban?” And you won’t know what to answer because it’s like comparing apples and oranges, or asking, “Which is better, pancakes or beer?” Both are better.
    Kanban is a simple method that aims for just-in-time delivery while not overloading the team members. It is similar to scrum in that the goal is to deliver maximum value at the end, but it is much more flexible than scrum.
    Kanban was not invented by the software development community. In fact, it has its origins in manufacturing processes at Toyota, and it has wide usage in other spheres. There are no strict procedures that you should follow, and no strict way you should implement and use kanban; it is, rather, a set of principles and practices, and you can choose from these practices to suit your needs. But there is one most-often used implementation of kanban in software development that includes the usage of a kanban board, consisting of columns representing stages of work, and tasks.
    Columns represent the state of a task in the development process. The simplest example consists of three columns: “To Do,” “In Progress,” and “Done.” So, tasks are added to “To Do,” moved to “In Progress” when development starts, and considered “Done” when moved to the last column. But of course, it could be more complex:

    “Backlog” → “Defining Specification” → “Ready for Development” → “Development” → “Code Review” → “Testing” → “Deployed” (→ “No one really uses it” → “Completely Removed”).

    Every column can have subcolumns; for example, “Development” can be divided into “Planning” and “Coding”; “Testing” can be divided into “Unit Testing” and “Integration Testing,” and so on. Columns might be dedicated to specialists, if appropriate. The team defines the columns and stages according to its needs. Per the “pull” philosophy, tasks should only enter the workflow when the demand for them is immediate.
    Kanban boards help visualize the workflow.
    The purpose of this board is to visualize the workflow, which is the first key practice in kanban. In fact, kanban can be done without a board at all! It could be a simple list of tasks in a Google sheet with different background colors indicating the state of the task, or it can be Gantt charts, diagrams, tables… It could even be a set of buckets in your office, where each one represents the state of the task, and where balls are used as tasks. Just visualise the workflow and provide transparency to the whole process.
    Another important principle is to reduce the batch size of your efforts. Simplified, this means avoid multitasking. That can mean reducing the volume of tasks you work on at the same time. If you have three designers in a team, the team might set the maximum number of tasks in the “Designing” column to three.
    Like scrum, kanban also sees the team as the most important figure in the process. But it doesn’t suggest roles as scrum does, and you may keep the existing roles to avoid making changes to your existing process. The same stands for continuous improvement: Kanban generally encourages you to learn and improve continuously, but does not prescribe a specific event just for that process, as does scrum’s Sprint Retrospective.

    Which Should I Use?

    Scrum and kanban are not mutually exclusive and not really comparable. In scrum, there are defined roles, while kanban says, “What the hell, keep your current roles and responsibilities.” Scrum will force you to change your way of working; kanban lets you start with your existing process. In scrum, a clear schedule for events is prescribed by the framework; in kanban you don’t have events. Yet, they have a lot of similarities: Both are value-centric, team members are respected as “bosses” of the system, and essentially, they have the same mission: To continuously eliminate waste and remove obstacles.
    But the question, “What should I use in my particular project and with my particular team?” makes much more sense. Kanban doesn’t require so much of the process and cultural changes, and, in most cases, it will be easier to adopt than scrum. Scrum, on the other hand, offers significantly more structure to guide the process, which can eliminate a great deal of overhead as long as everyone is on the same page.
    But the beauty of both is that neither is a strict set of rules. There is nothing stopping you from picking and choosing the best scrum elements for you, such as a daily meeting or review. And there is no reason you cannot incorporate a kanban board into scrum.
    Scrum has proven to be a highly effective framework when the whole team understands it well. However, in my experience, I find it hard to work in scrum with some clients. The process and cultural changes required for proper scrum implementation can be too much (especially when dealing with someone who believes that he is making a new Google!). On the other hand, kanban is more flexible and doesn’t force people to change. Some authors also say that kanban is a good path to agility, and offers easier implementation of scrum. Others say that using scrum should lead to kanban at the end.
    The truth is that every project is different, and there is no one-size-fits-all solution. As a project manager, it is up to you to determine what works best for your team.
    This post originally appeared in the Toptal Engineering blog

  • Ensemble Methods: Elegant Techniques to Produce Improved Machine Learning Results

    Ensemble methods are techniques that create multiple models and then combine them to produce improved results. Ensemble methods usually produces more accurate solutions than a single model would. This has been the case in a number of machine learning competitions, where the winning solutions used ensemble methods. In the popular Netflix Competition, the winner used an ensemble method to implement a powerful collaborative filtering algorithm. Another example is KDD 2009 where the winner also used ensemble methods. You can also find winners who used these methods in Kaggle competitions, for example here is the interview with the winner of CrowdFlower competition.
    It is important that we understand a few terminologies before we continue with this article. Throughout the article I used the term “model” to describe the output of the algorithm that trained with data. This model is then used for making predictions. This algorithm can be any machine learning algorithm such as logistic regression, decision tree, etc. These models, when used as inputs of ensemble methods, are called ”base models”.
    In this blog post I will cover ensemble methods for classification and describe some widely known methods of ensemble: voting, stacking, bagging and boosting.

    Voting and Averaging Based Ensemble Methods

    Voting and averaging are two of the easiest ensemble methods. They are both easy to understand and implement. Voting is used for classification and averaging is used for regression.
    Voting and Averaging Based Ensemble Methods
    In both methods, the first step is to create multiple classification/regression models using some training dataset. Each base model can be created using different splits of the same training dataset and same algorithm, or using the same dataset with different algorithms, or any other method. The following Python-esque pseudocode shows the use of same training dataset with different algorithms.

    train = load_csv("train.csv")
    target = train["target"]
    train = train.drop("target")
    test = load_csv("test.csv")
    algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    algorithms = [linear_regression, decision_tree_regressor, ...] #for regression
    predictions = matrix(row_length=len(target), column_length=len(algorithms))
    for i,algorithm in enumerate(algorithms):
        predictions[,i] = algorithm.fit(train, target).predict(test)
    

    According to the above pseudocode, we created predictions for each model and saved them in a matrix called predictions where each column contains predictions from one model.

    Majority Voting

    Every model makes a prediction (votes) for each test instance and the final output prediction is the one that receives more than half of the votes. If none of the predictions get more than half of the votes, we may say that the ensemble method could not make a stable prediction for this instance. Although this is a widely used technique, you may try the most voted prediction (even if that is less than half of the votes) as the final prediction. In some articles, you may see this method being called “plurality voting”.

    Weighted Voting

    Unlike majority voting, where each model has the same rights, we can increase the importance of one or more models. In weighted voting you count the prediction of the better models multiple times. Finding a reasonable set of weights is up to you.

    Simple Averaging

    In simple averaging method, for every instance of test dataset, the average predictions are calculated. This method often reduces overfit and creates a smoother regression model. The following pseudocode code shows this simple averaging method:

    final_predictions = []
    for row_number in len(predictions):
        final_predictions.append(
            mean(prediction[row_number, ])
        )
    

    Weighted Averaging

    Weighted averaging is a slightly modified version of simple averaging, where the prediction of each model is multiplied by the weight and then their average is calculated. The following pseudocode code shows the weighted averaging:

    
    weights = [..., ..., ...] #length is equal to len(algorithms)
    final_predictions = []
    for row_number in len(predictions):
        final_predictions.append(
            mean(prediction[row_number, ]*weights)
        )
    

    Stacking Multiple Machine Learning Models

    Stacking, also known as stacked generalization, is an ensemble method where the models are combined using another machine learning algorithm. The basic idea is to train machine learning algorithms with training dataset and then generate a new dataset with these models. Then this new dataset is used as input for the combiner machine learning algorithm.
    Stacking Multiple Machine Learning Models
    The pseudocode of a stacking procedure is summarized as below:

    base_algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    stacking_train_dataset = matrix(row_length=len(target), column_length=len(algorithms))
    stacking_test_dataset = matrix(row_length=len(test), column_length=len(algorithms))
    for i,base_algorithm in enumerate(base_algorithms):
        stacking_train_dataset[,i] = base_algorithm.fit(train, target).predict(train)
        stacking_test_dataset[,i] = base_algorithm.predict(test)
    final_predictions = combiner_algorithm.fit(stacking_train_dataset, target).predict(stacking_test_dataset)
    

    As you can see in the above pseudocode, the training dataset for combiner algorithm is generated using the outputs of the base algorithms. In the pseudocode, the base algorithm is generated using training dataset and then the same dataset is used again to make predictions. But as we know, in the real world we do not use the same training dataset for prediction, so to overcome this problem you may see some implementations of stacking where training dataset is splitted. Below you can see a pseudocode where the training dataset is split before training the base algorithms:

    base_algorithms = [logistic_regression, decision_tree_classification, ...] #for classification
    stacking_train_dataset = matrix(row_length=len(target), column_length=len(algorithms))
    stacking_test_dataset = matrix(row_length=len(test), column_length=len(algorithms))
    for i,base_algorithm in enumerate(base_algorithms):
        for trainix, testix in split(train, k=10): #you may use sklearn.cross_validation.KFold of sklearn library
            stacking_train_dataset[testcv,i] = base_algorithm.fit(train[trainix], target[trainix]).predict(train[testix])
    stacking_test_dataset[,i] = base_algorithm.fit(train).predict(test)
    final_predictions = combiner_algorithm.fit(stacking_train_dataset, target).predict(stacking_test_dataset)
    

    Bootstrap Aggregating

    The name Bootstrap Aggregating, also known as “Bagging”, summarizes the key elements of this strategy. In the bagging algorithm, the first step involves creating multiple models. These models are generated using the same algorithm with random sub-samples of the dataset which are drawn from the original dataset randomly with bootstrap sampling method. In bootstrap sampling, some original examples appear more than once and some original examples are not present in the sample. If you want to create a sub-dataset with m elements, you should select a random element from the original dataset m times. And if the goal is generating n dataset, you follow this step n times.
    Bootstrap Aggregating
    At the end, we have n datasets where the number of elements in each dataset is m. The following Python-esque pseudocode show bootstrap sampling:

    def bootstrap_sample(original_dataset, m):
        sub_dataset = []
        for i in range(m):
            sub_dataset.append(
                random_one_element(original_dataset)
            )
        return sub_dataset
    

    The second step in bagging is aggregating the generated models. Well known methods, such as voting and averaging, are used for this purpose.
    The overall pseudocode look like this:

    def bagging(n, m, base_algorithm, train_dataset, target, test_dataset):
        predictions = matrix(row_length=len(target), column_length=n)
        for i in range(n):
            sub_dataset = bootstrap_sample(train_dataset, m)
            predictions[,i] = base_algorithm.fit(original_dataset, target).predict(test_dataset)
        final_predictions = voting(predictions) # for classification
        final_predictions = averaging(predictions) # for regression
        return final_predictions
    

    In bagging, each sub-samples can be generated independently from each other. So generation and training can be done in parallel.
    You can also find implementation of the bagging strategy in some algorithms. For example, Random Forestalgorithm uses the bagging technique with some differences. Random Forest uses random feature selection, and the base algorithm of it is a decision tree algorithm.

    Boosting: Converting Weak Models to Strong Ones

    The term “boosting” is used to describe a family of algorithms which are able to convert weak models to strong models. The model is weak if it has a substantial error rate, but the performance is not random (resulting in an error rate of 0.5 for binary classification). Boosting incrementally builds an ensemble by training each model with the same dataset but where the weights of instances are adjusted according to the error of the last prediction. The main idea is forcing the models to focus on the instances which are hard. Unlike bagging, boosting is a sequential method, and so you can not use parallel operations here.
    The general procedure of the boosting algorithm is defined as follows:

    def adjust_dataset(_train, errors):
        #create a new dataset by using the hardest instances
        ix = get_highest_errors_index(train)
        return concat(_train[ix], random_select(train))
    models = []
    _train = random_select(train)
    for i in range(n): #n rounds
        model = base_algorithm.fit(_train)
        predictions = model.predict(_train)
        models.append(model)
        errors = calculate_error(predictions)
        _train = adjust_dataset(_train, errors)
    final_predictions = combine(models, test)
    

    The adjust_dataset function returns a new dataset containing the hardest instances, which can then be used to force the base algorithm to learn from.
    Adaboost is a widely known algorithm which is a boosting method. The founders of Adaboost won the Gödel Prize for their work. Mostly, decision tree algorithm is preferred as a base algorithm for Adaboost and in sklearn library the default base algorithm for Adaboost is decision tree (AdaBoostRegressor and AdaBoostClassifier). As we discussed in the previous paragraph, the same incremental method applies for Adaboost. Information gathered at each step of the AdaBoost algorithm about the ‘hardness’ of each training sample is fed into the model. The ‘adjusting dataset’ step is different from the one described above and the ‘combining models’ step is calculated by using weighted voting.

    Conclusion

    Although ensemble methods can help you win machine learning competitions by devising sophisticated algorithms and producing results with high accuracy, it is often not preferred in the industries where interpretability is more important. Nonetheless, the effectiveness of these methods are undeniable, and their benefits in appropriate applications can be tremendous. In fields such as healthcare, even the smallest amount of improvement in the accuracy of machine learning algorithms can be something truly valuable.
    This post originally appeared on the Toptal Engineering blog

  • Context Validation in Domain-Driven Design

    Domain-driven design (DDD in short) is not a technology or a methodology. DDD provides a structure of practices and terminology for making design decisions that focus and accelerate software projects dealing with complicated domains. As described by Eric Evans and Martin Fowler, Domain objects are a place to put validation rules and business logic.
    Eric Evans:

    Domain Layer (or Model Layer): Responsible for representing concepts of the business, information about the business situation, and business rules. State that reflects the business situation is controlled and used here, even though the technical details of storing it are delegated to the infrastructure. This layer is the heart of business software.

    Martin Fowler:

    The logic that should be in a domain object is domain logic – validations, calculations, business rules – whatever you like to call it.

    Context Validation in Domain-Driven Design
    Putting all of validation in Domain objects results in huge and complex domain objects to work with. Personally I much prefer the idea of decoupling domain validations into separate validator components that can be reused anytime and that will be based on context and user action.
    As Martin Fowler wrote in a great article:  ContextualValidation.

    One common thing I see people do is to develop validation routines for objects. These routines come in various ways, they may be in the object or external, they may return a boolean or throw an exception to indicate failure. One thing that I think constantly trips people up is when they think of object validity in a context independent way, such as an isValid method implies. […] I think it’s much more useful to think of validation as something that’s bound to a context , typically an action that you want to do. Such as asking if this order valid to be filled, or is this customer valid to check in to the hotel. So rather than have methods like isValid, have methods like isValidForCheckIn.

    Action Validation Proposal

    In this article we will implement a simple interface ItemValidator for which you need to implement a validatemethod with return type ValidationResult. ValidationResult is an object containing the item that has been validated and also the Messages object. The latter contains an accumulation of errors, warnings, and information validation states (messages) dependent upon the execution context.
    Validators are decoupled components that can be easily reused anywhere they are needed. With this approach all dependencies, which are needed for validation checks, can be easily injected. For example, to check in the database if there is a user with given email only UserDomainService is used.
    Validators decoupling will be per context (action). So if UserCreate action and UserUpdate action will have decoupled components or any other action (UserActivate, UserDelete, AdCampaignLaunch, etc.), validation can rapidly grow.
    Each action validator should have a corresponding action model which will have only the allowed action fields. For creating users, the following fields are needed:
    UserCreateModel:

    {
      "firstName": "John",
      "lastName": "Doe",
      "email": "[email protected]",
      "password": "MTIzNDU="
    }
    

    And to update user the following are allowed externalId, firstName and lastName. externalId is used for user identification and only changing of firstName and lastName is allowed.
    UserUpdateModel:

    {
      "externalId": "a55ccd60-9d82-11e5-9f52-0002a5d5c51b",
      "firstName": "John Updated",
      "lastName": "Doe Updated"
    }
    

    Field integrity validations can be shared, firstName maximum length is always 255 characters.
    During validating it is desirable to not only get the first error that occurs, but a list of all issues encountered. For example, the following 3 issues may happen at the same time, and can be reported accordingly during execution:

    • invalid address format [ERROR]
    • email must be unique among users [ERROR]
    • password too short [ERROR]

    To achieve that kind of validation, something like validation state builder is needed, and for that purpose Messages is introduced. Messages is a concept that I heard from my great mentor years ago when he introduced it to support validation and also for various other things that can be done with it, as Messages are not just for validation.
    Note that in the following sections we will be using Scala to illustrate the implementation. Just in case you are not a Scala expert, fear not as it should be easy to follow along nonetheless.

    Messages in Context Validation

    Messages is an object that represents the validation state builder. It provides an easy way to collect errors, warnings, and information messages during validation. Each Messages object has an inner collection of Message objects and also can have a reference to parentMessages object.

    A Message object is an object that can have type, messageText, key (which is optional and is used to support validation of specific inputs which are identified by identifier), and finally childMessages that provies a great way for building composable message trees.
    A message can be of one of the following types:

    • Information
    • Warning
    • Error

    Messages structured like this allows us to build them iteratively and also allows decisions to be made about next actions based on prior messages state. For example, performing validation during user creation:

    @Component
    class UserCreateValidator @Autowired (private val entityDomainService: UserDomainService) extends ItemValidator[UserCreateEntity] {
      Asserts.argumentIsNotNull(entityDomainService)
      private val MAX_ALLOWED_LENGTH = 80
      private val MAX_ALLOWED_CHARACTER_ERROR = s"must be less than or equal to $MAX_ALLOWED_LENGTH character"
      override def validate(item: UserCreateEntity): ValidationResult[UserCreateEntity] = {
        Asserts.argumentIsNotNull(item)
        val validationMessages = Messages.of
        validateFirstName (item, validationMessages)
        validateLastName  (item, validationMessages)
        validateEmail     (item, validationMessages)
        validateUserName  (item, validationMessages)
        validatePassword  (item, validationMessages)
        ValidationResult(
          validatedItem = item,
          messages      = validationMessages
        )
      }
      private def validateFirstName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.firstName
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.FIRST_NAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
      private def validateLastName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.lastName
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.LAST_NAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
      private def validateEmail(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.email
        ValidateUtils.validateEmail(
          fieldValue,
          UserCreateEntity.EMAIL_FORM_ID,
          localMessages
        )
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.EMAIL_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
        if(!localMessages.hasErrors()) {
          val doesExistWithEmail = this.entityDomainService.doesExistByByEmail(fieldValue)
          ValidateUtils.isFalse(
            doesExistWithEmail,
            localMessages,
            UserCreateEntity.EMAIL_FORM_ID.value,
            "User already exists with this email"
          )
        }
      }
      private def validateUserName(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.username
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.USERNAME_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
        if(!localMessages.hasErrors()) {
          val doesExistWithUsername = this.entityDomainService.doesExistByUsername(fieldValue)
          ValidateUtils.isFalse(
            doesExistWithUsername,
            localMessages,
            UserCreateEntity.USERNAME_FORM_ID.value,
            "User already exists with this username"
          )
        }
      }
      private def validatePassword(item: UserCreateEntity, validationMessages: Messages) {
        val localMessages = Messages.of(validationMessages)
        val fieldValue = item.password
        ValidateUtils.validateLengthIsLessThanOrEqual(
          fieldValue,
          MAX_ALLOWED_LENGTH,
          localMessages,
          UserCreateEntity.PASSWORD_FORM_ID.value,
          MAX_ALLOWED_CHARACTER_ERROR
        )
      }
    }
    

    Looking into this code, you can see use of ValidateUtils. These utility functions are used to populate the Messages object in predefined cases. You can check out the implementation of ValidateUtils on Github code.
    During email validation, first it is checked if email is valid by calling ValidateUtils.validateEmail(…, and it is also checked if email has a valid length by calling ValidateUtils.validateLengthIsLessThanOrEqual(… . Once these two validations are done, checking if the email is already assigned to some User is performed, only if the prior email validation conditions are passing and that is done with  if(!localMessages.hasErrors()) { … . This way expensive database calls can be avoided. This is only part of UserCreateValidator. Complete source code can be found  here.
    Notice that one of the validation parameters stand out: UserCreateEntity.EMAIL_FORM_ID. This parameter connects validation state to a specific input ID.
    In previous examples, next action is decided based upon the fact if Messages object has errors (using hasErrors method). One can easily check if there are any “WARNING” messages and retry if necessary.
    One thing that can be noticed is the way localMessages is used. Local messages are messages that have been created the same as any message, but with parentMessages. With that said, the goal is to have a reference only to current validation state (in this example emailValidation), so localMessages.hasErrors can be called, where it is checked only if emailValidation context hasErrors. Also when a message is added to localMessages, it is also added to parentMessages and so all validation messages exist in higher context of UserCreateValidation.
    Now that we have seen Messages in action, in next chapter we will focus on ItemValidator.

    ItemValidator – Reusable Validation Component

    ItemValidator is a simple trait (interface) that forces developers to implement the method validate, which needs to return ValidationResult.
    ItemValidator:

    trait ItemValidator[T] {
      def validate(item:T) : ValidationResult[T]
    }
    

    ValidationResult:

    case class ValidationResult[T: Writes](
      validatedItem : T,
      messages      : Messages
    ) {
      Asserts.argumentIsNotNull(validatedItem)
      Asserts.argumentIsNotNull(messages)
      def isValid :Boolean = {
        !messages.hasErrors
      }
      def errorsRestResponse = {
        Asserts.argumentIsTrue(!this.isValid)
        ResponseTools.of(
          data      = Some(this.validatedItem),
          messages  = Some(messages)
        )
      }
    }
    

    When ItemValidators such as UserCreateValidator are implemented to be dependency injection components, then ItemValidator objects can be injected and reused in any object that needs UserCreate action validation.
    After validation is executed, it is checked if validation was successful. If it is, then user data is persisted to database, but if not the API response containing validation errors is returned.
    In the next section we will see how we can present validation errors in RESTful API response and also how to communicate with API consumers about execution action states.

    Unified API Response – Simple User Interaction

    After user action has been successfully validated, in our case user creation, validation action results need to be displayed to RESTful API consumer. The best way is to have a unified API response where only context will be switched (in terms of JSON, value of “data”). With unified responses, errors can be presented easily to RESTful API consumers.
    Unified response structure:

    {
        "messages" : {
            "global" : {
                "info": [],
                "warnings": [],
                "errors": []
            },
            "local" : []
        },
    	"data":{}
    }
    

    Unified response is structured to have two tiers of messages, global and local. Local messages are messages that are coupled to specific inputs. Such as “username is too long, at most 80 characters is allowed”_. Global messages are messages that are reflecting the state of whole data on page, such as “user will not be active until approved”. Local and global messages have three levels – error, warning and information. The value of “data” is specific to the context. When creating users the data field will contain user data, but when getting a list of users the data field will be an array of users.

    With this kind of structured response the client UI handler can be created easily, which will be responsible for displaying errors, warnings, and information messages. Global messages will be displayed at the top of the page, because they are related to global API action state, and local messages can be displayed near specified input (field), as they are directly related to the field’s value. Error messages can be presented in red color, warning messages in yellow, and information in blue.
    For example, in an AngularJS based client app we can have two directives responsible for handling local and global response messages, so that only these two handlers can deal with all responses in a consistent manner.
    Directive for the local message will need to be applied to an element parent to the actual element holding all the messages.
    localmessages.direcitive.js :

    (function() {
      'use strict';
      angular
        .module('reactiveClient')
        .directive('localMessagesValidationDirective', localMessagesValidationDirective);
      /** @ngInject */
      function localMessagesValidationDirective(_) {
        return {
          restrict: 'AE',
          transclude: true,
          scope: {
            binder: '='
          },
          template: '<div ng-transclude></div>',
          link: function (scope, element) {
            var messagesWatchCleanUp = scope.$watch('binder', messagesBinderWatchCallback);
            scope.$on('$destroy', function() {
              messagesWatchCleanUp();
            });
            function messagesBinderWatchCallback (messagesResponse) {
              if (messagesResponse != undefined && messagesResponse.messages != undefined) {
                if (messagesResponse.messages.local.length > 0) {
                  element.find('.alert').remove();
                  _.forEach(messagesResponse.messages.local, function (localMsg) {
                    var selector = element.find('[id="' + localMsg.inputId + '"]').parent();
                    _.forEach(localMsg.info, function (msg) {
                      var infoMsg = '<div class="form-control validation-alert alert alert-info alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(infoMsg);
                    });
                    _.forEach(localMsg.warnings, function (msg) {
                      var warningMsg = '<div class="form-control validation-alert alert alert-warning alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(warningMsg);
                    });
                    _.forEach(localMsg.errors, function (msg) {
                      var errorMsg = '<div class="form-control validation-alert  alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + msg + '</div>';
                      selector.after(errorMsg);
                    });
                  });
                }
              }
            }
          }
        }
      }
    })();
    

    Directive for global messages will be included in the root layout document (index.html) and will register to an event for handling all global messages.
    globalmessages.directive.js:

    (function() {
      'use strict';
      angular
        .module('reactiveClient')
        .directive('globalMessagesValidationDirective', globalMessagesValidationDirective);
      /** @ngInject */
      function globalMessagesValidationDirective(_, toastr, $rootScope, $log) {
        return {
          restrict: 'AE',
          link: function (scope) {
            var cleanUpListener = $rootScope.$on('globalMessages', globalMessagesWatchCallback);
            scope.$on('$destroy', function() {
              cleanUpListener();
            });
            function globalMessagesWatchCallback (event, messagesResponse) {
              $log.log('received rootScope event: ' + event);
              if (messagesResponse != undefined && messagesResponse.messages != undefined) {
                if (messagesResponse.messages.global != undefined) {
                  _.forEach(messagesResponse.messages.global.info, function (msg) {
                    toastr.info(msg);
                  });
                  _.forEach(messagesResponse.messages.global.warnings, function (msg) {
                    toastr.warning(msg);
                  });
                  _.forEach(messagesResponse.messages.global.errors, function (msg) {
                    toastr.error(msg);
                  });
                }
              }
            }
          }
        }
      }
    })();
    

    For a more complete example, let us consider the following response containing a local message:

    {
        "messages" : {
            "global" : {
                "info": [],
                "warnings": [],
                "errors": []
            },
            "local" : [
               {
                    "inputId" : "email",
                    "errors" : ["User already exists with this email"],
                    "warnings" : [],
                    "info" : []
                }
            ]
        },
    	"data":{
    	    "firstName": "John",
    	    "lastName": "Doe",
    	    "email": "[email protected]",
          "password": "MTIzNDU="
        }
    }
    

    The above response can lead to something as follows:

    On the other hand, with a global message in response:

    {
        "messages" : {
            "global" : {
                "info": ["User successfully created."],
                "warnings": ["User will not be available for login until is activated"],
                "errors": []
            },
            "local" : []
        },
    	"data":{
    	    "externalId": "a55ccd60-9d82-11e5-9f52-0002a5d5c51b",
    	    "firstName": "John",
    	    "lastName": "Doe",
    	    "email": "[email protected]"
        }
    }
    

    The client app can now show the message with more prominence:

    In above examples it can be seen how a unified response structure can be handled for any request with the same handler.

    Conclusion

    Applying validation on large projects can become confusing, and validation rules can be found everywhere throughout project code. Keeping validation consistent and well structured makes things easier and reusable.
    You can find these ideas implemented in two different versions of boilerplates below:

    In this article I have presented my suggestions on how to support deep, composable context validation which can be easily presented to a user. I hope this will help you solve the challenges of proper validation and error handling once and for all. Please feel free to leave your comments and share your thoughts below.