Blog

  • 10 reasons why choose BackdropCMS instead of Drupal

    10 reasons why choose BackdropCMS instead of Drupal

    What is Backdrop CMS?
    Backdrop CMS is a free and open-source content management system written in PHP and distributed under the GNU General Public License. Backdrop CMS is a fork of the Drupal project. The directory structure is like Drupal 8 but the code is similar to Drupal 7.
    10 reasons why choose BackdropCMS instead of Drupal.

    1. Why spend a lot of time managing configuration using Features module. Backdrop includes built-in Configuration Management tools that allow us to deploy configuration across environments using JSON files, which should save a lot of time compared to Features.
    2. The backdrop is slightly faster than Drupal 7 out of the box because of it’s lighter core. Generally, it’s about the same speed as D7 but since D8 is slower than D7, Backdrop is faster than D8.
    3. The backdrop has a built-in Panels-like module (Layout) that replaces the old Block system. Blocks are given new powers like contextual information, advanced conditional selection, multiple instances, control over markup, and config-based settings.
    4. Responsive, HTML5 elements, and better mobile support out of the box.
    5. Updated libraries (e.g. new jQuery versions).
    6. Browse and install add-ons directly from your Backdrop site. No need to scour the internet for available modules, themes, and layouts.
    7. Basic module out of the box no need to install manually.
    8. More stable compared to Drupal 8.
    9. Major features from Drupal 8
    10. Advance Caching and memory optimization.

    Here you can see the performance:

  • Best Bike Polish, Scratch remover, Car Polish, Vehicle Wax

    Hello Guys,
    If you love your bike/car and want to keep it shiny, I mean not only shiny a shin like a mirror. Then here is my recommendation for you.
    I have my Bajaj Avenger 220 – 2014 model and I love it when it shines like a mirror. And after 3 years it still shines like a brand new bike. “Formula 1 Scratch Out Heavy Duty Paste” will help you to glow your vehicle’s color and hide scratches and “Formula 1 Carnauba Paste Wax” will give it a mirror polish. And especially in the raining season, it will help to avoid rusting on the bike/vehicle, water spots on your vehicle. Here is the procedure to apply it

    1. Clean your vehicle with fresh water and keep it for dry
    2. Once it dry then apply “Formula 1 Scratch Out Heavy Duty Paste”
      1. Use a fresh and clean cloth to apply it. Do remember always apply and spread it in one direction so if you are comfortable in up and down direction then use that direction or if you want are comfortable with left and right direction then apply it in the left-right
    3. Once you are done with then wait for 5-10 minute
    4. Now apply “Formula 1 Carnauba Paste Wax” and apply it with its own sponge and don’t spread it to clean it. Remember you only need to spread it. And then wait for 10 minutes.
    5. After 10-minute use a clean cloth and rub it on the part where you apply that wax. And use one direction only. And after few minute you will note the shining like a mirror. Remember the much time you rub the more glow and shine.

    Here is the video for more detail

  • The Advanced Guide to Optimizing WordPress Performance

    The Advanced Guide to Optimizing WordPress Performance

    BY MARTÍN DI FELICE – FREELANCE SOFTWARE ENGINEER @ TOPTAL

    #Performance#Tips#WordPress

    This article was translated by Isabella Rolz into Spanish

    Today, WordPress powers 25% of the Internet. It’s easy to use, incredibly popular, and not going anywhere anytime soon.

    But WordPress can be slow. So how do you optimize it?

    There are loads of articles about how to tune and optimize WordPress. In fact, WordPress itself provides a robust guide on WordPress optimization. For the most part, these articles and tutorials cover pretty basic yet useful concepts, like using cache plugins, integrating with content delivery networks (CDNs), and minimizing requests. While these tips are highly effective and even necessary, in the end, they don’t address the underlying problem: Most slow WordPress sites are a result of bad or inefficient code.

    WordPress can be slow, but it doesn’t have to be.

    Tweet Therefore, this article is mainly aimed at providing developers with some guidelines that can help them address the underlying causes of many WordPress performance issues. WordPress provides many performance-oriented features that are often overlooked by developers. Code that doesn’t leverage these features can slow down the simplest of tasks , such as fetching posts. This article details four possible solutions, which address some of the underlying problems behind slow WordPress performance.

    Fetching Posts

    WordPress offers the possibility of fetching any kind of post from the database. There are three basic ways of doing so:

    • Using the query_posts() function: This is a very direct approach, but the problem is that it overrides the main query, which could lead to inconveniences. For example, this could be an issue if we wanted to determine, at some point after fetching the posts (such as inside footer.php), what kind of page we are dealing with. In fact, the official documentation has a note recommending against the use of this function as you will need to call an additional function to restore the original query. Moreover, replacing the main query will negatively impact page loading times.
    • Using the get_posts() function: This works almost like query_posts(), but it does not modify the main query. On the other hand, get_posts() by default performs the query with the suppress_filters parameter set to true. This could lead to inconsistencies, especially if we use query-related filters in our code, as posts that you are not expecting in a page may be returned by this function.
    • Using the WP_Query class: In my opinion, this is the best way to retrieve posts from the database. It does not alter the main query, and it is executed in its standard way, just like any other WordPress query.

    But whichever method we use to interact with the database, there are other things we need to consider.

    Limiting the Query

    We should always specify how many posts our query must fetch. In order to accomplish that, we use the posts_per_page parameter. WordPress lets us indicate -1 as a possible value for that parameter, in which case the system will try to fetch all the posts that meet the defined conditions. This is not a good practice, even if we are certain that we’ll only get a few results back as the response. For one, we rarely can be certain about only getting a few results back. And even if we can, setting no limit will require the database engine to scan the entire database looking for matches. Conversely, limiting the results often enables the database engine to only partially scan the data, which translates into less processing time and faster response. Another thing that WordPress does by default, which can adversely impact performance, is that it tries to bring sticky posts and calculate how many rows were found on the query. Often, though, we don’t really need that information. Adding these two parameters will disable those features and speed up our query:

    $query = new WP_Query( array(
    'ignore_sticky_posts'=> true,
    'no_found_rows'=> true
    )
    );
    

    Excluding Posts from the Query

    Sometimes we want to exclude certain posts from the query. WordPress offers a pretty direct way of achieving it: using the post__not_in parameter. For example:

    $posts_to_exclude = array( 1, 2, 3 );
    $posts_per_page= 10;
    $query = new WP_Query( array(
    'posts_per_page'=> $posts_per_page,
    'post__not_in'=> $posts_to_exclude
    )
    );
    for ( $i = 0; $i < count( $query->posts ); $i++ ) {
    //do stuff with $query->posts[ $i ]
    }
    

    But while this is pretty simple, it’s not optimal because internally it generates a subquery. Especially in large installations, this can lead to slow responses. It’s faster to let that processing be done by the PHP interpreter with some simple modifications:

    $posts_to_exclude = array( 1, 2, 3 );
    $posts_per_page= 10;
    $query = new WP_Query( array(
    'posts_per_page'=> $posts_per_page + count( $posts_to_exclude )
    )
    );
    for ( $i = 0; $i < count( $query->posts ) && $i < $posts_per_page; $i++ ) {
    if ( ! in_array( $query->posts[ $i ]->ID, $posts_to_exclude ) ) {
    //do stuff with $query->posts[ $i ]
    }
    }
    

    What did I do there? Basically, I took off some work from the database engine and left it instead to the PHP engine, which does the same stuff but in memory, which is way faster. How? First, I removed the post__not_in parameter from the query. Since the query may bring us some posts that we do not want as a result, I increased the posts_per_page parameter. That way I ensure that, even if I had had some undesired posts in my response, I would have at least $posts_per_page desired posts there. Then, when I loop over the posts I only process those which are not inside the $posts_to_exclude array.

    Avoiding Complex Parameterization

    All these query methods offer a wide variety of possibilities for fetching posts: by categories, by meta keys or values, by date, by author, etc. And while that flexibility is a powerful feature, it should be used with caution because that parametrization could translate into complex table joins and expensive database operations. In the next section, we will outline an elegant way to still achieve similar functionality without compromising performance.

    Squeezing the Most out of WordPress Options

    The WordPress Options API provides a series of tools to easily load or save data. It’s useful for handling small pieces of information, for which other mechanisms that WordPress offers (like posts or taxonomies) are overly complex.

    For example, if we want to store an authentication key or the background color of our site’s header, options are what we are looking for. WordPress not only gives us the functions to handle them, but it also enables us to do so in the most efficient way. Some of the options are even loaded directly when the system starts, thus providing us with faster access (when creating a new option, we need to consider whether we want to autoload it or not). Consider, for example, a site on which we have a carousel displaying breaking news specified in the back-end. Our first instinct would be to use a meta key for that as follows:

    // functions.php
    add_action( 'save_post', function ( $post_id ) {
    // For simplicity, we do not include all the required validation before saving
    // the meta key: checking nonces, checking post type and status, checking
    // it is not a revision or an autosaving, etc.
    update_post_meta( $post_id, 'is_breaking_news', ! empty ( $_POST['is_breaking_news'] ) );
    } );
    // front-page.php
    $query = new WP_Query( array(
    'posts_per_page'=> 1,
    'meta_key'=> 'is_breaking_news'
    )
    );
    $breaking_news = $query->posts[0] ?: NULL;
    

    As you can see, this approach is very simple, but it is not optimal. It will perform a database query trying to find a post with a specific meta key. We could use an option to achieve a similar result:

    // functions.php
    add_action( 'save_post', function ( $post_id ) {
    // Same comment for post validation
    if ( ! empty ( $_POST['is_breaking_news'] ) )
    update_option( 'breaking_news_id', $post_id );
    } );
    // front-page.php
    if ( $breaking_news_id = get_option( 'breaking_news_id' ) )
    $breaking_news = get_post( $breaking_news_id );
    else
    $breaking_news = NULL;
    

    The functionality slightly varies from one example to another. In the first piece of code, we will always get the latest breaking news, in terms of the post’s published date. In the second one, every time a new post is set as breaking news, it will overwrite the previous breaking news. But because we probably want one breaking news post at a time, it should not be a problem. And, in the end, we changed a heavy database query (using WP_Query with meta keys) into a simple and direct query (calling get_post()) which is a better and more performant approach. We could also make a small change, and use transients instead of options. Transients work similarly but allow us to specify an expiration time. For example, for breaking news, it fits like a glove because we don’t want an old post as breaking news, and if we leave the task of changing or eliminating that breaking news to the administrator, [s]he could forget to do it. So, with two simple changes, we add an expiration date:

    // functions.php
    add_action( 'save_post', function ( $post_id ) {
    // Same comment for post validation
    // Let's say we want that breaking news for one hour
    // (3600 = # of seconds in an hour).
    if ( ! empty ( $_POST['is_breaking_news'] ) )
    set_transient( 'breaking_news_id', $post_id, 3600 );
    } );
    // front-page.php
    if ( $breaking_news_id = get_transient( 'breaking_news_id' ) )
    $breaking_news = get_post( $breaking_news_id );
    else
    $breaking_news = NULL;
    

    Enable Persistent Caching

    WordPress natively has an object caching mechanism. Options, for example, are cached using that mechanism. But, by default, that caching is not persistent, meaning that it only lives for the duration of a single request. All data is cached in memory, for faster access, but it is only available during that request. Supporting persistent caching requires the installation of a persistent cache plugin. Some full-page cache plugins come with a persistent cache plugin included (for example W3 Total Cache), but others do not, and we need to install it separately. It will depend on the architecture of our platform, whether we will use files, Memcached or some other mechanism to store cached data, but we should take advantage of this amazing feature. One might ask: “If this is such a great feature, why doesn’t WordPress enable it by default”? The main reason is that, depending on the architecture of our platform, some cache techniques will work and others will not. If we host our site in our distributed server, for example, we should use an external cache system, (such as a Memcached server), but if our website resides on a single server, we could save some money by simply using the file system to cache. One thing that we need to take into account is cache expiration. This is the most common pitfall of working with persistent caching. If we don’t address this issue correctly, our users will complain that they will not see the changes they have made or that their changes took too long to apply. Sometimes we are going to find ourselves making tradeoffs between performance and dynamism, but even with those obstacles, persistent caching is something that virtually every WordPress installation should take advantage of.

    AJAXing the Fastest Way

    If we need to communicate via AJAX with our website, WordPress offers some abstraction at the time of processing the request on the server side. Even though those techniques can be used when programming back-end tools or form submissions from the front-end, they should be avoided if it is not strictly necessary. The reason for this is that in order to use those mechanisms, we are obligated to make a post request to some file located inside the wp-admin folder. The majority (if not all) of WordPress full-page caching plugins neither cache post requests nor calls to administrator files. For example, if we dynamically load more posts when the user is scrolling our homepage, it would be better to directly call to some other front-end page, which will get the benefits of being cached. We could then parse the results via JavaScript in the browser. Yes, we are sending more data than we need to, but we are winning in terms of processing speed and response time.

    Destroy the Notion That WordPress is Just Slow

    These are just a few pieces of advice that developers should consider when coding for WordPress. Sometimes, we forget that our plugin or theme might need to live together with other plugins, or that our site may be served by a hosting company that serves hundreds or thousands of other sites with a common database. We just focus on how the plugin should function and not on how it deals with that functionality, or how to do it in an efficient way. From the above, it is clear that root causes of poor performance in WordPress are bad and inefficient code. However, WordPress provides all the necessary functionalities through its various APIs that can help us build much more performant plugins and themes without compromising the speed of the overall platform. Originally published on Toptal.

  • Use Magento If You’re Serious About eCommerce

    Use Magento If You’re Serious About eCommerce

    You may have heard that Magento is the eCommerce platform you use if you’re serious about your business—and you’re serious about your business—so you’ve decided on Magento.

    But do you know what you’re getting yourself into?

    Magento is an incredibly powerful program. One blogger I read compared it to a Leatherman, because it had a tool for every use. I like to think of it more as one of those large universal remotes people used to buy that seemingly had a hundred programmable buttons that could control every media appliance in their house.

    It can do just about anything if, and only if, you’re willing to dedicate the time and money to make it happen. Magento is great, it really is, but it’s also complex. Are you willing to spend the time to educate your clients (or are they savvy enough to teach themselves) how to use Magento’s incredibly powerful admin panel? If not, you might want to look at another solution.

    Magento is an expert system. Much like the various Adobe products, such as Photoshop and Illustrator, it rewards expertise, but at the cost of a steep learning curve. It can be grueling initially, but with a little work it becomes a potent tool.

    For your business, this translates into more expensive hosting (does spending $300 a month on AWS hosting scare you?), higher development costs, and more upfront time working to understand the administrative features, but once these hurdles are overcome, you have a platform that is infinitely expandable and scalable.

    Because of Magento’s flexibility and ability to scale, your business will not outgrow Magento anytime soon, and if it does, you’ll be doing so much business, you’ll be successful enough to tackle the next stage in eCommerce evolution.

    Magento is the leading eCommerce platform, with roughly 30% of the market.

    Magento excels (and, in fact, may be basically the only option short of a custom-built web application) when you:

    • Have a large, complex inventory.
    • Need to model complex product types.
    • Have relatively static content.
    • Want to run multiple stores from a single CMS back-end.
    • Need a super powerful and expandable admin panel.

    Other great benefits include:

    • Magento’s large user base and commercial backing means that it is actively developed and secure. Security updates are published regularly and in a timely manner.
    • Magento also supports a huge variety of payment gateways.
    • Magento extensions have been developed for everything from auctions to data import and export.
    • Magento is SEO-friendly.

    Magento: eCommerce for Experts

    Magento is open-source and was specifically made for eCommerce. It’s a PHP framework loosely based on the Zend Framework and uses a MySQL database for storage. Its module templating system has a hierarchical folder structure, which allows developers and designers to override core and theme files without editing them and without breaking subsequent updates unnecessarily.

    Its open-source history is both a blessing and a curse.

    The Magento ecosystem likely wouldn’t exist without it, but it has also resulted in a large, complex codebase that’s sometimes poorly documented and often has confusingly named functions. Sometimes it feels like everything in Magento is an exception to a rule, and often modifications have to be made in many different files to implement a single feature change.

    This is partially why professional Magento developers are expensive. They’ve put in the time, taken the classes, stepped through the code, earned the certificates–worked damn hard to understand and master the complex beast–and as such, they deserve and expect to be compensated fairly for their time and expertise.

    Caching can be an issue with Magento.

    Properly configured on a professional hosting solution, Magento is highly-scalable and can run blazingly fast. Poorly configured on an underpowered hosting provider will take ages to load even the simplest page though. Caching is the answer: PHP opcode caching, database back-end caching, and full-page caching.

    Opcode caching is now pretty much standard with PHP, but you might need to update the php.ini file to configure it. A Redis back-end cache is also a must. And if you want the absolute best performance, a full page cache, like Varnish, is highly recommended.

    These requirements mean that you need a hosting solution that will support these features, and you need a development team that knows how to properly configure them. Magento won’t run well on discount hosting providers, like Bluehost and GoDaddy.

    You’ll need to spring for an Amazon EC2 or Digital Ocean instance (or an instance from one of the Magento-specific managed hosting providers that has these features already configured).

    And what’s with all these caches?

    Generally speaking, a cache is a short-term storage buffer for data that’s been fetched from disk or computed.

    It’s the computer’s way of saying: I went through all the trouble of fetching or generating this data, I might as well keep it around a little while in case anyone else needs it.

    Since caches are typically in volatile memory, retrieving data from a cache is orders of magnitude faster than recomputing or reading from disk.

    The different caches mentioned above work at different levels of abstraction in the framework.

    The opcode cache works at the level of PHP code compilation and saves already compiled chunks of PHP code for later execution. A back-end cache for Magento is an improvement on the file caching system. To display a page, Magento has to chew through potentially hundreds of PHP and XML files. This is slow.

    Often the page contents don’t change between requests. Because of this, when Magento renders a page, it saves the results in a file system cache.

    This is faster than re-rendering the page. But disk reads are still relatively slow, so using Redis as an in-memory cache to store these rendered blocks and pages is much faster (and it can also be used to store session data).
    The third cache I mentioned, Varnish, is a full-page cache.

    It works completely separate from Magento (and typically is installed on a separate server). It’s a caching HTTP reverse proxy: It sits between your website and the world, saving entire pages and associating them with request URLs.

    Caching sounds great, right? It is, but it also adds significant complexity.

    Consider this. Now, you’ve added a Redis database to your server; you’ve updated and maintained your configuration files; and you’ve possibly added another server to host your Varnish full-page cache.

    Further, what happens when a page changes content? How does the cache know not to send the cached result? Uh oh.

    There are obviously solutions to this, called cache invalidation, but it does add another layer of thought, complexity and potential problems.

    On top of this, if your development team is truly professional, they’re going to insist on a test environment in addition to the production environment as well as a Git repository on GitHub for source control (and by the way, if they’re not using source control, find another developer!).

    An alternative is WordPress WooCommerce.

    It’s helpful to compare Magento with one of it’s main alternatives: WordPress with the WooCommerce plugin installed.

    I recently worked with a company in Denver that had a fantastic Magento website and hosting solution. They had an Amazon EC2 instance for the production server, as well as one for their test environment. I was brought in to improve performance and help them implement a complete redesign of the website.

    I set them up with a Redis back-end cache, which made the page load almost instantaneously, and worked with the designer to turn his Photoshop mockups into a live website.

    After a few weeks of work, the website looked great. However, as I continued to work with them, I began to realize that the hosting costs and development costs were out of line with what they could afford.

    As their branding evolved, they wanted to make more changes to the website, as well as integrate a number of custom modules. They were paying me thousands of dollars to help design, and redesign the website. Furthermore, at the time, they only had around six products. On top of that, they asked me about creating dynamic content and setting up a blog on the website.

    Looking at their needs, the stage the company was in, and how much they were paying for hosting and development, we decided that Magento was not a great fit for them.

    After a lot of research, they went with a new WordPress/WooCommerce website.

    I essentially talked myself out of a job, but my priority was what was best for my client; and the truth is, if the client doesn’t know what they’re in for with Magento, doesn’t actually need its features, and doesn’t have the budget to support it, it’s not going to be fun for anybody involved.
    If you have a business with relatively few products that fit into a standard business product model, WordPress/WooCommerce might be a great option.

    WordPress developers are (generally) cheaper than Magento developers. The WordPress community is thriving, and the platform is very well-documented with a polished codebase. This solution is small, fast, and runs on pretty much any hosting provider, including all of the various discount providers.

    If this combination will work for you, it will save you money in both development and hosting costs. If you’re trying to do your site yourself, without paying an outside developer, you should probably avoid Magento and might want to consider WordPress/WooCommerce.

    Another reason you might look into WordPress/WooCommerce is if you want to take advantage of WordPress’s blogging capabilities. Magento has the ability to allow clients to create and update dynamic content, but it’s nowhere near as polished and as easy as it is with WordPress.

    That said, WordPress/WooCommerce doesn’t have anywhere near the ability of Magento to configure products and discounts and manage large inventories (not that it can’t do it–it has great features and is growing constantly–but this is where Magento excels).

    WordPress/WooCommerce will start to feel clunky when the number of products you sell grows past a few hundred, or when you start wanting to create complex, grouped products with custom attached attributes; or when you want to schedule discounts and give out rebates, but just to certain customer groups, and you want to cross-sell and up-sell and have a gift option; etc.

    Which solution is right for you? It depends.

    As is true with all technologies, Magento has a number of distinct advantages, but it also has its drawbacks.
    Key benefits of Magento include:

    • Open-source
    • Specifically made for eCommerce
    • Great discount system
    • Payment gateway integration is easy
    • Flexible and customizable
    • Very powerful admin panel
    • Highly scalable
    • Once optimized (vanish, db optimizations, redis caching, opcode caching), Magento can be quite fast
    • Multi-tenant support
    • SEO-friendly
    • Large user base, actively developed, secure

    Known issues include:

    • History of open-source has left it with an enormous, overgrown codebase that does everything, and leaves every door open to customization
    • Not as well-documented as other platforms
    • Development is expensive. Partly because it’s hard, and partly because it’s a popular system
    • Important features are often only available in commercial modules of varying quality that may even require third-party integration support
    • Expensive server requirements

    All of these factors need to be carefully weighed on a case-by-case basis when deciding whether Magento is the right solution for you or your client.

    Don’t be scared of Magento.

    Have I scared you off of Magento yet? I hope not.

    Does the following sound like you?

    You have a thriving store with 2,000 products and need the ability to create complex configurable products with a dozen options and bundle those products with other products into groups.

    You also want to be able to easily schedule sales and promos and hand out codes to clients for discounts. You have the budget and drive to invest in a truly professional solution that is open-source, SEO-friendly, highly scalable, and quite fast once optimized and properly hosted.

    If so, take a look at Magento. If you’re willing to invest the time and money, it’s a truly professional eCommerce solution that will last a lifetime.

    This article was originally posted on Toptal

  • The Mistakes Most Swift Developers Don’t Know They’re Making

    The Mistakes Most Swift Developers Don’t Know They’re Making

    Coming from an Objective-C background, in the beginning, I felt like Swift was holding me back. Swift was not allowing me to make progress because of its strongly typed nature, which used to be infuriating at times.

    Unlike Objective-C, Swift enforces many requirements at the compile time. Things that are relaxed in Objective-C, such as the id type and implicit conversions, are not a thing in Swift. Even if you have an Intand a Double, and you want to add them up, you will have to convert them to a single type explicitly.

    Also, optionals are a fundamental part of the language, and even though they are a simple concept, it takes some time to get used to them.

    In the beginning, you might want to force unwrap everything, but that will eventually lead to crashes. As you get acquainted with the language, you start to love how you hardly have runtime errors since many mistakes are caught at compile time.

    Most Swift programmers have significant previous experience with Objective-C, which, among other things, might lead them to write Swift code using the same practices they are familiar with in other languages. And that can cause some bad mistakes.

    In this article, we outline the most common mistakes that Swift developers make and ways to avoid them.

    Top Swift Development Mistakes

    Make no mistake – Objective-C best practices are not Swift best practices.

    1. Force-Unwrapping Optionals

    A variable of an optional type (e.g. String?) might or might not hold a value. When they don’t hold a value, they’re equal to nil. To obtain the value of an optional, first you have to unwrap them, and that can be made in two different ways.
    One way is optional binding using an if let or a guard let, that is:

      var optionalString: String?
      //...
      if let s = optionalString {
          // if optionalString is not nil, the test evaluates to
          // true and s now contains the value of optionalString
      }
      else {
          // otherwise optionalString is nil and the if condition evaluates to false
      }
    

    Second is forcing unwrap using the ! operator, or using an implicitly unwrapped optional type (e.g. String!). If the optional is nil, forcing an unwrap will cause a runtime error and terminate the application. Further, attempting to access the value of an implicitly unwrapped optional will cause the same.

    We sometimes have variables that we can’t (or don’t want to) initialize in the class/struct initializer. Thus, we have to declare them as optionals. In some cases, we assume they won’t be nil in certain parts of our code, so we force unwrap them or declare them as implicitly unwrapped optionals because that’s easier than having to do optional binding all the time. This should be done with care.

    This is similar to working with IBOutlets, which are variables that reference an object in a nib or storyboard. They won’t be initialized upon the parent object’s initialization (usually a view controller or custom UIView), but we can be sure they won’t be nil when viewDidLoad (in a view controller) or awakeFromNib (in a view) is called, and so we can access them safely.

    In general, the best practice is to avoid forcing unwrap and using implicitly unwrapped optionals. Always consider the optional could be nil and handle it appropriately either using optional binding, or checking if it’s not nil before forcing an unwrap, or accessing the variable in case of an implicitly unwrapped optional.

    2. Not Knowing Pitfalls of Strong Reference Cycles

    A strong reference cycle exists when a pair of objects keeps a strong reference to each other. This is not something new to Swift, since Objective-C has the same issue, and seasoned Objective-C developers are expected to properly manage this. It’s important to pay attention to strong references and what references what. The Swift documentation has a section dedicated to this topic.

    It’s particularly important to manage your references when using closures. By default, closures (or blocks), keep a strong reference to every object that is referenced inside of them. If any of these objects has a strong reference to the closure itself, we have a strong reference cycle. It’s necessary to make use of capture lists to properly manage how your references are captured.

    If there’s the possibility that the instance captured by the block will be deallocated before the block gets called, you have to capture it as a weak reference, which will be optional since it can be nil. Now, if you’re sure the captured instance will not be deallocated during the lifetime of the block, you can capture it as an unowned reference. The advantage of using unowned instead of weak is that the reference won’t be an optional and you can use the value directly without the need to unwrap it.

    In the following example, which you can run in the Xcode Playground, the Container class has an array and an optional closure that is invoked whenever its array changes (it uses property observers to do so). The Whatever class has a Container instance, and in its initializer, it assigns a closure to arrayDidChange and this closure references self, thus creating a strong relationship between the Whatever instance and the closure.

        struct Container<T> {
            var array: [T] = [] {
                didSet {
                    arrayDidChange?(array: array)
                }
            }
            var arrayDidChange: ((array: [T]) -> Void)?
        }
        class Whatever {
            var container: Container<String>
            init() {
                container = Container<String>()
                container.arrayDidChange = { array in
                    self.f(array)
                }
            }
            deinit {
                print("deinit whatever")
            }
            func f(s: [String]) {
                print(s)
            }
        }
        var w: Whatever! = Whatever()
        // ...
        w = nil
    

    If you run this example, you’ll notice that deinit whatever never gets printed, which means our instance wdoesn’t get deallocated from memory. To fix this, we have to use a capture list to not capture self strongly:

        struct Container<T> {
            var array: [T] = [] {
                didSet {
                    arrayDidChange?(array: array)
                }
            }
            var arrayDidChange: ((array: [T]) -> Void)?
        }
        class Whatever {
            var container: Container<String>
            init() {
                container = Container<String>()
                container.arrayDidChange = { [unowned self] array in
                    self.f(array)
                }
            }
            deinit {
                print("deinit whatever")
            }
            func f(s: [String]) {
                print(s)
            }
        }
        var w: Whatever! = Whatever()
        // ...
        w = nil
    

    In this case, we can use unowned, because self will never be nil during the lifetime of the closure.
    It’s a good practice to nearly always use capture lists to avoid reference cycles, which will reduce memory leaks, and a safer code in the end.

    3. Using self Everywhere

    Unlike in Objective-C, with Swift, we are not required to use self to access a class’ or struct’s properties inside a method. We are only required to do so in a closure because it needs to capture self. Using selfwhere it’s not required is not exactly a mistake, it works just fine, and there will be no errors and no warnings. However, why write more code than you have to? Also, it is important to keep your code consistent.

    4. Not Knowing the Type of Your Types

    Swift uses value types and reference types. Moreover, instances of a value type exhibit a slightly different behavior of instances of reference types. Not knowing what category each of your instances fit in will cause false expectations on the behavior of the code.

    In the most object oriented languages, when we create an instance of a class and pass it around to other instances and as an argument to methods, we expect this instance to be the same everywhere. That means any change to it will be reflected everywhere, because in fact, what we have are just a bunch of references to the exact same data. Objects that exhibit this behavior are reference types, and in Swift, all types declared as class are reference types.

    Next, we have value types which are declared using struct or enum. Value types are copied when they’re assigned to a variable or passed as an argument to a function or method. If you change something in the copied instance, the original one will not be modified. Value types are immutable. If you assign a new value to a property of an instance of a value type, such as CGPoint or CGSize, a new instance is created with the changes. That’s why we can use property observers on an array (as in the example above in the Containerclass) to notify us of changes. What’s actually happening, is that a new array is created with the changes; it is assigned to the property, and then didSet gets invoked.

    Thus, if you don’t know the object you’re dealing with is of a reference or value type, your expectations about what your code is going to do, might be entirely wrong.

    5. Not Using the Full Potential of Enums

    When we talk about enums, we generally think of the basic C enum, which is just a list of related constants that are integers underneath. In Swift, enums are way more powerful. For example, you can attach a value to each enumeration case. Enums also have methods and read-only/computed properties that can be used to enrich each case with more information and details.

    The official documentation on enums is very intuitive, and the error handling documentation presents a few use cases for enums’ extra power in Swift. Also, check out following extensive exploration of enums in Swift to learn pretty much everything you can do with them.

    6. Not Using Functional Features

    The Swift Standard Library provides many methods that are fundamental in functional programming and allow us to do a lot with just one line of code, such as map, reduce, and filter, among others.

    Let’s examine few examples.

    Say, you have to calculate the height of a table view. Given you have a UITableViewCell subclass such as the following:

      class CustomCell: UITableViewCell {
          // Sets up the cell with the given model object (to be used in tableView:cellForRowAtIndexPath:)
          func configureWithModel(model: Model)
          // Returns the height of a cell for the given model object (to be used in tableView:heightForRowAtIndexPath:)
          class func heightForModel(model: Model) -> CGFloat
      }
    

    Consider, we have an array of model instances modelArray; we can compute the height of the table view with one line of code:

      let tableHeight = modelArray.map { CustomCell.heightForModel($0) }.reduce(0, combine: +)
    

    The map will output an array of CGFloat, containing the height of each cell, and the reduce will add them up.

    If you want to remove elements from an array, you might end up doing the following:

      var supercars = ["Lamborghini", "Bugatti", "AMG", "Alfa Romeo", "Koenigsegg", "Porsche", "Ferrari", "McLaren", "Abarth", "Morgan", "Caterham", "Rolls Royce", "Audi"]
      func isSupercar(s: String) -> Bool {
          return s.characters.count > 7
      }
      for s in supercars {
          if !isSupercar(s), let i = supercars.indexOf(s) {
              supercars.removeAtIndex(i)
          }
      }
    

    This example doesn’t look elegant, nor very efficient since we’re calling indexOf for each item. Consider the following example:

      var supercars = ["Lamborghini", "Bugatti", "AMG", "Alfa Romeo", "Koenigsegg", "Porsche", "Ferrari", "McLaren", "Abarth", "Morgan", "Caterham", "Rolls Royce", "Audi"]
      func isSupercar(s: String) -> Bool {
          return s.characters.count > 7
      }
      for (i, s) in supercars.enumerate().reverse() { // reverse to remove from end to beginning
          if !isSupercar(s) {
              supercars.removeAtIndex(i)
          }
      }
    

    Now, the code is more efficient, but it can be further improved by using the filter:

      var supercars = ["Lamborghini", "Bugatti", "AMG", "Alfa Romeo", "Koenigsegg", "Porsche", "Ferrari", "McLaren", "Abarth", "Morgan", "Caterham", "Rolls Royce", "Audi"]
      func isSupercar(s: String) -> Bool {
          return s.characters.count > 7
      }
      supercars = supercars.filter(isSupercar)
    

    The next example illustrates how you can remove all subviews of a UIView that meet certain criteria, such as the frame intersecting a particular rectangle. You can use something like:

      for v in view.subviews {
        if CGRectIntersectsRect(v.frame, rect) {
          v.removeFromSuperview()
        }
      }
      ```
      We can do that in one line using `filter`
      ```
      view.subviews.filter { CGRectIntersectsRect($0.frame, rect) }.forEach { $0.removeFromSuperview() }
    

    We have to be careful, though, because you might be tempted to chain a couple of calls to these methods to create fancy filtering and transforming, which may end up with one line of unreadable spaghetti code.

    7. Staying in the Comfort-Zone and Not Trying Protocol-Oriented Programming

    Swift is claimed to be the first protocol-oriented programming language, as mentioned in the WWDC Protocol-Oriented Programming in Swift session. Basically, that means we can model our programs around protocols and add behavior to types simply by conforming to protocols and extending them. For example, given we have a Shape protocol, we can extend CollectionType (which is conformed by types such as Array, Set, Dictionary), and add a method to it that calculates the total area accounting for intersections

      protocol Shape {
          var area: Float { get }
          func intersect(shape: Shape) -> Shape?
      }
      extension CollectionType where Generator.Element: Shape {
          func totalArea() -> Float {
              let area = self.reduce(0) { (a: Float, e: Shape) -> Float in
                  return a + e.area
              }
              return area - intersectionArea()
          }
          func intersectionArea() -> Float {
              /*___*/
          }
      }
    

    The statement where Generator.Element: Shape is a constraint that states the methods in the extension will only be available in instances of types that conform to CollectionType, which contains elements of types that conform to Shape. For example, these methods can be invoked on an instance of Array<Shape>, but not on an instance of Array<String>. If we have a class Polygon that conforms to the Shape protocol, then those methods will be available for an instance of Array<Polygon> as well.

    With protocol extensions, you can give a default implementation to methods declared in the protocol, which will then be available in all types that conform to that protocol without having to make any changes to those types (classes, structs or enums). This is done extensively throughout the Swift Standard Library, for example, the mapand reduce are defined in an extension of CollectionType, and this same implementation is shared by types such as Array and Dictionary without any extra code.

    This behavior is similar to mixins from other languages, such as Ruby or Python. By simply conforming to a protocol with default method implementations, you add functionality to your type.

    Protocol oriented programming might look quite awkward and not very useful at first sight, which could make you ignore it and not even give it a shot. This post gives a good grasp of using protocol-oriented programming in real applications.

    As We Learned, Swift Is Not a Toy Language

    Swift was initially received with a lot of skepticism; people seemed to think that Apple was going to replace Objective-C with a toy language for kids or with something for non-programmers. However, Swift has proven to be a serious and powerful language that makes programming very pleasant. Since it is strongly typed, it is hard to make mistakes, and as such, it’s difficult to list mistakes you can make with the language.

    When you get used to Swift and go back to Objective-C, you will notice the difference. You’ll miss nice features Swift offers and will have to write tedious code in Objective-C to achieve the same effect. Other times, you’ll face runtime errors that Swift would have caught during compilation. It is a great upgrade for Apple programmers, and there’s still a lot more to come as the language matures.

    This article was originally posted on Toptal

  • How to Isolate Client-Server Interaction Logic in iOS Applications

    How to Isolate Client-Server Interaction Logic in iOS Applications

    Nowadays most mobile applications rely heavily on client-server interactions. Not only does this mean that can they offload most of their heavy tasks to backend servers, but it also allows these mobile applications to offer all sorts of features and functionality that can only be made available through the Internet.

    Backend servers are usually designed to offer their services through RESTful APIs. For simpler applications, we often feel tempted to get by creating spaghetti code; mixing code that invokes the API with rest of the application logic. However as applications grow complex and deal with more and more APIs, it can become a nuisance to interact with these APIs in an unstructured, unplanned manner.

    Keep your iOS application code clutter-free with a well-designed REST client networking module.

    Keep your iOS application code clutter-free with a well-designed REST client networking module.

    This article discusses an architectural approach for building a clean REST client networking module for iOS applications that allows you to keep all of your client-server interaction logic isolated from rest of your application code.

    Client-Server Applications

    A typical client-server interaction looks something like this:

    1. A user performs some action (e.g., tapping on some button or performing some other gesture on the screen).
    2. The application prepares and sends an HTTP/REST request in response to the user action.
    3. The server processes the request and responds accordingly to the application.
    4. The application receives the response and updates the user interface based on it.

    At quick glance, the overall process may look simple, but we do have to think about the details.

    Even assuming that a backend server API works as advertised (which is not always the case!), it can often be poorly designed making it inefficient, or even difficult, to use. One common annoyance is that all calls to the API require the caller to redundantly provide the same information (e.g., how request data is formatted, an access token that the server can use to identify the currently signed in user, and so on).

    Mobile applications may also need to utilize multiple back-end servers concurrently for different purposes. One server may, for example, be dedicated to user authentication while another deals with collecting analytics only.

    Furthermore, a typical REST client will need to do way more than just invoke remote APIs. The ability to cancel pending requests, or a clean and manageable approach to handling errors, are examples of functionality that needs to be built into any robust mobile application.

    An Overview of the Architecture

    The core of our REST client will be built on these following components:

    • Models: Classes that describe the data models of our application, reflecting the structure of data received from, or sent to, the backend servers.
    • Parsers: Responsible for decoding server responses and producing model objects.
    • Errors: Objects to represent erroneous server responses.
    • Client: Sends requests to backend servers and receives responses.
    • Services: Manage logically linked operations (e.g. authentication, managing user related data, analytics, etc).

    This is how each of these components will interact with each other:

    The arrows 1 through 10 in the image above show an ideal sequence of operations between the application invoking a service and the service eventually returning the requested data as a model object. Each component in that flow has a specific role ensuring separation of concerns within the module.

    Implementation

    We will implement our REST client as part of our imaginary social network application into which we will load a list of the currently logged in user’s friends. We will assume our remote server uses JSON for responses.
    Let us begin by implementing our models and parsers.

    From Raw JSON to Model Objects

    Our first model, User, defines the structure of information for any user of the social network. To keep things simple, we will only include fields that are absolutely necessary for this tutorial (in a real application, the structure would typically have a lot more properties).

    struct User {
        var id: String
        var email: String?
        var name: String?
    }
    

    Since we will receive all user data from the backend server via its API, we need a way to parse the API response into a valid User object. To do this, we will add a constructor to User that accepts a parsed JSON object (Dictionary) as a parameter. We will define our JSON object as an aliased type:

    typealias JSON = [String: Any]
    

    We will then add the constructor function to our User struct as follows:

    extension User {
        init?(json: JSON) {
            guard let id = json["id"] as? String else {
                return nil
            }
            self.id = id
            self.email = json["email"] as? String
            self.name = json["name"] as? String
        }
    }
    

    To preserve the original default constructor of User, we add the constructor through an extension on the User type.
    Next, to create a User object from a raw API response, we need to perform the following two steps:

    // Transform raw JSON data to parsed JSON object using JSONSerializer (part of standard library)
    let userObject = (try? JSONSerialization.jsonObject(with: data, options: [])) as? JSON
    // Create an instance of `User` structure from parsed JSON object
    let user = userObject.flatMap(User.init)
    

     

    Streamlined Error Handling

    We will define a type to represent different errors that may occur when attempting to interact with the backend servers. We can divide all such errors into three basic categories:

    • No Internet connectivity
    • Errors that reported as a part of the response (e.g. validation errors, insufficient access rights, etc.)
    • Errors that the server fails to report as a part of the response (e.g. server crash, responses timing out, etc.)
    • We can define our error objects as an enumeration type. And while we are at it, it is a good idea to make our ServiceError type conform to the Error protocol. This will allow us to use and handle these error values using standard mechanisms provided by Swift (such as using throw to throw an error).

    enum ServiceError: Error {
    case noInternetConnection
    case custom(String)
    case other
    }
    Unlike noInternetConnection and other errors, the custom error has a value associated with it. This will allow us to use the error response from the server as an associated value for the error itself, thereby giving the error more context.
    Now, let’s add a errorDescription property to the ServiceError enumartion to make the errors more descriptive. We will add hardcoded messages for the noInternetConnection and other errors and use the associated value as the message for custom errors.
    extension ServiceError: LocalizedError {
    var errorDescription: String? {
    switch self {
    case .noInternetConnection:
    return “No Internet connection”
    case .other:
    return “Something went wrong”
    case .custom(let message):
    return message
    }
    }
    }
    There is just one more thing we need to implement in our ServiceError enumeration. In the case of a custom error, we need to transform the server JSON data into an error object. To do this, we use the same approach we used in the case of models:
    extension ServiceError {
    init(json: JSON) {
    if let message = json[“message”] as? String {
    self = .custom(message)
    } else {
    self = .other
    }
    }
    }

    Bridging the Gap Between the Application and Backend Server

    The client component will be an intermediary between the application and the backend server. It’s a critical component that will define how the application and the server will communicate, yet it will know nothing about the data models and their structures. The client will be responsible for invoking specific URLs with provided parameters and returning incoming JSON data parsed as JSON objects.

    enum RequestMethod: String {
    case get = "GET"
    case post = "POST"
    case put = "PUT"
    case delete = "DELETE"
    }
    final class WebClient {
    private var baseUrl: String
    init(baseUrl: String) {
    self.baseUrl = baseUrl
    }
    func load(path: String, method: RequestMethod, params: JSON, completion: @escaping (Any?, ServiceError?) -> ()) -> URLSessionDataTask? {
    // TODO: Add implementation
    }
    }

    Let’s examine what’s happening in the above code…

    First, we declared an enumeration type, RequestMethod, that describes four common HTTP methods. These are among the methods used in REST APIs.

    The WebClient class contains the baseURL property which will be used to resolve all relative URLs that it receives. In case our application needs to interact with multiple servers, we can create multiple instances of WebClient each with a different value for baseURL.

    The Client has a single method load, which takes a path relative to baseURL as a parameter, request method, request parameters, and completion closure. The completion closure is invoked with the parsed JSON and ServiceError as parameters. For now, the method above lacks an implementation, which we will get to shortly.

    Before implementing the load method, we need a way to create a URL from all the information available to the method. We will extend the URL class for this purpose:

    extension URL {
    init(baseUrl: String, path: String, params: JSON, method: RequestMethod) {
    var components = URLComponents(string: baseUrl)!
    components.path += path
    switch method {
    case .get, .delete:
    components.queryItems = params.map {
    URLQueryItem(name: $0.key, value: String(describing: $0.value))
    }
    default:
    break
    }
    self = components.url!
    }
    }

    Here we simply add the path to the base URL. For GET and DELETE HTTP methods, we also add the query parameters to the URL string.

    Next, we need to be able to create instances of URLRequest from given parameters. To do this we will do something similar to what we did for URL:

    extension URLRequest {
    init(baseUrl: String, path: String, method: RequestMethod, params: JSON) {
    let url = URL(baseUrl: baseUrl, path: path, params: params, method: method)
    self.init(url: url)
    httpMethod = method.rawValue
    setValue("application/json", forHTTPHeaderField: "Accept")
    setValue("application/json", forHTTPHeaderField: "Content-Type")
    switch method {
    case .post, .put:
    httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
    default:
    break
    }
    }
    }

    Here, we first create a URL using the constructor from the extension. Then we initialize an instance of URLRequest with this URL, set a few HTTP headers as necessary, and then in case of POST or PUT HTTP methods, add parameters to the request body.

    Now that we have covered all the prerequisites, we can implement the load method:

    final class WebClient {
    private var baseUrl: String
    init(baseUrl: String) {
    self.baseUrl = baseUrl
    }
    func load(path: String, method: RequestMethod, params: JSON, completion: @escaping (Any?, ServiceError?) -> ()) -> URLSessionDataTask? {
    // Checking internet connection availability
    if !Reachability.isConnectedToNetwork() {
    completion(nil, ServiceError.noInternetConnection)
    return nil
    }
    // Adding common parameters
    var parameters = params
    if let token = KeychainWrapper.itemForKey("application_token") {
    parameters["token"] = token
    }
    // Creating the URLRequest object
    let request = URLRequest(baseUrl: baseUrl, path: path, method: method, params: params)
    // Sending request to the server.
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
    // Parsing incoming data
    var object: Any? = nil
    if let data = data {
    object = try? JSONSerialization.jsonObject(with: data, options: [])
    }

    if let httpResponse = response as? HTTPURLResponse, (200..<300) ~= httpResponse.statusCode { completion(object, nil) } else { let error = (object as? JSON).flatMap(ServiceError.init) ?? ServiceError.other completion(nil, error) } } task.resume() return task } } The load method above performs the following steps: Check availability of the Internet connection. If Internet connectivity is not available, we call the completion closure immediately with noInternetConnection error as a parameter. (Note: Reachability in the code is a custom class, which uses one of the common approaches to check the Internet connection.) Add common parameters.. This can include common parameters such as an application token or user id. Create the URLRequest object, using the constructor from the extension. Send the request to the server. We use the URLSession object to send data to the server. Parse incoming data. When the server responds, we first parse the response payload into a JSON object using JSONSerialization. Then we check the status code of the response. If it is a success code (i.e., in the range between 200 and 299), we call the completion closure with the JSON object. Otherwise, we transform the JSON object into a ServiceError object and call the completion closure with that error object. Defining Services for Logically Linked Operations In the case of our application, we need a service that will deal with tasks related to friends of a user. For this, we create a FriendsService class. Ideally, a class like this will be in charge of operations such as getting a list of friends, adding a new friend, removing a friend, grouping some friends into a category, etc. For simplicity in this tutorial, we will implement just one method:

    final class FriendsService { private let client = WebClient(baseUrl: "https://your_server_host/api/v1") @discardableResult func loadFirends(forUser user: User, completion: @escaping ([User]?, ServiceError?) -> ()) -> URLSessionDataTask? {
    let params: JSON = ["user_id": user.id]
    return client.load(path: "/friends", method: .get, params: params) { result, error in
    let dictionaries = result as? [JSON]
    completion(dictionaries?.flatMap(User.init), error)
    }
    }
    }

    The FriendsService class contains a client property of type WebClient. It is initialized with the base URL of the remote server which is in charge of managing friends. As previously mentioned, in other service classes, we can have a different instance of WebClient initialized with a different URL if necessary.

    In the case of an application that works with only one server, the WebClient class can be given a constructor that initializes with that server’s URL:

    final class WebClient {
    // ...
    init() {
    self.baseUrl = "https://your_server_base_url"
    }
    // ...
    }

    The loadFriends method, when invoked, prepares all the necessary parameters and uses FriendService’s instance of WebClient to make an API request. After it receives the response from the server through the WebClient, it transforms the JSON object into User models and calls the completion closure with them as a parameter.

    A typical usage of the FriendService may look something like the following:

    let friendsTask: URLSessionDataTask!
    let activityIndicator: UIActivityIndicatorView!
    var friends: [User] = []
    func friendsButtonTapped() {
    friendsTask?.cancel() //Cancel previous loading task.
    activityIndicator.startAnimating() //Show loading indicator
    friendsTask = FriendsService().loadFriends(forUser: currentUser) {[weak self] friends, error in
    DispatchQueue.main.async {
    self?.activityIndicator.stopAnimating() //Stop loading indicators
    if let error = error {
    print(error.localizedDescription) //Handle service error
    } else if let friends = friends {
    self?.friends = friends //Update friends property
    self?.updateUI() //Update user interface
    }
    }
    }
    }

    In the above example, we are assuming that the function friendsButtonTapped is invoked whenever the user taps on a button intended to show them a list of their friends in the network. We also keep a reference to the task in the friendsTask property so that we can cancel the request at any time by calling friendsTask?.cancel().

    This allows us to have a greater control of the lifecycle of pending requests, enabling us to terminate them when we determine that they have become irrelevant.

    Conclusion
    In this article, I have shared a simple architecture of a networking module for your iOS application that is both trivial to implement and can be adapted to the intricate networking needs of most iOS applications. However, the key takeaway from this is that a properly designed REST client and components accompanying it – that are isolated from the rest of your application logic – can help keep your application’s client-server interaction code simple, even as the application itself becomes increasingly complex.

    I hope you find this article helpful in building your next iOS application. You can find the source code of this networking module on GitHub. Check out the code, fork it, change it, play with it.

    If you find some other architecture more preferable for you and your project, please do share the details in the comments section below.

    Source: Toptal

  • 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.

  • Build Ultra-Modern Web Apps with Angular Material

    Build Ultra-Modern Web Apps with Angular Material

    At the Google I/O Conference back in 2014, Google announced Material Design, their new design language. They have since converted much of their popular applications to adhere to this new spec in an effort to provide a consistent experience. Now they are trying to convince you to follow along as well.
    Angular Material: Superheroic Javascript Framework Meets Ultra-Modern Design

    What is Material Design?

    After a visit to the official Material Design spec, you will immediately get a feeling of ultra-modern minimalism. Basic shapes and flat colors are the theme here. Going through the documentation is quite an experience. I recommend taking a look for yourself, but I will summarize it here.

    Goal

    The purpose is to create a visual language that synthesizes classic principles of good design with the innovation and possibility of technology and science. Also to develop a single underlying system that allows for a unified experience across various platforms and device sizes.

    Principles

    Material Design is founded on three principles.

    Material Is the Metaphor

    Inspired by the study of paper and ink, the material lives in 3D space and is grounded in tactile reality. It gives the illusion of space by using realistic shadows. The paper material must abide by the laws of physics (i.e. two pieces of paper may not travel through each other), but may supercede the physical world (i.e. a paper may grow or shrink).

    Bold, Graphic, Intentional

    Deliberate color choices, edge-to-edge imagery, large-scale typography, and intentional white space create a bold and graphic interface that immerse the user in the experience. The Floating Action Button, or FAB, is a prime example of this principle. Have you noticed that little circle with the ‘plus’ symbol floating around in your Google Inbox app? Material Design makes it very apparent that this is an important button.

    Motion Provides Meaning

    Motion is meaningful and appropriate, serving to focus attention and maintain continuity. Feedback is subtle yet clear. Transitions are efficient yet coherent. The main point here is to animate only when it has a purpose and not to overdo it.

    How does AngularJS fit into Material Design?

    AngularJS, Google’s “Superheroic JavaScript MVW Framework”, addresses many of the challenges encountered in developing single-page applications (SPA). It provides the framework needed for creating modern web applications that connect to APIs and never need the page to be refreshed.

    AngularJS: A New Approach

    Angular is what HTML would have been, had it been designed for applications. HTML is a great declarative language for static documents, but creating dynamic applications not so much.
    Creating dynamic applications with HTML has always been an exercise in tricking the browser into doing things it wasn’t meant to do. There are a couple of approaches to doing this.

    1. Library – a collection of functions. (jQuery)
    2. Framework – code dynamically fills in static elements when needed. (Durandal, Ember)

    Angular takes a different approach to solve this problem. Instead of struggling with the HTML it is given, it creates new HTML constructs. Angular teaches the browser new HTML syntax through a construct called ‘directives’. Angular comes with a set of these directives built-in, but also allows you to create custom directives, so it allows you to write your own HTML elements.
    Wouldn’t it be neat if Google created a set of directives based on Material Design principles?

    Introducing Angular Material

    Google is actively developing Angular Material, an implementation of Material Design in AngularJS. Angular Material provides a set of reusable UI components based on the Material Design system. Angular Material is composed of several pieces. It has a CSS library for typography and other elements, it provides an interesting JavaScript approach for theming, and its responsive layout uses a flex grid. But the most appealing feature of Angular Material is its amazing collection of directives.

    Getting Started

    I have created an open source project to help jumpstart your next Angular Material project. The purpose of this project is to give an example of everything Angular Material has to offer, all under one roof. Navigation, paging, theming, and the entire collection of directives are ready to go, all you have to do is feed in your data and bind it to the HTML.
    Take a look at the demo here or fork the code on GitHub.

    Directives

    Directives are a core Angular feature. Angular comes with several directives that you use all of the time like ng-model or ng-repeat. They are a very important piece of Angular that makes the framework function as it should.

    How to Use an Angular Material Directive

    Angular Material extends this directive library with a set of beautiful Material Design inspired directives. Angular Material directives are HTML tags that begin with ‘md’; short for Material Design. They couldn’t be much easier to use. For example, let’s take a look at the good old button.
    A standard HTML button might look something like this.

    <button>Click Me</button>
    

    An Angular Material button looks like this.

    <md-button>Click Me</md-button>
    

    And this is all that is needed to make a Material button. Now, there are several other options that are available for this directive such as theming it and raising it from the surface to imply importance.

    <md-button class="md-raised md-primary md-hue-1">Click Me</md-button>
    

    Services

    Services are also core to Angular functionality. They are used to share code across the application. A common core service like $http is used and reused for data calls in Angular applications.
    Angular services are:

    1. Lazily instantiated – Angular only instantiates a service when an application component depends on it.
    2. Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

    How to Use an Angular Material Service

    Angular Material comes packaged with some services that provide some extra functionality to the application. They also contribute to the performance of some of the directives. A great example of a service is the ‘toast’.

    A toast is a small notification that slides in from the top of the screen and goes away after a few seconds. Using this service is easy.
    In JavaScript,

    $mdToast.show(
          $mdToast.simple('Simple Toast!')
            .position('left bottom')
            .hideDelay(3000)
        );
    

    This example shows a simple toast that pops up on the bottom left of the screen and retreats after 3 seconds.
    Some services can be personalized with custom templates. In this case, the $mdToast service can use a custom HTML template by using the md-toast directive.

    Theming

    Material Design is a visual language where themes convey meaning through color, tones, and contrast. These themes are expressed throughout the components in the entire application to provide a more unified feel.

    According to the Material Design guidelines, you must “limit your selection of colors by choosing three color hues from the primary palette and one accent color from the secondary palette.” Angular Material makes following this guideline simple by using JavaScript to configure the theme. But first, what is a palette and a hue?

    • Hue: A hue is a single color in a palette.
    • Palette: A palette is a collection of hues.

    For example, a palette would be ‘green’ and a hue is a particular shade of green. Angular Material comes packaged with all of the valid palettes from the Material Design spec. You can learn about more about the valid color palettes here.

    Configuring the Theme

    Theming your project is a piece of cake. In the app.js file, set your desired palettes and hues using the Theming Provider service.

    angular.module('myApp', ['ngMaterial'])
    .config(function($mdThemingProvider) {
      $mdThemingProvider.theme('default')
        .primaryPalette(‘cyan’, {
          'default': '400',
          'hue-1': '100',
          'hue-2': '600',
          'hue-3': 'A100'
        })
        .accentPalette('amber')
        .warnPalette('red')
        .backgroundPalette('grey');
    });
    

    Using the Theme

    To apply the theme to the components, set the class of the element to the desired palette and hue.

    <md-button class="md-primary">Click me</md-button>
    <md-button class="md-primary md-hue-1">Click me</md-button>
    <md-button class="md-primary md-hue-2">Click me</md-button>
    <md-button class="md-accent">or maybe me</md-button>
    <md-button class="md-warn">Careful</md-button>
    

    Layout

    Flexbox is the latest and greatest addition to responsive design and Angular Material comes packaged with it. If you are familiar with the Bootstrap grid system, then you should be able to catch on quickly. In fact, Bootstrap is switching to Flexbox in its upcoming release. It has the familiar rows and columns layout you have become accustomed to, but with much more. Learn how to use Flexbox with this tutorial or study theofficial documentation.

    Top 9 Best Angular Material Directives

    There are too many Angular Material directives to list them all, so I would like to share with you my favorites.

    9. Progress Linear

    Often in SPAs, pages need time to load data from the server. If the application shows a blank page during this time, users may think the application is broken and will leave. Let users know the data is loading with theProgress Linear directive. Users will know to wait when they see an animated progress bar indicating that something is happening. Alternatively, use the Progress Circular directive for a round indicator.

    8. Date Picker

    The Date Picker directive makes choosing a date a clean, simple experience for the user and a true one-liner to write. Simply use md-datepicker and optionally confine the range with md-min-date and md-max-date and that’s it.

    7. Autocomplete

    Autocomplete provides a pleasant user experience by helping the user choose an option. It is what makes Google’s search engine the best. The Autocomplete directive adds this functionality to your application by completing a user’s words as they type. But the best part about this directive is customization. By filling your autocomplete with md-item-template you can give more meaning to the suggestions. For instance, if a user was searching for names in a company, the autocomplete could show the matching names with their picture and company role, giving a more robust user experience.

    6. Bottom Sheet

    The bottom sheet is a little menu that slides up from the bottom of your screen, covering content and taking focus. Originally intended to be used solely for mobile devices, the bottom sheet has been gaining popularity on larger screens. To use it, create a template with md-bottom-sheet containing either an md-grid or an md-list for a grid layout or list layout, respectively. Then call it with the Bottom Sheet service, $mdBottomSheet.show().

    5. Input

    Input forms are boring and have been since the beginning of the internet. But they don’t have to be! Give yourinputs some flair with the Input directive. Wrap your input tag with md-input-container and watch it come to life. Watch as your placeholder animates into a floating label. Easily validate your input with instant, but subtle, color changes and warning messages. Input directive takes an element that is expected to be boring and delivers a pleasant surprise.

    4. Toast

    The most aggravating user experience is not knowing what the application is doing. We ease this aggravation with toasters, or little unobtrusive notifications. In the olden days, when we sent a request to the server we waited on that page until the response came back before we could move on. User attention span has dropped drastically since then. In today’s SPAs, we click a button and expect to move along immediately, dealing with the server response when it comes. The Toast directive makes this a piece of cake. A toaster is summoned by simply using the Toast Service, $mdToast.show(), and setting the text, duration, and which corner to appear in. Make your own custom toaster with md-toast.

    3. Grid List

    Are your lists lacking pizazz? Grid lists are an alternative to standard list views. A grid list is best for presenting images, and is optimized for visual comprehension. It works by laying different sized tiles on a grid, giving a scattered, eclectic feel. The tile size and layout then respond to the screen size. This directive is sure to give your application an exciting and fun look.

    2. Whiteframe

    The concept of space is the core of Material Design and its paper metaphor. Two sheets of paper in the same z-position (or depth), form a seam and must move together. Two overlapping sheets of paper, with different z-positions, form a step. They move independently of each other. To follow the design, we must be able to shift elements along the z-axis. Angular Material provides a simple way to do this. Using the Whiteframe directive, set the class to md-whiteframe-z{x}, where x is the units of depth up from the background. The larger the number, the larger the shadow cast by the paper.

    1. Sidenav

    Creating a side navigation menu has never been easier. The Sidenav directive places a navigation menu on either the left or right of the screen. Keeping mobile in mind, it swipes in and out as expected, or programmatically with a button click. A nice addition is the lock open feature. The side navigation can be set to lock open when the screen reaches a certain size. By setting the parameter md-is-locked-open=”$mdMedia(‘gt-sm’)” the menu will be tucked away on the phone but locked open on tablet and larger.

    Conclusion

    Google is converting their most popular applications to Material Design. Now they are heading the development of Angular Material, an implementation of Material Design written in AngularJS. Material Design uses a paper metaphor, bold intentions, and meaningful motion. AngularJS organizes single page applications. Angular Material applies Material Design principles to AngularJS applications.
    Material Design is here and Angular Material is a fantastic way to apply the Material design spec to your single page applications. If you want to create your own Angular Material application, don’t waste your time starting from scratch. Rather, start off with a fully functioning app with demos of the directives, theming already set up, and navigation and routing ready to go. Take a look at the demo here or fork the code on GitHub. Of course, you can also learn all about Angular Material by visiting the official documentation.
    What do you think about my picks for the best Angular Material directives? Did I get them right? What are your favorites?
    Source: Toptal

  • How Sequel and Sinatra Solve Ruby’s API Problem

    How Sequel and Sinatra Solve Ruby’s API Problem

    Introduction

    In recent years, the number of JavaScript single page application frameworks and mobile applications has increased substantially. This imposes a correspondingly increased demand for server-side APIs. With Ruby on Rails being one of the today’s most popular web development frameworks, it is a natural choice among many developers for creating back-end API applications.
    Yet while the Ruby on Rails architectural paradigm makes it quite easy to create back-end API applications, using Rails only for the API is overkill. In fact, it’s overkill to the point that even the Rails team has recognized this and has therefore introduced a new API-only mode in version 5. With this new feature in Ruby on Rails, creating API-only applications in Rails became an even easier and more viable option.
    But there are other options too. The most notable are two very mature and powerful gems, which in combination provide powerful tools for creating server-side APIs. They are Sinatra and Sequel.
    Both of these gems have a very rich feature set: Sinatra serves as the domain specific language (DSL) for web applications, and Sequel serves as the object-relational mapping (ORM) layer. So, let’s take a brief look at each of them.
    API With Sinatra and Sequel: Ruby Tutorial

    Ruby API on a diet: introducing Sequel and Sinatra.

    Sinatra

    Sinatra is Rack-based web application framework. The Rack is a well known Ruby web server interface. It is used by many frameworks, like Ruby on Rails, for example, and supports lot of web servers, like WEBrick, Thin, or Puma. Sinatra provides a minimal interface for writing web applications in Ruby, and one of its most compelling features is support for middleware components. These components lie between the application and the web server, and can monitor and manipulate requests and responses.
    For utilizing this Rack feature, Sinatra defines internal DSL for creating web applications. Its philosophy is very simple: Routes are represented by HTTP methods, followed by a route matching a pattern. A Ruby block within which request is processed and the response is formed.

    get '/' do
      'Hello from sinatra'
    end
    

    The route matching pattern can also include a named parameter. When route block is executed, a parameter value is passed to the block through the params variable.

    get '/players/:sport_id' do
      # Parameter value accessible through params[:sport_id]
    end
    

    Matching patterns can use splat operator * which makes parameter values available through params[:splat].

    get '/players/*/:year' do
      # /players/performances/2016
      # Parameters - params['splat'] -> ['performances'], params[:year] -> 2016
    end
    

    This is not the end of Sinatra’s possibilities related to route matching. It can use more complex matching logic through regular expressions, as well as custom matchers.
    Sinatra understands all of the standard HTTP verbs needed for creating a REST API: Get, Post, Put, Patch, Delete, and Options. Route priorities are determined by the order in which they are defined, and the first route that matches a request is the one that serves that request.
    Sinatra applications can be written in two ways; using classical or modular style. The main difference between them is that, with the classical style, we can have only one Sinatra application per Ruby process. Other differences are minor enough that, in most cases, they can be ignored, and the default settings can be used.

    Classical Approach

    Implementing classical application is straightforward. We just have to load Sinatra and implement route handlers:

    require 'sinatra'
    get '/' do
      'Hello from Sinatra'
    end
    

    By saving this code to demo_api_classic.rb file, we can start the application directly by executing the following command:

    ruby demo_api_classic.rb
    

    However, if the application is to be deployed with Rack handlers, like Passenger, it is better to start it with the Rack configuration config.ru file.

    require './demo_api_classic'
    run Sinatra::Application
    

    With the config.ru file in place, the application is started with the following command:

    rackup config.ru
    

    Modular Approach

    Modular Sinatra applications are created by subclassing either Sinatra::Base or Sinatra::Application:

    require 'sinatra'
    class DemoApi < Sinatra::Application
      # Application code
      run! if app_file == $0
    end
    

    The statement beginning with run! is used for starting the application directly, with ruby demo_api.rb, just as with the classical application. On the other hand, if the application is to be deployed with Rack, the handlers content of rackup.ru must be:

    require './demo_api'
    run DemoApi
    

    Sequel

    Sequel is the second tool in this set. In contrast to ActiveRecord, which is part of the Ruby on Rails, Sequel’s dependencies are very small. At the same time, it is quite feature rich and can be used for all kinds of database manipulation tasks. With its simple domain specific language, Sequel relieves the developer from all the problems with maintaining connections, constructing SQL queries, fetching data from (and sending data back to) the database.
    For example, establishing a connection with the database is very simple:

    DB = Sequel.connect(adapter: :postgres, database: 'my_db', host: 'localhost', user: 'db_user')
    

    The connect method returns a database object, in this case, Sequel::Postgres::Database, which can be further used to execute raw SQL.

    DB['select count(*) from players']
    

    Alternatively, to create a new dataset object:

    DB[:players]
    

    Both of these statements create a dataset object, which is a basic Sequel entity.
    One of the most important Sequel dataset features is that it does not execute queries immediately. This makes it possible to store datasets for later use and, in most cases, to chain them.

    users = DB[:players].where(sport: 'tennis')
    

    So, if a dataset does not hit the database immediately, the question is, when does it? Sequel executes SQL on the database when so-called “executable methods” are used. These methods are, to name a few, all, each,map, first, and last.
    Sequel is extensible, and its extensibility is a result of a fundamental architectural decision to build a small core complemented with a plugin system. Features are easily added through plugins which are, actually, Ruby modules. The most important plugin is the Model plugin. It is an empty plugin which does not define any class or instance methods by itself. Instead, it includes other plugins (submodules) which define a class, instance or model dataset methods. The Model plugin enables the use of Sequel as the object-relational-mapping (ORM) tool and is often referred to as the “base plugin”.

    class Player < Sequel::Model
    end
    

    The Sequel model automatically parses the database schema and sets up all necessary accessor methods for all columns. It assumes that table name is plural and is an underscored version of the model name. In case there is a need to work with databases that do not follow this naming convention, the table name can be explicitly set when the model is defined.

    class Player < Sequel::Model(:player)
    end
    

    So, we now have everything we need to start building the back-end API.

    Building the API

    Code Structure

    Contrary to Rails, Sinatra does not impose any project structure. However, since it is always a good practice to organize code for easier maintenance and development, we’ll do it here too, with the following directory structure:

    project root
       |-config
       |-helpers
       |-models
       |-routes
    

    The application configuration will be loaded from the YAML configuration file for the current environment with:

    Sinatra::Application.config_file File.join(File.dirname(__FILE__),
                                               'config',
                                               "#{Sinatra::Application.settings.environment}_config.yml")
    

    By default, Sinatra::Applicationsettings.environment value is development, and it is changed by setting the RACK_ENV environment variable.
    Furthermore, our application must load all files from the other three directories. We can do that easily by running:

    %w{helpers models routes}.each {|dir| Dir.glob("#{dir}/*.rb", &method(:require))}
    

    At first glance, this way of loading might look convenient. However, with this one line of the code, we cannot easily skip files, because it will load all the files from the directories in the array. That’s why we will use a more efficient single-file load approach, which assumes that in each folder we have a manifest file init.rb, which loads all other files from the directory. Also, we will add a target directory to the Ruby load path:

    %w{helpers models routes}.each do |dir|
      $LOAD_PATH << File.expand_path('.', File.join(File.dirname(__FILE__), dir))
      require File.join(dir, 'init')
    end
    

    This approach requires a bit more work because we have to maintain require statements in each init.rb file but, in return, we get more control, and we can easily leave one or more files out by removing them from the manifest init.rb file in the target directory.

    API Authentication

    The first thing we need in each API is authentication. We will implement it as a helper module. Complete authentication logic will be in the helpers/authentication.rb file.

    require 'multi_json'
    module Sinatra
      module Authentication
        def authenticate!
          client_id = request['client_id']
          client_secret = request['client_secret']
          # Authenticate client here
          halt 401, MultiJson.dump({message: "You are not authorized to access this resource"}) unless authenticated?
        end
        def current_client
          @current_client
        end
        def authenticated?
          !current_client.nil?
        end
      end
      helpers Authentication
    end
    

    All we have to do now is to load this file by adding a require statement in the helper manifest file (helpers/init.rb) and to call the authenticate! method in Sinatra’s before hook which will be executed before processing any request.

    before do
      authenticate!
    end
    

    Database

    Next, we have to prepare our database for the application. There are many ways to prepare the database, but since we are using Sequel, it is natural to do it by using migrators. Sequel comes with two migrator types – integer and timestamp based. Each one has its advantages and drawbacks. In our example, we decided to use the Sequel’s timestamp migrator, which requires migration files to be prefixed with a timestamp. The timestamp migrator is very flexible and can accept various timestamp formats, but we will only use the one that consists of year, month, day, hour, minute, and second. Here are our two migration files:

    # db/migrations/20160710094000_sports.rb
    Sequel.migration do
      change do
        create_table(:sports) do
          primary_key :id
          String :name, :null => false
        end
      end
    end
    # db/migrations/20160710094100_players.rb
    Sequel.migration do
      change do
        create_table(:players) do
          primary_key :id
          String :name, :null => false
          foreign_key :sport_id, :sports
        end
      end
    end
    

    We are now ready to create a database with all the tables.

    bundle exec sequel -m db/migrations sqlite://db/development.sqlite3
    

    Finally, we have the model files sport.rb and player.rb in the models directory.

    # models/sport.rb
    class Sport < Sequel::Model
      one_to_many :players
      def to_api
        {
          id: id,
          name: name
        }
      end
    end
    # models/player.rb
    class Player < Sequel::Model
      many_to_one :sport
      def to_api
        {
          id: id,
          name: name,
          sport_id: sport_id
        }
      end
    end
    

    Here we are employing a Sequel way of defining model relationships, where the Sport object has many players and Player can have only one sport. Also, each model defines its to_api method, which returns a hash with attributes that need to be serialized. This is a general approach we can use for various formats. However, if we will only use a JSON format in our API, we could use Ruby’s to_json with only argument to restrict serialization to required attributes, i.e. player.to_json(only: [:id, :name, :sport_i]). Of course, we could also define a BaseModel that inherits from Sequel::Model and defines a default to_api method, from which inherit all models could then inherit.
    Now, we can start implementing the actual API endpoints.

    API Endpoints

    We will keep the definition of all endpoints in files within the routes directory. Since we are using manifest files for loading files, we will group routes by resources (i.e., keep all sports related routes in sports.rb file, all players routes in routes.rb, and so on).

    # routes/sports.rb
    class DemoApi < Sinatra::Application
      get "/sports/?" do
        MultiJson.dump(Sport.all.map { |s| s.to_api })
      end
      get "/sports/:id" do
        sport = Sport.where(id: params[:id]).first
        MultiJson.dump(sport ? sport.to_api : {})
      end
      get "/sports/:id/players/?" do
        sport = Sport.where(id: params[:id]).first
        MultiJson.dump(sport ? sport.players.map { |p| p.to_api } : [])
      end
    end
    # routes/players.rb
    class DemoApi < Sinatra::Application
      get "/players/?" do
        MultiJson.dump(Player.all.map { |p| s.to_api })
      end
      get "/players/:id/?" do
        player = Player.where(id: params[:id]).first
        MultiJson.dump(player ? player.to_api : {})
      end
    end
    

    Nested routes, like the one for getting all the players within one sport /sports/:id/players, can either be defined by placing them together with other routes, or by creating a separate resource file that will contain only the nested routes.
    With designated routes, the application is now ready to accept requests:

    curl -i -XGET 'https://localhost:9292/sports?client_id=<client_id>&client_secret=<client_secret>'
    

    Note that as required by the application’s authentication system defined in helpers/authentication.rb file, we are passing credentials directly in request parameters.

    Conclusion

    The principles demonstrated in this simple example application apply to any API back-end application. It is not based on the model-view-controller (MVC) architecture, yet it keeps a clear separation of responsibilities in a similar way; complete business logic is kept in model files while handling requests is done in Sinatra’s routes methods. Contrary to MVC architecture, where views are used to render responses, this application does that at the same place where it handles requests – in the routes methods. With new helper files, the application can be easily extended to send pagination or, if needed, request limits information back to the user in response headers.
    In the end, we’ve built a complete API with a very simple toolset and without losing any functionality. The limited number of dependencies helps ensure that the application loads and starts much faster, and has a much smaller memory footprint than a Rails based one would have. So, next time you start work on a new API in Ruby, consider using Sinatra and Sequel since they are very powerful tools for such a use case.
    Source: Toptal

  • Six Commandments of Good Code: Write Code that Stands the Test of Time

    Six Commandments of Good Code: Write Code that Stands the Test of Time

    Humans have only been grappling with the art and science of computer programming for roughly half a century. Compared to most arts and sciences, computer science is in many ways still just a toddler, walking into walls, tripping over its own feet, and occasionally throwing food across the table. As a consequence of its relative youth, I don’t believe we have a consensus yet on what a proper definition of “good code” is, as that definition continues to evolve. Some will say “good code” is code with 100% test coverage. Others will say it’s super fast and has a killer performance and will run acceptably on 10 year old hardware. While these are all laudable goals for software developers, however I venture to throw another target into the mix: maintainability. Specifically, “good code” is code that is easily and readily maintainable by an organization (not just by its author!) and will live for longer than just the sprint it was written in. The following are some things I’ve discovered in my career as an engineer at big companies and small, in the USA and abroad, that seem to correlate with maintainable, “good” software.

    Never settle for code that just “works.” Write superior code.

    Commandment #1: Treat Your Code the Way You Want Other’s Code to Treat You

    I’m far from the first person to write that the primary audience for your code is not the compiler/computer, but whomever next has to read, understand, maintain, and enhance the code (which will not necessarily be you 6 months from now). Any engineer worth their pay can produce code that “works”; what distinguishes a superb engineer is that they can write maintainable code efficiently that supports a business long term, and have the skill to solve problems simply and in a clear and maintainable way.
    In any programming language, it is possible to write good code or bad code. Assuming we judge a programming language by how well it facilitates writing good code (it should at least be one of the top criteria, anyway), any programming language can be “good” or “bad” depending on how it is used (or abused).
    An example of a language that by many is considered ‘clean’ and readable is Python. The language itself enforces some level of white space discipline and the built in APIs are plentiful and fairly consistent. That said, it’s possible to create unspeakable monsters. For example, one can define a class and define/redefine/undefine any and every method on that class during runtime (often referred to as monkey patching). This technique naturally leads to at best an inconsistent API and at worst an impossible to debug monster. One might naively think,”sure, but nobody does that!” Unfortunately they do, and it doesn’t take long browsing pypi before you run into substantial (and popular!) libraries that (ab)use monkey patching extensively as the core of their APIs. I recently used a networking library whose entire API changes depending on the network state of an object. Imagine, for example, calling client.connect() and sometimes getting a MethodDoesNotExist error instead of HostNotFound or NetworkUnavailable.

    Commandment #2: Good Code Is Easily Read and Understood, in Part and in Whole

    Good code is easily read and understood, in part and in whole, by others (as well as by the author in the future, trying to avoid the “Did I really write that?” syndrome).
    By “in part” I mean that, if I open up some module or function in the code, I should be able to understand what it does without having to also read the entire rest of the codebase. It should be as intuitive and self-documenting as possible.
    Code that constantly references minute details that affect behavior from other (seemingly irrelevant) portions of the codebase is like reading a book where you have to reference the footnotes or an appendix at the end of every sentence. You’d never get through the first page!
    Some other thoughts on “local” readability:

    • Well encapsulated code tends to be more readable, separating concerns at every level.
    • Names matter. Activate Thinking Fast and Slow’ssystem 2 way in which the brain forms thoughts and put some actual, careful thought into variable and method names. The few extra seconds can pay significant dividends. A well-named variable can make the code much more intuitive, whereas a poorly-named variable can lead to headfakes and confusion.
    • Cleverness is the enemy. When using fancy techniques, paradigms, or operations (such as list comprehensions or ternary operators), be careful to use them in a way that makes your code morereadable, not just shorter.
    • Consistency is a good thing. Consistency in style, both in terms of how you place braces but also in terms of operations, improves readability greatly.
    • Separation of concerns. A given project manages an innumerable number of locally important assumptions at various points in the codebase. Expose each part of the codebase to as few of those concerns as possible. Say you had a people management system where a person object may sometimes have a null last name. To somebody writing code in a page that displays person objects, that could be really awkward! And unless you maintain a handbook of “Awkward and non obvious assumptions our codebase has” (I know I don’t) your display page programmer is not going to know last names can be null and is probably going to write code with a null pointer exception in it when the last name-being null case shows up. Instead handle these cases with well thought out APIs and contracts that different pieces of your codebase use to interact with each other.

    Commandment #3: Good Code Has a Well Thought-out Layout and Architecture to Make Managing State Obvious

    State is the enemy. Why? Because it is the single most complex part of any application and needs to be dealt with very deliberately and thoughtfully. Common problems include database inconsistencies, partial UI updates where new data isn’t reflected everywhere, out of order operations, or just mind numbingly complex code with if statements and branches everywhere leading to difficult to read and even harder to maintain code. Putting state on a pedestal to be treated with great care, and being extremely consistent and deliberate with regard to how state is accessed and modified, dramatically simplifies your codebase. Some languages (Haskell for example) enforce this at a programmatic and syntactic level. You’d be amazed how much the clarity of your codebase can improve if you have libraries of pure functions that access no external state, and then a small surface area of stateful code which references the outside pure functionality.

    Commandment #4: Good Code Doesn’t Reinvent the Wheel, it Stands on the Shoulders of Giants

    Before potentially reinventing a wheel, think about how common the problem is you’re trying to solve or the function is you’re trying to perform. Somebody may have already implemented a solution you can leverage. Take the time to think about and research any such options, if appropriate and available.

    That said, a completely reasonable counter-argument is that dependencies don’t come for “free” without any downside. By using a 3rd party or open source library that adds some interesting functionality, you are making the commitment to, and becoming dependent upon, that library. That’s a big commitment; if it’s a giant library and you only need a small bit of functionality do you really want the burden of updating the whole library if you upgrade, for example, to Python 3.x? And moreover, if you encounter a bug or want to enhance the functionality, you’re either dependent on the author (or vendor) to supply the fix or enhancement, or, if it’s open source, find yourself in the position of exploring a (potentially substantial) codebase you’re completely unfamiliar with trying to fix or modify an obscure bit of functionality.
    Certainly the more well used the code you’re dependent upon is, the less likely you’ll have to invest time yourself into maintenance. The bottom line is that it’s worthwhile for you to do your own research and make your own evaluation of whether or not to include outside technology and how much maintenance that particular technology will add to your stack.
    Below are some of the more common examples of things you should probably not be reinventing in the modern age in your project (unless these ARE your projects).

    Databases

    Figure out which of CAP you need for your project, then chose the database with the right properties. Database doesn’t just mean MySQL anymore, you can chose from:

    • “Traditional” Schema’ed SQL: Postgres / MySQL / MariaDB / MemSQL / Amazon RDS, etc.
    • Key Value Stores: Redis / Memcache / Riak
    • NoSQL: MongoDB/Cassandra
    • Hosted DBs: AWS RDS / DynamoDB / AppEngine Datastore
    • Heavy lifting: Amazon MR / Hadoop (Hive/Pig) / Cloudera / Google Big Query
    • Crazy stuff: Erlang’s Mnesia, iOS’s Core Data

    Data Abstraction Layers

    You should, in most circumstances, not be writing raw queries to whatever database you happen to chose to use. More likely than not, there exists a library to sit in between the DB and your application code, separating the concerns of managing concurrent database sessions and details of the schema from your main code. At the very least, you should never have raw queries or SQL inline in the middle of your application code. Rather, wrap it in a function and centralize all the functions in a file called something really obvious (e.g., “queries.py”). A line like users = load_users(), for example, is infinitely easier to read than users = db.query(“SELECT username, foo, bar from users LIMIT 10 ORDER BY ID”). This type of centralization also makes it much easier to have consistent style in your queries, and limits the number of places to go to change the queries should the schema change.

    Other Common Libraries and Tools to Consider Leveraging

    • Queuing or Pub/Sub Services. Take your pick of AMQP providers, ZeroMQ, RabbitMQ, Amazon SQS
    • Storage. Amazon S3, Google Cloud Storage
    • Monitoring: Graphite/Hosted Graphite, AWS Cloud Watch, New Relic
    • Log Collection / Aggregation. Loggly, Splunk

    Auto Scaling

    • Auto Scaling. Heroku, AWS Beanstalk, AppEngine, AWS Opsworks, Digital Ocean

    Commandment #5: Don’t Cross the Streams!

    There are many good models for programming design, pub/sub, actors, MVC etc. Choose whichever you like best, and stick to it. Different kinds of logic dealing with different kinds of data should be physically isolated in the codebase (again, this separation of concerns concept and reducing cognitive load on the future-reader). The code which updates your UI should be physically distinct from the code that calculates what goes into the UI, for example.

    Commandment #6: When Possible, Let the Computer Do the Work

    If the compiler can catch logical errors in your code and prevent either bad behavior, bugs, or outright crashes, we absolutely should take advantage of that. Of course, some languages have compilers that make this easier than others. Haskell, for example, has a famously strict compiler that results in programmers spending most of their effort just getting code to compile. Once it compiles though, “it just works”. For those of you who’ve either never written in a strongly typed functional language this may seem ridiculous or impossible, but don’t take my word for it. Seriously, click on some of these links, it’s absolutely possible to live in a world without runtime errors. And it really is that magical.
    Admittedly, not every language has a compiler or a syntax that lends itself to much (or in some cases any!) compile-time checking. For those that don’t, take a few minutes to research what optional strictness checks you can enable in your project and evaluate if they make sense for you. A short, non-comprehensive list of some common ones I’ve used lately for languages with lenient runtimes include:

    Conclusion

    This is by no means an exhaustive or the perfect list of commandments for producing “good” (i.e., easily maintainable) code. That said, if every codebase I ever had to pick up in the future followed even half of the concepts in this list, I will have many fewer gray hairs and might even be able to add an extra 5 years on the end of my life. And I’ll certainly find work more enjoyable and less stressful.
    This article is from Toptal.