A developer’s day in life

I have meet and worked with few developers. I have always found it common theme that they are always better at there task and programming however struggle with time management, project management and client understanding. Everyone is not in this category, its a mix and a match. Let me list out few example of true stories you may be able to relate.

Stories of developer struggles:

  1. Important and urgent emails are not replied for 2 days, especially when the email is from Exec/Director who is asking for some status directly to the developer (When its a flat structure).
  2. The Client has requested for apples and he gets apples tasting like oranges. Most common reason miss understanding of requirement
  3. The projects completes on time but gets over budget, due to number of hours spend by developers.
  4. Or the worst of them all not communicating back to the team when the task is done and there are half a dozen people who are eagerly waiting for it.
  5. so on…

Before even going further and giving my 2 cents blanket advice to budding developers. Here is the principles on which it has been derived. As a developer you much be aware why principles and patterns works out best and we don’t have to reinvent the wheel again. This is a 4 quadrant principle from the book “The Seven Habits of Highly Effective People” by Stephen Covey.

four-quadrants

As such the above image is self explanatory short detail about this is given here

Quadrant 1 is what you must be doing already, because your boss or client is keeping a watch on it. Quadrant 2, honestly if you are struggling as programmer or developer. You don’t bother its not on your books at all or only occasional thought. However remember this is most important quadrant for your career. The time we are saving will be invested in here.

Lets talk about Quadrant 3, mostly likely this will be your major time consuming activity. Some ones else priority, meeting that you need not attend, overthinking and over-designing a simple programming problem, creating generic frameworks in tight deadline and so on.

And your most common friend, Quadrant 4. Checking social media feeds again and again and again. Long coffee breaks and charts, playing games on your smart phone. Checking stock price every minute, Checking on news of countries you don’t belong. Have you ever thought of switching your phone for an hour and working on a programming task. Think about it.

Now that you have got a glimpse about possible struggle and resolving principles. Lets plan a day for you. Its cannot be repeated each day however it will work like a framework to bring yourself in track. Reminder I am not Nostradamus and I don’t have a crystal ball. Use your common sense!

The framework for your EPIC day:

  1. Your day starts at 5 minutes on previous night before you sleep. You know what are the big deadlines of your project. You pick 1 big task for a day, which will take around 90 to 120 minutes to finish. You also pick 2 small task which takes 30 minutes each. So you know your must complete task for the following day.
  2. Good morning! You don’t start with your day with your emails (No-Email). You pick your first task and complete it on the basis which you decided on the previous night. If you are scared of not checking your email first thing in the morning then come 2 hours early then your regular time. So to begin with you check your email as you used to check on your normal day.
  3. Once your big task is done you will already feel more accomplished for your day and you will find you are in control.
  4. You move on to your next 2 task once the first task is complete and the only other activity you can do to bend this rule is quadrant 1 task which is like Server crashed, Application down or fire in the building.
  5. Till you complete all 3 task for the day you will not take up any quadrant 3 task. If some one ask for help or your boss interrupts. Ask politely if you can do that post lunch, since you are middle of a billable task and in a zone. Most sane bosses will understand.
  6. Once you are done will all 3 task hope fully by your first half. Check your email before you take a lunch break. Reply to all the emails which will take less than 2 minutes. There are few example listed here. This tip form the book “Getting Things Done the art of stress free productivity” by David Allen
  7. So you had your lunch and you completed your BIG 3. Already feeling like ready to go home. Note: You have not spent an single minute on Quadrant 4 activity also being able to not do it for rest of your day. Being professional and giving your employer a bang for the buck.
  8. Now is the time for finishing your Quadrant 3 activity. Ideally in a time slot of 60 minutes each. Don’t take more than 2 task mentioning you are already working on some things else. which is already in your plate. Again use common sense in case of crisis and any quadrant one task.
  9. You need to take 10 mins of your planning this will help you if you are on course with your 3 months deliverable, your monthly deliverable, weekly deliverable and all your communications and dependencies.
  10. Planning: So I would recommend you to split it like 1st and 15th of the month check your Monthly deliverable. However 1st of every 3rd month check your 3 months deliverable. Every Friday check your weekly deliverable. Rest of the days check your daily goals. If you have time left check all the gaps of your communications. Like of you are waiting for some decisions or task. send a reminder. If you have completed a task send a notification. This time should be only for planning what to do. So the actual sending of email will be coming next. This time slot is only for brain work. Make good decisions here or I like to say thinking time.
  11. Now you again go back to your email to reply to all the long emails that you will have to read and reply and planned communication you did in previous step. Remember on a good non crisis day you would have spent only 10 minutes of your time on email before you reach at this 3rd email checking event. You keep a slot of 20 minutes to reply all Quadrant 1 and Quadrant 2 email. The main is quadrant 2 email especially relationship building with your clients and boss.
  12. For those you cannot reply answer them back you will reply them by tomorrow end of the day. Then you pick them up same time tomorrow in your 30 minute slot.
  13. The most fun time slot of your day begins, You will divide it into 2 slot, the First named as AutoBot and the second as MyWisdom each one about 45 minutes.
  14. AutoBot: This will be a time where you will add automation to your developer life. You will think of ways which you will do your task faster. Few example: Increase your programming speed by adding auto complete code snippet or some command script to automate your build, unit test and dev-deployment process. We are just following Do not repeat principles in our process. The out come of this time should be towards your long term goals, Should be able to used by your organization or your future team.
  15. MyWisdom: You should spend this 45 minutes for learning some thing new. Ideally by practicing it in a code base or setting up the tool in your computer. If possible avoid consuming articles or video during this time but actually getting hands dirty and making mistakes while learning new stuff. Asking important questions which you don’r know and then learning new things.
  16. If you count till now you will add up to 7 hours. the remaining 1 hour will be taken up by a 30 min status meeting, stand-up or some other meetings. The remaining 30 minutes will be taken up by context switching. Also quadrant 1 task can come up any time.
  17. Happy programming!

 

1 ) Scenarios for common anti patterns

2 ) Puzzle to choose which is right and wrong when you have to choose between two task

 

Open letter to Business Analyst

Business Analyst plays a very important role in the entire cross functional agile team. They are the more real truth about the requirement of the business to software developers. Since Business Analyst have seen much software being build and broken over the years they develop a strong skill on how the solution works. They are very much aware of the overall flow of the software or High Level Architecture. An experienced Business Analyst in a team with senior developer and junior developer. It is natural that they with experience start captaining the project. Also there can be a deliberation and debate over the logic of the requirement, thus putting out all possible input conditions. There is nothing wrong about it but when you are not a part of everyday coding. It doesn’t make any sense to decide on what will be the table names, will the logic reside on database or code level. It should be the job of developer. Definitely all suggestions are welcome, however you cannot dictate terms.

Here are my reasons why it should be a job of developer to do the detail decision:

  1. Developer has their own design challenges to deal with. All the decisions are taken based on the requirements provided by Business Analyst.
  2. There are underlying coding style or design choices which a developer is comfortable with. This will help them in long term maintenance of the project. Also there can be multiple solutions to a particular problem.
  3. The design of procedural programming will be difficult to adapt in object oriented programmer or functional programming.
  4. The performance issues of 1999 i.e. of memory and latency is no longer valid on today’s day and age.
  5. In memory functional programming helps parallelism easier than last decade.

This is just a rant and my humble way to put few points forward.

Happy Software Development!

1 Free & Easy tool to track your social media referrals

Recently one of my friend asked me below mentioned question.

How can I track how many clicked the referral link via my Instagram bio?

I wondered there should be an easy way without setting up your website and manage it via google analytics. It was a quick search and easy use. The answer is use bitly.com and its Free.

The use case explained below, Say you have an Instagram account and you are promoting a brand. For example purpose you are promoting www.nike.com

Login to bitly via your Facebook or Twitter account. You can also create a new signup. I created a new signup. Once you login you will see below screen. Bitly

Next you click on top right orange button Create Bitlink. You will see the screen below. First you paste the long link of your referral in the box which says “PASTE LONG URL”. Example: www.nike.com  Click on create button on the bottom of the page.

CreateLink

You will moved to another page displayed on the right side EDIT BITLINK. On Edit page update the “TITLE” box as some meaningful name – Instagram (Any social media site you want to track the source from). Then click Save.

SaveLink

That’s it. You are done. Your link is ready for tracking. See below.

ViewStats

Now it is time to test. Copy the link and paste it into your Instagram bio. I tested it for my site and below is the result on your dashboard.

CountClicks

The same with full screen and additional dashboard information for multiple links.

CountClicks_FullPage

If you have any further question add it on the comments below. I will try to answer them.

Happy Tracking!!!

How to search for quality remote work?

time-hop-holiday

Remote working is something which is gaining traction across the global. The trend of growing tech entrepreneurship and individual professional. Made the increase in demand of co-working place. There are company who have remote work options like wordpress.com, basecamp.com and upworthy.com. There are portal which cater only remote working jobs. Also there is a who book written about remote working called “remote” by the team at Basecamp. Below are the few location where you can find good quality remote work.

Places you can search for remote work:

  1. http://stackoverflow.com/jobs : Want to work remotely? The top developer website in the world has something to offer you.
  2. https://www.toptal.com/careers : Top quality technical freelancer. Why 3%? As a network, we have a very rigorous screening process to identify the best. We are experts in our domains, and we look for great problem solvers with passion and drive — the types of people we want to work with (and learn from) ourselves. Of the thousands of applications Toptal sees each month, typically fewer than 3% are accepted.
  3. https://weworkremotely.com/ : We Work Remotely is the best place to find and list jobs that aren’t restricted by commutes or a particular geographic area. Find the most qualified people in the most unexpected places

Here are few links that talk about the companies that offer remote work and there are more than 100 companies

  1. Remote
  2. These 7 amazing companies let you work remotely from anywhere
  3. 100 top companies with work from home jobs

Having given all this information there is an article about “How to Work Remotely and Still Be the Best” It covers following topics:

  1. The Remote or Home Office Setup
  2. Software Tools
  3. Remote Work Best Practices: Bug Tracking
  4. Remote Work Best Practices: Team Communication
  5. Making Your Presence Felt: Don’t Go Invisible

Details can be read here @ https://www.toptal.com/freelance/how-to-work-remotely-and-still-be-the-best

Happy Remote working

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.

Original post @ https://www.toptal.com/angular-js/ultra-modern-web-apps-angular-material

What is Bootstrap? A Short Bootstrap Tutorial on the What, Why, and How

 

 

If you’re doing anything web related, chances are you’ve heard about Bootstrap. If by now you still don’t know what Bootstrap is, or you just want to find a bootstrap tutorial for beginners to get a better overview of what it is and what it does best, you’ve come to the right place.

Bootstrap is a powerful toolkit – a collection of HTML, CSS, and JavaScript tools for creating and building web pages and web applications. It is a free and open source project, hosted on GitHub, and originally created by (and for) Twitter.

After its open source release in 2011, Bootstrap became popular very quickly, and not without reason. Web designers and web developers like Bootstrap because it is flexible and easy to work with. Its main advantages are that it is responsive by design, it maintains wide browser compatibility, it offers consistent design by using re-usable components, and it is very easy to use and quick to learn. It offers rich extensibility using JavaScript, coming with built-in support for jQuery plugins and a programmatic JavaScript API. Bootstrap can be used with any IDE or editor, and any server side technology and language, from ASP.NET to PHP to Ruby on Rails.

With Bootstrap, web developers can concentrate on the development work, without worrying about design, and get a good looking website up and running quickly. Conversely, it gives web designers a solid foundation for creating interesting Bootstrap themes.

Getting Started with this Bootstrap Tutorial

Bootstrap is available in two forms; as a precompiled version, and as a source code version. The source code version uses the Less CSS preprocessor, but if you are more into Sass, there is an official Sass port of Bootstrap also available. To make it easier to make use of CSS vendor prefixes, Bootstrap uses Autoprefixer.

The source code version comes styles source code written in Less (or Sass), all the JavaScript, and accompanying documentation. This allows more ambitious designers and developers to change and customize, at their will, all the provided styles, and to build their own version of Bootstrap. But if you are not familiar with Less (or Sass), or you are just not interested in changing the source code, don’t worry. You can just use the precompiled vanilla CSS. All the styles can be overridden later by using custom styles.

File Structure

We’ll focus on the precompiled version, which can be downloaded here. When you download the zip archive and uncompress it, the basic file structure looks like this:

bootstrap/
├── css/
│   ├── bootstrap.css
│   ├── bootstrap.css.map
│   ├── bootstrap.min.css
│   ├── bootstrap-theme.css
│   ├── bootstrap-theme.css.map
│   └── bootstrap-theme.min.css
├── js/
│   ├── bootstrap.js
│   └── bootstrap.min.js
└── fonts/
    ├── glyphicons-halflings-regular.eot
    ├── glyphicons-halflings-regular.svg
    ├── glyphicons-halflings-regular.ttf
    ├── glyphicons-halflings-regular.woff
    └── glyphicons-halflings-regular.woff2

The Bootstrap structure is pretty simple and self-explanatory. It includes precompiled files that enable quick usage in any web project. Besides compiled and minified CSS and JS files, it also includes fonts fromGlyphicons, and the optional starting Bootstrap theme.

This structure can be easily incorporated in your own project’s file structure by just including the Bootstrap files exactly as they come out of the zip archive, or if it suits your project better, you can rearrange these files and place them anywhere you like. Just be sure that the Glyphicons fonts folder is on the same level as the CSS folder.

Basic HTML Template

A basic Bootstrap HTML template should look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap Template</title>
    <link href="css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <h1>Hello, world!</h1>
    https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
    http://js/bootstrap.min.js
  </body>
</html>

It is important to start any HTML with a HTML 5 Doctype declaration, so that browsers know what kind of a document they can expect. The head contains three important <meta> tags that must be declared first, and any additional head tags must be added after these. If you want to support older browsers like IE8, you can also include HTML 5 shim in the head, which will enable use of HTML5 elements in older browsers, andRespond.js, that will polyfill CSS3 Media Queries, in the old versions of Internet Explorer.

<head>
  ...
  <!--[if lt IE 9]>
    https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js
    https://oss.maxcdn.com/respond/1.4.2/respond.min.js
  <![endif]-->
</head>

Although this is not very important if you are targeting only modern browsers.

JavaScript files are added to the end of the body to allow the web page to load visibly before any JavaScript is executed. jQuery is needed for Bootstrap plugins, and needs to load before bootstrap.js. If you aren’t using any of Bootstrap’s interactive features, you can also omit these files from the source.

This is the bare minimum that is needed to get a basic Bootstrap layout up and running. If you’re a developer, you’ll probably want to take a look at some more advanced examples at Bootstrap’s examples page. If you’re a designer, or just looking for inspiration, Bootstrap Expo showcases sites that are built using Bootstrap. As we’ll see later, every part of Bootstrap can be easily customized in CSS. But if that’s not your thing, and you are looking for a slightly different look and feel from the prepackaged Bootstrap themes, there are a lot of free, open source and premium themes available from sources like Bootswatch and WrapBootstrap.

Components

Bootstrap comes bundled with basic HTML and CSS design templates that include many common UI components. These include Typography, Tables, Forms, Buttons, Glyphicons, Dropdowns, Buttons and Input Groups, Navigation, Pagination, Labels and Badges, Alerts, Progress Bars, Modals, Tabs, Accordions, Carousels, and many others. Many of these use JavaScript extensions and jQuery plugins.

These templates are made available as well-factored CSS classes that you can apply to your HTML to achieve different effects. This makes using Bootstrap very convenient. By using semantic class names like .success, .warning and .info, these components are easily reusable and extensible. But while Bootstrap uses descriptive class names that have meaning, it isn’t specific about implementation details. All classes can be overridden with custom CSS style and color, and still the meaning of the class will stay the same.

Grids

Before we dive more into Bootstrap components and design templates, it is important to mention one of the major features that Bootstrap introduced in version 3: a mobile-first design philosophy, which resulted in a Bootstrap that is responsive by design. The end result is that Bootstrap easily and efficiently scales with a single code base, from phones, through tablets, to desktops.

This responsiveness is achieved using a fluid grid system that can be applied to appropriately scale up to 12 columns according to the size of the device or viewport. Grids provide structure to the layout, defining the horizontal and vertical guidelines for arranging content and enforcing margins. Grids also offer an intuitive structure for viewers, because it’s easy to follow a left to right, or a right to left flow of content moving down the page. Before grids, and before CSS was so powerful, grid based layouts were achieved by using tables, where the content would be arranged inside table cells. As CSS became more mature, a number of CSS frameworks for grid-based layouts started to appear. These include YUI grids, 960 GS and blueprint, to name a few.

To use the Bootstrap grid system, a few rules need to be followed. Grid column elements are placed inside row elements, which create horizontal groups of columns. You can have as many rows as you want on the page, but columns must be immediate children of rows. In a full row, the column widths will be any combination that adds up to 12, but it is not mandatory to use all 12 available columns.

Rows need to be placed either in a fixed-width layout wrapper, which has a .container class and a width of 1170px, or in full-width layout wrapper, which has a .container-fluid class, and which enables the responsive behavior in that row.

The Bootstrap grid system has four tiers of classes: xs for phones (<768px), sm for tablets (≥768px), md for desktops (≥992px), and lg for larger desktops (≥1200px). These basically define the sizes at which the columns will collapse or spread horizontally. The class tiers can be used in any combination to get dynamic and flexible layouts.

Bootstrap on desktop and mobile

It is possible to disable page responsiveness completely. This will basically disable the “mobile site” aspects of Bootstrap. Just keep in mind that if you disable responsiveness, any fixed-width component, such as a fixed navbar, will not be visible when the viewport becomes narrower than the page content. For a non-responsive container, that means a width of 970px. Also in this case, navbars won’t collapse in mobile views as described later.

These are just basic examples. To see the full potential of the grids, check out Bootstrap’s Grids documentation.

Typography

Beginning developers often assume their pure and un-styled HTML will look the same across all browsers. Unfortunately, every browser has its own default “user agent” style sheet that is applied to the HTML, and no two browsers have the same defaults. For example, heading font sizes are not consistent across browsers, some unordered and ordered lists have left margins and others have left padding, browsers apply custom borders and padding to the HTML body, and even buttons are rendered differently across browsers. To solve all these inconsistencies, different CSS “reset” rules were born that define consistent style defaults.

Bootstrap brings some more goodies to table besides pure CSS reset. It comes with normalize.css, an HTML5-ready alternative to CSS resets, and it also has some well-designed defaults of its own. For example, Bootstrap sets the global default font-size to 14px, with a line-height of 1.428. The default font is changed to Helvetica/Arial, with sans serif fallback. All these styles are applied to the <body> and all paragraphs, with the addition that <p> (paragraphs) receive a bottom margin of half their computed line-height (10px by default). Besides these defaults, there are also customizable styles for standard HTML tags that bring more consistency to the text, such as highlighted text (<mark>), deleted text (<del> and <s>), underlined text (<u>), small text (<small>), and bold text (<strong>). Alignment classes help to arrange content on the page more easily by using .text-left, .text-center, .text-right, .text-justify and .text-nowrap classes. There are also predefined styles for block quotes, and unordered and ordered list, with inline options, just to name a few. To get a full list, head to the Bootstrap Typography page.

One interesting thing that Bootstrap also makes possible is that you can use, for example, heading styles by using either the <h1> tag, or the .h1 class. The latter will match the styling of the <h1> heading, but will allow the text to be displayed inline.

Forms

Forms have come a long way over the years, and today using a web form is one of the most common activities performed while browsing the web. While HTML5 introduced a number of new form attributes, input types, and other helper elements, browsers haven’t visually improved forms much. This is one area where Bootstrap really shines, because aligning and styling labels and inputs, validating forms, and showing error messages, can be tricky without some help.

First, Bootstrap sets all textual input elements, like <input>, <textarea>, and <select>, to 100% width of the parent form element. It also gives you the ability to choose between inline forms, which will render multiple labels and input fields in the same line, by using the .form-inline class, or horizontal forms, which use grids to align each input in its own row, by using the .form-horizontal class. And if you need to place plain text next to a form label, instead of the input field, you can give it the .form-control-static class to make it match the visual look of the form.

Maybe the greatest feature that Bootstrap brings to forms is validation styles for error, warning, and success states. These can be applied using the .has-warning, .has-error, and .has-success classes, respectively. Combining this with icons that can be placed inside the input forms, we can get quick and effective form validation effects, even without using any error text message.

 

Again, we have only scratched the surface here. For more examples, take a look at Bootstrap’s Forms documentation.

Images and Icons

Images in Bootstrap can be made responsive by simply giving them the .img-responsive class. This will apply max-width:100%; height:auto; and display:block; to the image in question, so that it scales to the parent element.

Besides making images responsive, we can easily add different effects. For example, rounded corners are applied with the .img-rounded class, and the image can be shaped to be a circle by using .img-circle, or to a thumbnail by using .img-thumbnail class.

Bootstrap comes bundled with over 260 glyphs in font format, from the Glyphicons Halflings set. Jan Kovařík, author and designer of Glyphicons, has made them available for Bootstrap for free and under the same license as Bootstrap, which is awesome. Font icons have many advantages over plain raster images, a big one being that they are scalable. They can also easily be customized using just CSS, so manipulating size or color, or even adding a drop a shadow, is a breeze.

Buttons, Button Groups, and Button Dropdowns

Buttons are one of the things every browser renders totally differently. If you want to have consistent design across all browsers, this is potentially a big problem. Luckily, Bootstrap has an elegant solution for buttonsalso. And besides making them consistent, it brings a lot of variations to play with. You can apply the .btnclass to <a> and <input> elements. You can group a series of buttons together into a single line using the .btn-group class on the parent <div>. With a little help from JavaScript, you can create radio- and checkbox- style behavior on buttons. Or you can turn your buttons into dropdown menus by placing it within a .btn-group, and providing the proper menu markup of unordered list of items.

The navigational bar, or navbar, is a Bootstrap component designed specifically to build the primary navigation menu of the website. On big screens, it is displayed horizontally, and on small and mobile screens (those below 768px), it transformed into a “hamburger” dropdown menu. Under the hood, navbar is an unordered inline list of menu items, with additional HTML elements that are added as desired. Among the possible additions are branding (either text or logo), form items such as a search bar, and menu dropdowns. Two styles are available to choose from out-of-the-box: light and dark, inverted. Items in the navbar can be aligned left or right by applying .navbar-left or .navbar-right classes, respectively.

Navbars can have 4 different position behaviors. The default float position has buffer space around it; the full-width static navbar scrolls away when the user scrolls down the page, and the fixed navbar, which can be either on the top or the bottom of the window, is always visible on the page, no matter where the user has scrolled to.

Bootstrap navbars

Conclusion

This covers only a few of the great Bootstrap components that puts Bootstrap ahead of similar frameworks, libraries, and toolkits. With Bootstrap, just a few simple CSS classes are all it takes to build a fully responsive and beautiful front end, fast and easily. It’s a great starting point for your next big project or startup.

Full Original post @ https://www.toptal.com/front-end/what-is-bootstrap-a-short-tutorial-on-the-what-why-and-how

Clean Code and The Art of Exception Handling

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

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

And that handling them requires:

specialized programming language constructs or computer hardware mechanisms.

So, exceptions require special treatment, and an unhandled exception may cause unexpected behavior. The results are often spectacular. In 1996, the famous Ariane 5 rocket launch failure was attributed to an unhandled overflow exception. History’s Worst Software Bugs contains some other bugs that could be attributed to unhandled or miss-handled exceptions.

Over time, these errors, and countless others (that were, perhaps, not as dramatic, but still catastrophic for those involved) contributed to the impression that exceptions are bad.

The results of improperly handling exceptions have led us to believe that exceptions are always bad.

But exceptions are a fundamental element of modern programming; they exist to make our software better. Rather than fearing exceptions, we should embrace them and learn how to benefit from them. In this article, we will discuss how to manage exceptions elegantly, and use them to write clean code that is more maintainable.

Exception Handling: It’s a Good Thing

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

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

There is nothing wrong with the previous code. But overusing these patterns will cause code smells, and won’t necessarily be beneficial. Likewise, misusing them can actually do a lot of harm to your code base, making it brittle, or obfuscating the cause of errors.

The stigma surrounding exceptions often makes programmers feel at a loss. It’s a fact of life that exceptions can’t be avoided, but we are often taught they must be dealt with swiftly and decisively. As we will see, this is not necessarily true. Rather, we should learn the art of handling exceptions gracefully, making them harmonious with the rest of our code.

Following are some recommended practices that will help you embrace exceptions and make use of them and their abilities to keep your code maintainable, extensible, and readable:

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

These elements are the main factors of what we might call cleanliness or quality, which is not a direct measure itself, but instead is the combined effect of the previous points, as demonstrated in this comic:

"WTFs/m" by Thom Holwerda, OSNews

With that said, let’s dive into these practices and see how each of them affects those three measures.

Note: We will present examples from Ruby, but all of the constructs demonstrated here have equivalents in the most common OOP languages.

Always create your own ApplicationError hierarchy

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

class ApplicationError < StandardError; end

# Validation Errors
class ValidationError < ApplicationError; end
class RequiredFieldError < ValidationError; end
class UniqueFieldError < ValidationError; end

# HTTP 4XX Response Errors
class ResponseError < ApplicationError; end
class BadRequestError < ResponseError; end
class UnauthorizedError < ResponseError; end
# ...

Example of an application exception hierarchy.

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

From the readability perspective, it’s much easier to read:

rescue ValidationError => e

Than to read:

rescue RequiredFieldError, UniqueFieldError, ... => e

From the maintainability perspective, say, for example, we are implementing a JSON API, and we have defined our own ClientError with several subtypes, to be used when a client sends a bad request. If any one of these is raised, the application should render the JSON representation of the error in its response. It will be easier to fix, or add logic, to a single block that handles ClientErrors rather than looping over each possible client error and implementing the same handler code for each. In terms of extensibility, if we later have to implement another type of client error, we can trust it will already be handled properly here.

Moreover, this does not prevent us from implementing additional special handling for specific client errors earlier in the call stack, or altering the same exception object along the way:

# app/controller/pseudo_controller.rb
def authenticate_user!
  fail AuthenticationError if token_invalid? || token_expired?
  User.find_by(authentication_token: token)
rescue AuthenticationError => e
  report_suspicious_activity if token_invalid?
  raise e
end

def show
  authenticate_user!
  show_private_stuff!(params[:id])
rescue ClientError => e
  render_error(e)
end

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

Two things to note here:

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

Never rescue Exception

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

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

# elsewhere.rb
def i_might_raise_exception!
  retrun do_a_lot_of_work!
end

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

Never rescue more exceptions than you need to

The previous point is a specific case of this rule: We should always be careful not to over-generalize our exception handlers. The reasons are the same; whenever we rescue more exceptions than we should, we end up hiding parts of the application logic from higher levels of the application, not to mention suppressing the developer’s ability to handle the exception his or herself. This severely affects the extensibility and maintainability of the code.

If we do attempt to handle different exception subtypes in the same handler, we introduce fat code blocks that have too many responsibilities. For example, if we are building a library that consumes a remote API, handling a MethodNotAllowedError (HTTP 405), is usually different from handling an UnauthorizedError (HTTP 401), even though they are both ResponseErrors.

As we will see, often there exists a different part of the application that would be better suited to handle specific exceptions in a more DRY way.

So, define the single responsibility of your class or method, and handle the bare minimum of exceptions that satisfy this responsibility requirement. For example, if a method is responsible for getting stock info from a remote a API, then it should handle exceptions that arise from getting that info only, and leave the handling of the other errors to a different method designed specifically for these responsibilities:

def get_info
  begin
    response = HTTP.get(STOCKS_URL + "#{@symbol}/info")

    fail AuthenticationError if response.code == 401
    fail StockNotFoundError, @symbol if response.code == 404
    return JSON.parse response.body
  rescue JSON::ParserError
    retry
  end
end

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

Resist the urge to handle exceptions immediately

This is the complement to the last point. An exception can be handled at any point in the call stack, and any point in the class hierarchy, so knowing exactly where to handle it can be mystifying. To solve this conundrum, many developers opt to handle any exception as soon as it arises, but investing time in thinking this through will usually result in finding a more appropriate place to handle specific exceptions.

One common pattern that we see in Rails applications (especially those that expose JSON-only APIs) is the following controller method:

# app/controllers/client_controller.rb

def create
  @client = Client.new(params[:client])
  if @client.save
    render json: @client
  else
    render json: @client.errors
  end
end

(Note that although this is not technically an exception handler, functionally, it serves the same purpose, since @client.save only returns false when it encounters an exception.)

In this case, however, repeating the same error handler in every controller action is the opposite of DRY, and damages maintainability and extensibility. Instead, we can make use of the special nature of exception propagation, and handle them only once, in the parent controller class, ApplicationController:

# app/controllers/client_controller.rb

def create
  @client = Client.create!(params[:client])
  render json: @client
end
# app/controller/application_controller.rb

rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity

def render_unprocessable_entity(e)
  render \
    json: { errors: e.record.errors },
    status: 422
end

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

Not all exceptions need handling

When developing a gem or a library, many developers will try to encapsulate the functionality and not allow any exception to propagate out of the library. But sometimes, it’s not obvious how to handle an exception until the specific application is implemented.

Let’s take ActiveRecord as an example of the ideal solution. The library provides developers with two approaches for completeness. The save method handles exceptions without propagating them, simply returning false, while save! raises an exception when it fails. This gives developers the option of handling specific error cases differently, or simply handling any failure in a general way.

But what if you don’t have the time or resources to provide such a complete implementation? In that case, if there is any uncertainty, it is best to expose the exception, and release it into the wild.

Sometimes the best way to handle an exception is to let it fly free.

Here’s why: We are working with moving requirements almost all the time, and making the decision that an exception will always be handled in a specific way might actually harm our implementation, damaging extensibility and maintainability, and potentially adding huge technical debt, especially when developing libraries.

Take the earlier example of a stock API consumer fetching stock prices. We chose to handle the incomplete and malformed response on the spot, and we chose to retry the same request again until we got a valid response. But later, the requirements might change, such that we must fall back to saved historical stock data, instead of retrying the request.

At this point, we will be forced to change the library itself, updating how this exception is handled, because the dependent projects won’t handle this exception. (How could they? It was never exposed to them before.) We will also have to inform the owners of projects that rely on our library. This might become a nightmare if there are many such projects, since they are likely to have been built on the assumption that this error will be handled in a specific way.

Now, we can see where we are heading with dependencies management. The outlook is not good. This situation happens quite often, and more often than not, it degrades the library’s usefulness, extensibility, and flexibility.

So here is the bottom line: if it is unclear how an exception should be handled, let it propagate gracefully. There are many cases where a clear place exists to handle the exception internally, but there are many other cases where exposing the exception is better. So before you opt into handling the exception, just give it a second thought. A good rule of thumb is to only insist on handling exceptions when you are interacting directly with the end-user.

Follow the convention

The implementation of Ruby, and, even more so, Rails, follows some naming conventions, such as distinguishing between method_names and method_names! with a “bang.” In Ruby, the bang indicates that the method will alter the object that invoked it, and in Rails, it means that the method will raise an exception if it fails to execute the expected behavior. Try to respect the same convention, especially if you are going to open-source your library.

If we were to write a new method! with a bang in a Rails application, we must take these conventions into account. There is nothing forcing us to raise an exception when this method fails, but by deviating from the convention, this method may mislead programmers into believing they will be given the chance to handle exceptions themselves, when, in fact, they will not.

Another Ruby convention, attributed to Jim Weirich, is to use fail to indicate method failure, and only to use raise if you are re-raising the exception.

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

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

Logger.log(everything)

This practice doesn’t solely apply to exceptions, of course, but if there’s one thing that should always be logged, it’s an exception.

Logging is extremely important (important enough for Ruby to ship a logger with its standard version). It’s the diary of our applications, and even more important than keeping a record of how our applications succeed, is logging how and when they fail.

There is no shortage of logging libraries or log-based services and design patterns. It’s critical to keep track of our exceptions so we can review what happened and investigate if something doesn’t look right. Proper log messages can point developers directly to the cause of a problem, saving them immeasurable time.

That Clean Code Confidence

Proper exception handling allows for clean code and successful software.

Clean exception handling will send your code quality to the moon!
Exceptions are a fundamental part of every programming language. They are special and extremely powerful, and we must leverage their power to elevate the quality of our code instead of exhausting ourselves fighting with them.

In this article, we dived into some good practices for structuring our exception trees and how it can be beneficial for readability and quality to logically structure them. We looked at different approaches for handling exceptions, either in one place or on multiple levels.

We saw that it’s bad to “catch ‘em all”, and that it’s ok to let them float around and bubble up.

We looked at where to handle exceptions in a DRY manner, and learned that we are not obligated to handle them when or where they first arise.

We discussed when exactly it is a good idea to handle them, when it’s a bad idea, and why, when in doubt, it’s a good idea to let them propagate.

Finally, we discussed other points that can help maximize the usefulness of exceptions, such as following conventions and logging everything.

With these basic guidelines, we can feel much more comfortable and confident dealing with error cases in our code, and making our exceptions truly exceptional!

Special thank to Avdi Grimm and his awesome talk Exceptional Ruby, which helped a lot in the making of this article.

Original Post @ https://www.toptal.com/qa/clean-code-and-the-art-of-exception-handling