Rafael Freire - Tech Blog2022-07-29T15:10:15+00:00http://rafaelcfreire.github.ioRafael Freirerafaelcfreire@gmail.comThe Books That Influenced My Career2015-06-22T00:00:00+00:00http://rafaelcfreire.github.io/2015/06/22/the-books-that-influenced-my-career
<div style="margin-bottom: 1.5em;">
<div>
<a href="https://twitter.com/share" class="twitter-share-button" style="vertical-align: bottom">Tweet</a>
</div>
<div>
<span class="fb-share-button" data-href="http://rafaelcfreire.github.io2015/06/22/the-books-that-influenced-my-career/" data-layout="button"></span>
</div>
</div>
<p>Hi everybody,</p>
<p>This is the post that I always thought to write. Actually, it should have been the first material of the blog as a kind of presenting myself but as I was reading some titles during that time I decided to finish them before write it. This text is a kind of walkthrough in my career once I believe that the books you read directly influences the quality and the maturity level of the professional. As I mentioned before I usually read a lot of books but only achieve the end of those that really arouse my curiosity and interest, there are a lot of titles that I just start and some that I don’t think I am ready in terms of knowledge or inspiration to get the details so, I postpone the read and strangely that action works for me because some of the best titles I ever read were left aside to read in a later opportunity sometime.</p>
<p>I don’t like list anything in order of relevance because it is a very subtle concept, even being a personal list it is hard to give a cardinal order for my favorite books (I have already tried do it with my vinyl records and CDs but I always forget one that cannot be missing), I will try to put them in a chronological way, from the first to the last I’ve read to give an idea of sequence so, let’s start:</p>
<p>Thanks to <a href="https://twitter.com/jsonmez">John Sonmez</a>, author of <a href="http://simpleprogrammer.com/">Simple Programmer Blog</a> and <a href="https://www.manning.com/books/soft-skills">Soft Skills: The software developer’s life manual</a> book which is on my wishlist and next book in line to be read, for inspiring me to finish this post. ;)</p>
<h3 id="java-how-to-program-6th-edition-how-to-program-deitel">Java How to Program (6th Edition) (How to Program (Deitel))</h3>
<p>This was the first programming book which I’ve read and the one that helped me to get the concepts of OO and programing in Java Ecosystem. Clearly focused to starters, the Java Deitel is an awesome resource that brings an naive example of an ATM and its evolution to a java application using Swing GUI, network API, Multithreading and the old fashioned JDBC. Even the book being really large, it is not necessary fatinguing to read althought sometimes it goes really deeper in some examples (and some recurrent and trite explanations). The extensive use of <a href="http://www.uml.org/">UML</a> to illustrate the examples is perfect to enhance the reader understanding in a visual approach. Personally, even years later from my first contact with this reading I think it still relevant for entry level developers who intend to enter the Object Oriented world and the Java language.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=0131483986&asins=0131483986&linkId=N4R26YWGNBX5F5JK&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<h3 id="head-first-design-patterns">Head First Design Patterns</h3>
<p>One of the first books that I was suggested to read when starting programming was the <cite><a href="https://books.google.com.br/books/about/Design_Patterns.html?id=6oHuKQe3TjQC&redir_esc=y">Design Patterns: Elements of Reusable Object-Oriented Software</a></cite> written by the gang of four(Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides). Every experienced software developer recommend this as a mandatory read, so I gave a try years ago…It was disappointing. I could not understand even a line, and I felt terrible because every found that book awesome except me. Design Patterns stayed as a puzzle in my head for a long time, I could not get the practical benefit of using it. Then, Some time later the company that I was working at that time bought a copy of Head First: Design Patterns. The series was completely unknown for me and my first impression was terrible once the cover has a strange image of a Gwen Stefani style girl with a brain in her side, in my mind that weird book would not be able to make me grasp the concept of Design Patterns.
But as I started to read I could not stop, a real pleasant way to assimilate all his content with a lot of images and visual examples. Every Design Pattern is exemplified in a nicely and rich in details way ensuring that the reader is absorbing the main idea of the content.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=0596007124&asins=0596007124&linkId=DE26NV7EZTZLQ2BH&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<h3 id="effective-java">Effective Java</h3>
<p>Effective Java was written by <a href="https://twitter.com/joshbloch">Joshua Bloch</a>, if you don’t know him by his name just open some core classes of the Java Language and check the name of it’s author. In this book, Joshua Bloch gives insights that will led your career to a higher level (I think that this is a mandatory read for any Java Developer who believes to be at an advanced level). Important concepts like lifecycle of objects, concurrency, serialization and inheritance are addressed in a eloquent way going straight to the point and giving examples of choices made by him during the concept of some Java’s core classes. I have used this book for more than four years as a guideline, everytime I caught in a doubt about different approaches in to solve a problem in Java, I take a look at this and impressing is that every time I open this book, I learn something new that makes me think: “How I didn’t know this?”. The chapter “Creating and Destroying Objects” deserves a special attention from the reader considering that many developers does not have any idea of how it works.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=0321356683&asins=0321356683&linkId=M3N4R7RMPU4F4LQ4&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<h3 id="data-structure-and-algorithms-in-java">Data Structure and Algorithms In Java</h3>
<p>Understanding Data Structures in essential for any developer, definitely is impossible to thrive as a Software Engineer without a good notion of this concept. This book from <a href="http://www.wiley.com/WileyCDA/Section/id-350310.html">Wiley</a> presents the topic from basics to advanced concepts smoothly, inviting the reader to think and understand the concepts behind implementations. It starts with some basic definitions like flow control, loops and a little bit of theory that can be skipped by advanced readers. But from chapter 3 ahead the book gets exciting to read starting with <a href="https://en.wikipedia.org/wiki/List_of_data_structures">List</a> (awesome explanations for <a href="https://en.wikipedia.org/wiki/Round-robin_scheduling">Circular Linked List</a> and <a href="https://en.wikipedia.org/wiki/Doubly_linked_list">Doubly Linked List</a>), then one shallow chapter dedicated to Algorithm Analysis(if you want good resources in Algorithm Analysis, a quickly search on Google can provide you better sources) and the rest of the book is dedicated to theory and useful implementations of Stacks, Trees, Queues, Maps and Sorting and Ordering Algorithms. Some time ago I created a <a href="https://github.com/rafaelcfreire/Java-Algorithms">GitHub Repository</a> to implement the algorithms represented in this book, unfortunatelly I having a lack of time to finish it. If you enjoy the idea, feel free to fork and help to implement them. In a near future, I will be implementing them in Ruby to demonstrate the ease of legibility of this book for those that aren’t familiar with Java.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=1118771338&asins=1118771338&linkId=CSVQK4VIQH64NLQ2&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<!--
### Structure and Interpretation of Computer Programs
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon®ion=US&placement=0262510871&asins=0262510871&linkId=LKFRCQGPXD2DJPGW&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<!-- <a href="https://mitpress.mit.edu/sicp/full-text/book/book.html">Structure and Interpretation of Computer Programs</a>
### 97 Things Every Programmer Should Know
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon®ion=US&placement=0596809484&asins=0596809484&linkId=GONC242LMENHO6XI&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
-->
<h3 id="javascript-the-good-parts">Javascript: The Good Parts</h3>
<p>The entry point in Javascript language that every developer should consider. In this book, Douglas Crockford (creator of JSON) succinctly describes what makes Javascript an awesome language for modern applications. The Javascript grammar receives a special attention in the first chapter with diagrams to help understanding the concept (Worked very well for me). Then one chapter dedicated to objects lifecycle and after the the definitive chapter of the reading: Functions. This is the chapter you should read a plenty of times during you career, write the codes and debate with others javascript developers. Things like <a href="https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Guide/Closures">Closures</a>, <a href="http://addyosmani.com/blog/faster-javascript-memoization/">Memoization</a>, <a href="http://addyosmani.com/resources/essentialjsdesignpatterns/book/">Modules</a> and <a href="http://www.crockford.com/javascript/www_svendtofte_com/code/curried_javascript/index.html">Currying</a> are extremely well introduced here. There are other relevants chapters covering inheritance (a very misunderstood concept in Javascript for those who came from OO world and very recurrent topic in hiring process of many companies) and an appendix with the bad parts of the language. There is a talk performed by Crockford in GoogleTech Talk in <a href="https://www.youtube.com/watch?v=hQVTIJBZook">Youtube</a> with some of the topics addressed in the book, if you are planning to really understand Javascript, this is the book.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=0596517742&asins=0596517742&linkId=DWRBM53RCUG77TGS&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<h3 id="the-pragmatic-programmer-from-journeyman-to-master">The Pragmatic Programmer: From Journeyman To Master</h3>
<p>This is that book you should read everytime you pass through some situations that only happens in our area like maintaining bad code, working late to put a feature in production without test, doubts about your future and so forth. Definitely a classic in our area and impossible to read and do not identificate yourself in some scenarios described here. I read it in a moment that I was really frustrated with some situations in software development, personal achievements that I was unable to do and discrepancy of what I believe to be a good development environment with what my managers think. I thought that I was completely mistaken when I started to read Pragmatic Programmer and it was tremendously helpful for me. General hints that can drive the developer to the highly productivity way are presented in a contextual manner like be less wedded to a specific technology and create a background stem to allow you to decide which best fits your problem. I copied an important definition of what makes a pragmatic programmer of the preface of the book, they are:</p>
<ul>
<li>Early adopter/fast adapter: You have an instinct for technologies and techniques, and you love trying things out. When given something new, you can grasp it quickly and integrate it with the rest of your knowledge. Your confidence is born of experience.</li>
<li>Inquisitive: You tend to ask questions. That’s neat—how did you do that? Did you have problems with that library? What’s this B e OS I’ve heard about? How are symbolic links implemented? You are a pack rat for little facts, each of which may affect some decision years from now.</li>
<li>Critical thinker. You rarely take things as given without first getting the facts. When colleagues say “because that’s the way it’s done,” or a vendor promises the solution to all your problems, you smell a challenge.</li>
<li>Realistic. You try to understand the underlying nature of each problem you face. This realism gives you a good feel for how difficult things are, and how long things will take. Understanding for yourself that a process should be difficult or will take a while to complete gives you the stamina to keep at it.</li>
<li>Jack of all trades. You try hard to be familiar with a broad range of technologies and environments, and you work to keep abreast of new developments. Although your current job may require you to be a specialist, you will always be able to move on to new areas and new challenges.</li>
</ul>
<p>This book is a inspiring source of self improvement and I definitely wish I’d have read it before.</p>
<div class="bookImages">
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecbl09-20&marketplace=amazon&region=US&placement=020161622X&asins=020161622X&linkId=4622AAPXRKREODW7&show_border=false&link_opens_in_new_window=true">
</iframe>
</div>
<script type="text/javascript" src="/js/main.js"></script>
<link rel="stylesheet" type="text/css" href="/css/styles.css" />
Useful Tools to Test the Responsiveness of Your Site2015-02-24T00:00:00+00:00http://rafaelcfreire.github.io/tips/2015/02/24/useful-tools-to-test-the-responsiveness-of-your-site
<div style="margin-bottom: 1.5em;">
<div>
<a href="https://twitter.com/share" class="twitter-share-button" style="vertical-align: bottom">Tweet</a>
</div>
<div>
<span class="fb-share-button" data-href="http://rafaelcfreire.github.io/tips/2015/02/24/useful-tools-to-test-the-responsiveness-of-your-site/" data-layout="button"></span>
</div>
</div>
<p>Hello everyone,</p>
<p>One important part of the web developer’s job nowadays is assure the responsiveness of the pages that he is creating. It is impossible to start a project which <a href="http://speckyboy.com/2013/01/17/the-evolution-of-responsive-web-design-responsivity-analysis/">responsivity analysis</a> is not a mandatory requirement, the therm <a href="http://www.uxmatters.com/mt/archives/2012/03/mobile-first-what-does-it-mean.php">Mobile First</a> is a topic that every software developer should be comfortable a exhausted discussed <a href="http://www.webinsation.com/why-should-i-design-for-mobile-first/">here</a> and <a href="http://www.wearejh.com/design/benefits-of-a-mobile-first-approach/">here</a> by instance.
But even responsive development being not exactly a new trend, responsiveness test still being a <a href="http://stream1.gifsoup.com/view/656679/pitfall-o.gif" target="_blank">challenging</a> task once is impossible for a developer (even for a company) to have all devices to perform his tests and simulate specific scenarios for each case.
In this article I’ll show the tools I normally use (does not mean that these are the best, just that I am familiar with). In my opinion, the most important factor to decide a tool amongst others is how much productive you are with it, in my case includes avoid repetitive work, prevents you wasting too much time to find their resources and to understand how it works and obviously, give a decent emulation of the device you’re aiming to.</p>
<p>I classified the tools in two sections, first those that you can use during the development time, that is, tools embedded in browsers toward get a notion of your design while it is being created, the second part consists of tools to check the overall result of your work after it has been deployed. Things like layouts, font-sizes, distances and menus are extremely sensibles for differents environments so it is really worth to exhaustly test them all in at least the most common environments.</p>
<h3 id="during-implementation">During Implementation</h3>
<p>Major moderns browsers have their ours developer tools. Although it is a embedded feature, they are highly mature with all that is needed to develop a page fully responsive together with <a href="http://www.w3schools.com/cssref/css3_pr_mediaquery.asp" target="_blank">Media Queries</a> which you can emulate different types of screen. Personally, I use <a href="https://www.google.com/chrome/browser/desktop/" target="_blank">Google Chrome</a> for development because I use some of his features such as CPU Profile, Network analysis and memory leaks (if you are not familiar with those resources in Chrome, attend the free course <a href="https://www.codeschool.com/courses/discover-devtools">Discover DevTools</a>). However, the Safari and Firefox version will be described here. Let’s see each one at a glance:</p>
<h3 id="google-chrome">Google Chrome</h3>
<p>It is very easy to emulate a device in Google Chrome, first all open the ‘Developer Tools’ in View -> Developer -> Developer Tools then you will notice a cell phone image in the upper left side of the tool bar as you can see in the image below</p>
<p><img src="/assets/added.png" alt="My helpful screenshot" /></p>
<p>After clicking on the device icon, the page turns to a mobile mode where you can select the device model to emulate specific scenarios and both rotation to portrair or landscape. One nice feature in Chrome is the simulation of network velocity, if data transfer is a potential threat and the page content large images or resources, the user can select a network connection in the upper tab.</p>
<h3 id="mozilla-firefox">Mozilla Firefox</h3>
<p>Mozilla Firefox uses a different approach, instead od choosing a target device you can enter the width and length sizes. To enable, just select Responsive Design View in ‘Developer Tools’(⌘⌥M in Mac). The useful controls to rotate and simulate touch events are above the rendered page as you can se below.</p>
<p><img src="/assets/firefox_responsive_view.png" alt="My helpful screenshot" /></p>
<h3 id="after-deployment">After Deployment</h3>
<p>The ‘After Deployment’ tools are important for the overall look, to catch specific details that are hard to be tracked during development stage. Those pages are useful to test the navigation in different environments. They are called ‘after deployment’ because you cannot just point to your localhost. I like two sites that provides excellent simulation services, the first is <a href="http://ami.responsivedesign.is">Am I Responsive</a>, an easy tool that permits you to see the rendered page in all devices at the same time. Unfortunatelly, it just renders in Apple viewports.</p>
<p><img src="/assets/amiresponsive.png" alt="My helpful screenshot" /></p>
<p>The other page I usually test my features is <a href="http://responsive.is/typecast.com">Responsive Is</a>, which you can emulate different pre-defined viewports.</p>
<p><img src="/assets/responsiveis.png" alt="My helpful screenshot" /></p>
<h3 id="further-reading">Further Reading</h3>
<p>Recently I received a real good <a href="http://www.whoishostingthis.com/resources/responsive-design-video/">resource</a> explaining the pros of using responsive design with two detailed posts. One called <a href="http://www.whoishostingthis.com/blog/2013/06/26/responsive-design-infographic/">Responsive Design: Getting It Right</a> with a nice infographic and other post called <a href="http://www.whoishostingthis.com/blog/2014/02/25/keeping-it-simple-with-responsive-web-design/">Keeping it Simple with Responsive Web Design</a>, both with useful informations for those who are in doubt if worth to spend some time dedicated to ensure the responsiveness of his pages.</p>
<p>If you use another resource to test the responsiveness of your pages, write down on our comments.</p>
<script type="text/javascript" src="/js/main.js"></script>
Free EBook: Modern Web Essentials Using JavaScript and HTML52014-11-12T00:00:00+00:00http://rafaelcfreire.github.io/2014/11/12/free-ebook---modern-web-essentials-using-javascript-and-html5
<div style="margin-bottom: 1.5em;">
<div>
<a href="https://twitter.com/share" class="twitter-share-button" style="vertical-align: bottom">Tweet</a>
</div>
<div>
<span class="fb-share-button" data-href="http://rafaelcfreire.github.io/2014/11/12/free-ebook---modern-web-essentials-using-javascript-and-html5/" data-layout="button"></span>
</div>
</div>
<p>Hi,</p>
<p>For those who are starting or even looking for a deeper understand in his studies about HTML5, Javascript and <a href="http://en.wikipedia.org/wiki/Single-page_application">SPA</a> I highly recommend the download of “Modern Web Essentials Using JavaScript and HTML5” written by <a href="http://www.infoq.com/author/David-Pitt">David Pitt</a>. The book is available at <a href="http://www.infoq.com/minibooks/javascript-html5-essentials">http://www.infoq.com/minibooks/javascript-html5-essentials</a>.</p>
<p>Thanks,</p>
<script type="text/javascript" src="/js/main.js"></script>
Where to Start With Functional Programming?2014-10-30T00:00:00+00:00http://rafaelcfreire.github.io/2014/10/30/Where-to-start-with-functional-programming
<div style="margin-bottom: 1.5em;">
<div>
<a href="https://twitter.com/share" class="twitter-share-button" style="vertical-align: bottom">Tweet</a>
</div>
<div>
<span class="fb-share-button" data-href="http://rafaelcfreire.github.io/2014/10/30/Where-to-start-with-functional-programming/" data-layout="button"></span>
</div>
</div>
<p>Hi all,</p>
<p>Nowadays it is very common to see people discussing the use of <a href="https://www.haskell.org/haskellwiki/Functional_programming" target="_blank">functional programming</a>, most of modern languages adopt some of its principles and seems that it is a new shift that will change the way you program, but definitely isn’t. Functional programming has been around for a long time, the first functional language was <a href="http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Lisp_(programming_language).html" target="_blank">LISP</a> back in 1959 and since then there are some misconceptions and confusions about the idea of functional programming that leads to misuse of a very useful paradigm but that isn’t a silver bullet. People with background in <a href="http://en.wikipedia.org/wiki/Imperative_programming" target="_blank">imperative programming</a> where the solution for an algorithm should be described step by step in a sequence of statements tend to feel love at first sight with functional programming due to the fact of writing much less code to achieve the same results and ease of reading.</p>
<h3 id="principles-of-imperative-programming">Principles of Imperative Programming</h3>
<p>To a better understand of Functional Programming let’s see what are the principles of Imperative Programming, so we can have a trade between both. Basically Imperative Programming deals with:</p>
<ul>
<li>Modifying mutable variables</li>
<li>Using assignments</li>
<li>Control structures such as if-then-else, loops, breaks, continue, return</li>
</ul>
<p>As mentioned by <a href="http://lampwww.epfl.ch/~odersky/" target="_blank">Martin Odersky</a> in <a href="https://class.coursera.org/progfun-2012-001" target="_blank">Functional Principles with Scala</a> the most common informal way to understand imperative programs is a <a href="http://www.c-jump.com/CIS77/CPU/InstrCycle/lecture.html" target="_blank">instruction sequences for a Von Neumann computer</a>. So, what’s wrong here? The problem with Imperative Programming is its nature of changing states. Dealing with huge imperative applications can be extreme improductive to be sustained once scaling is a big problem when shared mutable state is on the scene.</p>
<h3 id="what-is-functional-programming">What is Functional Programming?</h3>
<p>One of the misconceptions that we can mention about functional programming is the fact that it is a replacement for object oriented programming. Definitely NOT…repeat it to yourself 3 times. There is no contradiction with OO (<a href="http://scala-lang.org" target="_blank">Scala</a> use both for example), rather, you can use object oriented design with a functional implementation. Functional programming is a <a href="http://en.wikipedia.org/wiki/Programming_paradigm" target="_blank">paradigm</a> focused in how should be the structure of the implementation, so, instead of describing all the steps to perform an action ending in a low level and verbose code, functional is more concise, easier and expressive. I came from OOP with imperative background and right in my first experiments with FP in Scala I was really excited, imagine a language with wich you code as simple as reading? Now Java 8 has the <a href="http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html" target="_blank">new syntax of Java 8 with Lambda expressions</a> which I just met but I always worked with Java’s previous versions that everything is so <a href="http://en.wiktionary.org/wiki/verbose" target="_blank">verbose</a>, let’s see a small example of iterating through a list.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">final</span> <span class="no">List</span><span class="o"><</span><span class="no">BigDecimal</span><span class="o">></span> <span class="n">valores</span> <span class="o">=</span> <span class="no">Arrays</span><span class="p">.</span><span class="nf">asList</span><span class="p">(</span><span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"70"</span><span class="p">),</span> <span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"25"</span><span class="p">),</span> <span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"55"</span><span class="p">),</span> <span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"12"</span><span class="p">));</span>
<span class="k">for</span><span class="p">(</span><span class="no">BigDecimal</span> <span class="n">doubleValue</span> <span class="p">:</span> <span class="n">valores</span><span class="p">){</span>
<span class="no">System</span><span class="p">.</span><span class="nf">out</span><span class="p">.</span><span class="nf">println</span><span class="p">(</span><span class="n">doubleValue</span><span class="p">);</span>
<span class="p">}</span></code></pre></figure>
<p>Even the syntax of <a href="https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with" target="_blank">enhanced loop</a> isn’t so clear but brought a huge improvement in terms of reading. Under the hood the enhanced for uses the <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html" target="_blank">Iterator Interface</a> calling <i>hasNext()</i> and <i>next()</i> methods.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">final</span> <span class="no">List</span><span class="o"><</span><span class="no">BigDecimal</span><span class="o">></span> <span class="n">values</span> <span class="o">=</span> <span class="no">Arrays</span><span class="p">.</span><span class="nf">asList</span><span class="p">(</span>
<span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"70"</span><span class="p">),</span> <span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"25"</span><span class="p">),</span> <span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"55"</span><span class="p">),</span>
<span class="n">new</span> <span class="no">BigDecimal</span><span class="p">(</span><span class="s2">"12"</span><span class="p">));</span>
<span class="n">values</span><span class="p">.</span><span class="nf">forEach</span><span class="p">((</span><span class="no">BigDecimal</span> <span class="n">doubleValue</span><span class="p">)</span> <span class="o">-></span> <span class="no">System</span><span class="p">.</span><span class="nf">out</span><span class="p">.</span><span class="nf">println</span><span class="p">(</span><span class="n">doubleValue</span><span class="p">));</span></code></pre></figure>
<p>Noticed how is more readable? Makes more sense and clearly you can identify the meaning of that execution in terms of purpose but, thats just one of the characteristics of FP used to show the difference from an imperative to a functional paradigm in coding. The definition of FP isn’t so clear but there are some features that can’t be forgot when talking about the benefits of FP. According to <a href="http://bracha.org" target="_blank">Gilad Bracha</a> in (<a href="http://www.infoq.com/presentations/functional-pros-cons" target="_blank>">one brilliant presentation about what is and what isn’t FP</a>, the definitions of FP vary, but tend to involve <a href="http://en.wikipedia.org/wiki/Higher-order_function" target="_blank">High Order Function</a> and <a href="">Abscence of effects</a>.</p>
<p>Those 2 things are really in the core of FP. Abscence of effects is directly related with immutability and one of the most important things when working with functions and you know that’re prepared for the shift to FP when abscence of effects is automatic in your mind when modelling your functions, I’d enumerate others points to understand if you want to really dig into FP, that are:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/First-class_function" target="_blank">First Class Functions</a></li>
<li><a href="http://en.wikipedia.org/wiki/Pure_function" target="_blank">Pure Functions</a></li>
<li><a href="http://en.wikipedia.org/wiki/Immutable_object" target="_blank">Immutable variables</a></li>
<li><a href="http://en.wikipedia.org/wiki/Currying" target="_blank">Currying</a></li>
<li><a href="http://en.wikipedia.org/wiki/Tail_call" target="_blank">Tail Recursion</a></li>
<li><a href="http://c2.com/cgi/wiki?PatternMatching" target="_blank">Pattern Matching</a></li>
<li><a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)" target="_blank">Monads</a></li>
<li>
<ul>
<li><a href="http://stackoverflow.com/questions/16501/what-is-a-lambda-function" target="_blank">Lambda (Anonymous functions)</a></li>
</ul>
</li>
</ul>
<p>So, let’s see a brief explanation and a small example of each one in Scala of the above</p>
<h3 id="first-class-functions">First Class Functions</h3>
<p>First Class Functions are functions treated as objects themselves. It can be passed as a parameter to another function, return a function from a function or store a function in a variable. Functions which take other functions as parameter or return them are also known as <i>High Order Function</i>. Here is a small example, i decided to use Javascript for ours examples because it is a well known language and available in all modern browsers so you can easily open your browser and test the code.</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">var</span> <span class="n">myFunction</span> <span class="o">=</span> <span class="n">function</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">){</span> <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="p">}</span>
<span class="n">myFunction</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">3</span><span class="p">);</span>
<span class="n">function</span> <span class="n">sumAllValues</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">b</span><span class="p">,</span> <span class="n">c</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">a</span> <span class="o">+</span> <span class="n">b</span> <span class="o">+</span> <span class="n">c</span> <span class="p">};</span>
<span class="n">sumAllValues</span><span class="p">(</span><span class="n">myFunction</span><span class="p">(</span><span class="mi">4</span><span class="p">,</span><span class="mi">3</span><span class="p">),</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span></code></pre></figure>
<p>In the example above we created a variable called <i>myFunction</i> and assigned an <a href="http://en.wikipedia.org/wiki/Anonymous_function" target="_blank">Anonymous Function</a> which sum two values. After I defined a function called <i>sumAllValues</i> where return the sum of his parameters that in our case one of them is the Anonymous Function assigned to myFunction variable, this is our small example of first class functions.</p>
<h3 id="pure-functions">Pure Functions</h3>
<p>Pure Functions is a mathematical concept that relies on the fact that a function always evaluates the same value given the same arguments. In our subject it is directly associated with mutability and side effects or the absence of them. In FP we should not mutate variable values that are passed as parameters inside our functions and a function should be designed to <u>always perform the same computation, resulting in the same output given a set of inputs</u>. Larger functions tends to be hard to maintain and error prone, in a good functional design a function does exactly one computation and return the value of it.</p>
<h3 id="immutable-variables">Immutable Variables</h3>
<p>Immutable variables is a concept in the core of Functional Programming. It is related with side effects like Pure Functions, in therms of multi-thread applications an immutable object is totally reliable once it can’t have his value changed so, if you want to change a value from a immutable object you should create a new one and reference to it. Immutable variables is not just a good practice in FP, languages like Java has lot of immutable classes in his core, <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html" target="_blank">String</a> is a classical example.</p>
<h3 id="currying">Currying</h3>
<p>Currying is a technique of changing the number of parameters of a function, so for example if a function has 5 parameters you can change it to one parameter. Currying is used behind the scenes in the <i>High Order Functions</i> mentioned above to simplify and reuse functions. Let’s see a practical example with Javascript code:</p>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">function</span> <span class="n">pow</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">j</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="n">i</span> <span class="o">*</span> <span class="n">j</span><span class="p">;</span>
<span class="p">}</span>
<span class="n">function</span> <span class="n">square</span> <span class="p">(</span><span class="n">k</span><span class="p">)</span> <span class="p">{</span>
<span class="k">return</span> <span class="n">pow</span><span class="p">(</span><span class="n">k</span><span class="p">,</span> <span class="mi">2</span><span class="p">);</span>
<span class="p">}</span>
<span class="n">alert</span><span class="p">(</span><span class="n">square</span><span class="p">(</span><span class="mi">6</span><span class="p">));</span></code></pre></figure>
<p>The code above is a classical example where a function called <i>pow</i> that takes two parameters is used inside the <i>square</i> function instead of redoing his algorithm inside square function. As mentioned above, it enhances the flexibility and reuse of functions.</p>
<p>When understanding these topics, you’ll start to take advantage of FP principles and have a better coding with more pleasure and less error prone. Probably you’ll never want get back to old imperative way and will notice yourself thinking functional for solving problems that you used to have. When its happen you’ve been bitten by the functional bug ;)</p>
<h3 id="for-further-reading">For Further Reading</h3>
<p>If you want to go further, you can start by the John Backus paper <a href="http://web.stanford.edu/class/cs242/readings/backus.pdf" target="_blank">Can Programming Be Liberated From the Von Neumann Style? A Functional Style and Its Algebra of Programs.</a> where, back in 1977 he discusses some application for FP. Other good reference is the already mentioned presentation of Gilad Bracha where he explains how to distinguish FP hype from reality and to apply key ideas of FP in non-FP languages, separating the good parts of FP from its unnecessary cultural baggage.
What really made me fell confortable with FP as a beginner was the Martin Odersky course at <a href="https://www.coursera.org" target="_blank">Coursera</a> called <a href="https://class.coursera.org/progfun-2012-001" target="_blank">Functional Principles with Scala</a> that I mentioned before in this article. In this course you’ll have a good understand of the difference between</p>
<p>Currently I’m reading the following book and finding it really helpful with good explanation about principles and techniques</p>
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=qf_sp_asin_til&ad_type=product_link&tracking_id=raffretecblo-20&marketplace=amazon&region=US&placement=1449368174&asins=1449368174&linkId=LENUPRQEWK47BLGG&show_border=true&link_opens_in_new_window=true">
</iframe>
<p>And you, from where you suggest to start with functional?</p>
<script type="text/javascript" src="/js/main.js"></script>
Javascript's This Nightmare2014-10-11T00:00:00+00:00http://rafaelcfreire.github.io/lessons/2014/10/11/javascripts-this-nightmare
<div style="margin-bottom: 1.5em;">
<div>
<a href="https://twitter.com/share" class="twitter-share-button" style="vertical-align: bottom">Tweet</a>
</div>
<div>
<span id="facebook-share" class="fb-share-button" data-href="http://rafaelcfreire.github.io/lessons/2014/10/11/Javascripts-this-nightmare/" data-layout="button"></span>
</div>
</div>
<p>Hi there,</p>
<p>This is the first formal post of my blog, the idea here is to bring relevant topics and discussions that I have faced in my career. Considering that, I decided to pick up a subject that is very confusing even for experienced developers, specially for those who came from an object oriented programming and aren’t so familiar with Javascript. The “this nightmare” can bring on some bugs that are really messy and hard to track. Actually it is some of the basic knowledge of the Javascript language that took me a long time to understand and consequently decided to write about. So, let’s dive into how the <i>this</i> reference works in Javascript.</p>
<h3 id="different-types-of-invocation">Different Types of Invocation</h3>
<p>The first step to understand how the <i>this</i> reference works in Javascript is know that it depends on how it is being referenced. There are four distinguished ways to do that and they are:</p>
<ul>
<li>As a simple function invocation.</li>
<li>As a method invocation.</li>
<li>As an object creation.</li>
<li>Using the .apply and .call functions.</li>
</ul>
<p>Let’s see each one and discuss the contrasts between them.</p>
<h3 id="as-a-simple-function-invocation">As a Simple Function Invocation</h3>
<p>That’s the simplest way to invoke a function, in a direct function call in Javascript the <i>this</i> reference is bound to the global object at runtime. Let’s go for some real life examples:</p>
<ul>
<li>Open a Chrome browser and then open the Developer Tools (F12).</li>
<li>Go to Console item in the toolbar.</li>
<li>Create a simple function called doSomething as follow.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">function</span> <span class="n">doSomething</span><span class="p">(){</span>
<span class="n">console</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span> <span class="n">this</span> <span class="p">);</span>
<span class="p">}</span></code></pre></figure>
<ul>
<li>Call the doSomething function.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">doSomething</span><span class="p">();</span></code></pre></figure>
<ul>
<li>Note that the <i>this</i> points to the window object.</li>
</ul>
<p>At this point you should have the same as image below:</p>
<p><img src="/assets/image_post_2014_10_11.png" alt="My helpful screenshot" /></p>
<h3 id="as-a-method-invocation">As a Method Invocation</h3>
<p>For those with a object oriented background, the method invocation is the most natural type of invocation. When a function is a property of an object, that function can be invoked as a method using the object’s instance and in this case the <i>this</i> reference clearly will be bounded to the instance of that object. Here’s an example:</p>
<ul>
<li>Open a Chrome browser and then open the Developer Tools (F12).</li>
<li>Go to Console item in the toolbar.</li>
<li>Create a Javascript object called <i>simpleObject</i> and add a method <i>simpleMethod</i> as follow.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">var</span> <span class="n">simpleObject</span> <span class="o">=</span>
<span class="p">{</span>
<span class="ss">counter: </span><span class="mi">0</span><span class="p">,</span>
<span class="ss">addCounter: </span><span class="n">function</span><span class="p">(</span><span class="n">value</span><span class="p">){</span>
<span class="n">this</span><span class="p">.</span><span class="nf">counter</span> <span class="o">+=</span> <span class="n">value</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">};</span></code></pre></figure>
<ul>
<li>Then, call our method <i>addCounter</i> on the instance of <i>simpleObject</i>.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">simpleObject</span><span class="p">.</span><span class="nf">addCounter</span><span class="p">(</span><span class="mi">1</span><span class="p">);</span></code></pre></figure>
<ul>
<li>Print the value of our variable counter by doing</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">simpleObject</span><span class="p">.</span><span class="nf">counter</span><span class="p">;</span></code></pre></figure>
<p>So, you’ll have the following values in your console:</p>
<p><img src="/assets/image2_post_2014_10_11.png" alt="My helpful screenshot" /></p>
<p>What happened in the example above? We created an object called <i>simpleObject</i> with two attributes: <i>counter</i> and <i>addCounter</i>. An <a href="http://en.wikipedia.org/wiki/Anonymous_function#Javascript" target="_blank">anonymous function</a> that is responsible for add an value to the counter attribute is associated with the addCounter attribute using the <i>this</i> to point to the instance of the object, then we call the method addCounter with “1” as parameter and next check the value of counter attribute. So, in a method invocation inside an Javascript object the this reference points to the instance of the object.</p>
<h3 id="as-an-object-creation">As an Object Creation</h3>
<p>AKA referenced as Constructor Invocation, this method considers that any named function can be used as a constructor. There’s no difference in the function declaration, the difference is in how the function is invoked once it uses the <i>new</i> keyword. If a function is invoked with the <i>new</i> prefix a new object is created and <i>this</i> is assigned to that object. Let’s see how it works:</p>
<ul>
<li>Open a Chrome browser and then open the Developer Tools (F12).</li>
<li>Go to Console item in the toolbar.</li>
<li>Create a Javascript function called <i>Creation</i> (By convention, once it’s a constructor we’ll keep it with a capitalized name). In this function, create an attribute called <i>firstAttribute</i> and bound it to a function associated with <i>this</i>.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">function</span> <span class="no">Creation</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">this</span><span class="p">.</span><span class="nf">firstAttribute</span> <span class="o">=</span> <span class="n">function</span> <span class="p">()</span> <span class="p">{</span> <span class="k">return</span> <span class="n">this</span><span class="p">;</span> <span class="p">};</span>
<span class="p">}</span></code></pre></figure>
<ul>
<li>Now, create an object using the constructor.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">var</span> <span class="n">objectOne</span> <span class="o">=</span> <span class="n">new</span> <span class="no">Creation</span><span class="p">();</span></code></pre></figure>
<ul>
<li>Check the value of firstAttribute inside objectOne.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">objectOne</span><span class="p">.</span><span class="nf">firstAttribute</span><span class="p">();</span></code></pre></figure>
<p>So, the value of <i>this</i> is an empty object created when the function <i>Creation</i> was called with the prefix <i>new</i> as in the following image:</p>
<p><img src="/assets/image3_post_2014_10_11.png" alt="My helpful screenshot" /></p>
<h3 id="using-the-apply-and-call-methods">Using the .apply and .call Methods</h3>
<p>And last, the <i>.apply</i> and <i>.call</i> are methods that you can set any object you want as <i>this</i>. Since functions are what we call as <a href="http://en.wikipedia.org/wiki/First-class_function" target="_blank">first class citizens</a> they can have properties and methods, just like an object and <i>.apply</i> and <i>.call</i> are two methods available for all functions in Javascript. First class citizens is one of the most important definitions of Javascript functions and you should read about it if don’t feel confident enough in this subject. So, as said before, <i>.apply</i> and <i>.call</i> are opened for you choose what will be your <i>this</i> reference, let’s practice:</p>
<ul>
<li>Open a Chrome browser and then open the Developer Tools (F12).</li>
<li>Go to Console item in the toolbar.</li>
<li>Create a function <i>sumArray</i> that sum the values of an array.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"><span class="n">function</span> <span class="n">sumArray</span><span class="p">(){</span>
<span class="n">var</span> <span class="n">sum</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">for</span><span class="p">(</span><span class="n">var</span> <span class="n">n</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="n">n</span> <span class="o"><</span> <span class="n">arguments</span><span class="p">.</span><span class="nf">length</span><span class="p">;</span> <span class="n">n</span><span class="o">++</span><span class="p">){</span>
<span class="n">sum</span> <span class="o">+=</span> <span class="n">arguments</span><span class="p">[</span><span class="n">n</span><span class="p">];</span>
<span class="p">}</span>
<span class="n">this</span><span class="p">.</span><span class="nf">sum</span> <span class="o">=</span> <span class="n">sum</span><span class="p">;</span>
<span class="p">}</span></code></pre></figure>
<ul>
<li>Create two variables and name them as <i>object1</i> and <i>object2</i>.</li>
<li>Call the <i>sumArray</i> function using the <i>apply</i> method. As parameter pass the <i>object1</i> to be the reference of <i>“this”</i> and an array with the values will be used to sum.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">sumArray</span><span class="p">.</span><span class="nf">apply</span><span class="p">(</span><span class="n">object1</span><span class="p">,</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span><span class="mi">3</span><span class="p">]);</span></code></pre></figure>
<ul>
<li>Call the <i>sumArray</i> function using the <i>call</i> method. As parameter pass the <i>object2</i> to be the reference of <i>“this”</i> and the values separated with commas to be used to sum.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">sumArray</span><span class="p">.</span><span class="nf">call</span><span class="p">(</span><span class="n">object2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">);</span></code></pre></figure>
<ul>
<li>Note that the first parameter will be our <i>this<i> in both cases, the difference between the two methods is that <i>.apply</i> expect an array and <i>.call</i> values separated by a single comma.</i></i></li>
<li>Inside <i>sumArray</i> function, we setted <i>this.sum</i> value, so let’s check those values. Type <i>object1.sum</i> and <i>object2.sum</i> to see if they were setted right.</li>
</ul>
<figure class="highlight"><pre><code class="language-ruby" data-lang="ruby"> <span class="n">object1</span><span class="p">.</span><span class="nf">sum</span><span class="p">;</span>
<span class="n">object2</span><span class="p">.</span><span class="nf">sum</span><span class="p">;</span></code></pre></figure>
<p><img src="/assets/image4_post_2014_10_11.png" alt="My helpful screenshot" /></p>
<h3 id="strict-mode">Strict Mode</h3>
<p>We mentioned some times that the this reference is bounded to the global object at runtime but, what it means? It depends on the environment you’re executing the code. If you run the example above in the console it will be the <a href="http://www.w3schools.com/js/js_window.asp" target="_blank">window object</a>, if you run inside a <a href="http://nodejs.org" target="_blank">NodeJS</a> environment it will be the NodeJS global object. But both environments have (<a href="http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/" target="_blank">Strict Mode</a>. Strict mode sets the <i>this</i> to an undefined reference. You can see in the link above the advantages of using Strict mode.</p>
<h3 id="for-further-reading">For Further Reading</h3>
<p>To go deeply in this subject I suggest the following books, both focused in Javascript. The first is a book of <a href="https://github.com/getify/You-Dont-Know-JS/blob/master/README.md#you-dont-know-js-book-series" target="_blank">You Don’t Know JS Series</a> which I’m currently reading and highly suggest for deeper understanding of the mechanism that <i>this</i> relies on. In the link above you can see that’s there are more interesting topics about JS like Scope, Closures. If you want to buy a copy of the book, click on the link below. The second link is one of the greatest books about JS. Javascript: The Good Parts is an introdutory reference to some of the most important points in JS. Written by <a href="http://Javascript.crockford.com" target="_blank">Douglas Crockford</a>, creator of JSON.</p>
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecblo-20&marketplace=amazon&region=US&placement=1491904151&asins=1491904151&linkId=463ZW6OOIPXPIIB5&show_border=true&link_opens_in_new_window=true">
</iframe>
<iframe style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=raffretecblo-20&marketplace=amazon&region=US&placement=0596517742&asins=0596517742&linkId=ZTOWF5DCU6HUXDRX&show_border=true&link_opens_in_new_window=true">
</iframe>
<script type="text/Javascript" src="/js/main.js"></script>
Jekyll Introduction2011-12-29T00:00:00+00:00http://rafaelcfreire.github.io/lessons/2011/12/29/jekyll-introduction
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-56746688-1', 'auto');
ga('send', 'pageview');
</script>
<p>This Jekyll introduction will outline specifically what Jekyll is and why you would want to use it.
Directly following the intro we’ll learn exactly <em>how</em> Jekyll does what it does.</p>
<h2 id="overview">Overview</h2>
<h3 id="what-is-jekyll">What is Jekyll?</h3>
<p>Jekyll is a parsing engine bundled as a ruby gem used to build static websites from
dynamic components such as templates, partials, liquid code, markdown, etc. Jekyll is known as “a simple, blog aware, static site generator”.</p>
<h3 id="examples">Examples</h3>
<p>This website is created with Jekyll. <a href="https://github.com/mojombo/jekyll/wiki/Sites">Other Jekyll websites</a>.</p>
<h3 id="what-does-jekyll-do">What does Jekyll Do?</h3>
<p>Jekyll is a ruby gem you install on your local system.
Once there you can call <code class="language-plaintext highlighter-rouge">jekyll --server</code> on a directory and provided that directory
is setup in a way jekyll expects, it will do magic stuff like parse markdown/textile files,
compute categories, tags, permalinks, and construct your pages from layout templates and partials.</p>
<p>Once parsed, Jekyll stores the result in a self-contained static <code class="language-plaintext highlighter-rouge">_site</code> folder.
The intention here is that you can serve all contents in this folder statically from a plain static web-server.</p>
<p>You can think of Jekyll as a normalish dynamic blog but rather than parsing content, templates, and tags
on each request, Jekyll does this once <em>beforehand</em> and caches the <em>entire website</em> in a folder for serving statically.</p>
<h3 id="jekyll-is-not-blogging-software">Jekyll is Not Blogging Software</h3>
<p><strong>Jekyll is a parsing engine.</strong></p>
<p>Jekyll does not come with any content nor does it have any templates or design elements.
This is a common source of confusion when getting started.
Jekyll does not come with anything you actually use or see on your website - you have to make it.</p>
<h3 id="why-should-i-care">Why Should I Care?</h3>
<p>Jekyll is very minimalistic and very efficient.
The most important thing to realize about Jekyll is that it creates a static representation of your website requiring only a static web-server.
Traditional dynamic blogs like Wordpress require a database and server-side code.
Heavily trafficked dynamic blogs must employ a caching layer that ultimately performs the same job Jekyll sets out to do; serve static content.</p>
<p>Therefore if you like to keep things simple and you prefer the command-line over an admin panel UI then give Jekyll a try.</p>
<p><strong>Developers like Jekyll because we can write content like we write code:</strong></p>
<ul>
<li>Ability to write content in markdown or textile in your favorite text-editor.</li>
<li>Ability to write and preview your content via localhost.</li>
<li>No internet connection required.</li>
<li>Ability to publish via git.</li>
<li>Ability to host your blog on a static web-server.</li>
<li>Ability to host freely on GitHub Pages.</li>
<li>No database required.</li>
</ul>
<h1 id="how-jekyll-works">How Jekyll Works</h1>
<p>The following is a complete but concise outline of exactly how Jekyll works.</p>
<p>Be aware that core concepts are introduced in rapid succession without code examples.
This information is not intended to specifically teach you how to do anything, rather it
is intended to give you the <em>full picture</em> relative to what is going on in Jekyll-world.</p>
<p>Learning these core concepts should help you avoid common frustrations and ultimately
help you better understand the code examples contained throughout Jekyll-Bootstrap.</p>
<h2 id="initial-setup">Initial Setup</h2>
<p>After <a href="/index.html#start-now">installing jekyll</a> you’ll need to format your website directory in a way jekyll expects.
Jekyll-bootstrap conveniently provides the base directory format.</p>
<h3 id="the-jekyll-application-base-format">The Jekyll Application Base Format</h3>
<p>Jekyll expects your website directory to be laid out like so:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.
|-- _config.yml
|-- _includes
|-- _layouts
| |-- default.html
| |-- post.html
|-- _posts
| |-- 2011-10-25-open-source-is-good.markdown
| |-- 2011-04-26-hello-world.markdown
|-- _site
|-- index.html
|-- assets
|-- css
|-- style.css
|-- javascripts
</code></pre></div></div>
<ul>
<li>
<p><strong>_config.yml</strong>
Stores configuration data.</p>
</li>
<li>
<p><strong>_includes</strong>
This folder is for partial views.</p>
</li>
<li>
<p><strong>_layouts</strong>
This folder is for the main templates your content will be inserted into.
You can have different layouts for different pages or page sections.</p>
</li>
<li>
<p><strong>_posts</strong>
This folder contains your dynamic content/posts.
the naming format is required to be <code class="language-plaintext highlighter-rouge">@YEAR-MONTH-DATE-title.MARKUP@</code>.</p>
</li>
<li>
<p><strong>_site</strong>
This is where the generated site will be placed once Jekyll is done transforming it.</p>
</li>
<li>
<p><strong>assets</strong>
This folder is not part of the standard jekyll structure.
The assets folder represents <em>any generic</em> folder you happen to create in your root directory.
Directories and files not properly formatted for jekyll will be left untouched for you to serve normally.</p>
</li>
</ul>
<p>(read more: <a href="https://github.com/mojombo/jekyll/wiki/Usage">https://github.com/mojombo/jekyll/wiki/Usage</a>)</p>
<h3 id="jekyll-configuration">Jekyll Configuration</h3>
<p>Jekyll supports various configuration options that are fully outlined here:
(<a href="https://github.com/mojombo/jekyll/wiki/Configuration">https://github.com/mojombo/jekyll/wiki/Configuration</a>)</p>
<h2 id="content-in-jekyll">Content in Jekyll</h2>
<p>Content in Jekyll is either a post or a page.
These content “objects” get inserted into one or more templates to build the final output for its respective static-page.</p>
<h3 id="posts-and-pages">Posts and Pages</h3>
<p>Both posts and pages should be written in markdown, textile, or HTML and may also contain Liquid templating syntax.
Both posts and pages can have meta-data assigned on a per-page basis such as title, url path, as well as arbitrary custom meta-data.</p>
<h3 id="working-with-posts">Working With Posts</h3>
<p><strong>Creating a Post</strong>
Posts are created by properly formatting a file and placing it the <code class="language-plaintext highlighter-rouge">_posts</code> folder.</p>
<p><strong>Formatting</strong>
A post must have a valid filename in the form <code class="language-plaintext highlighter-rouge">YEAR-MONTH-DATE-title.MARKUP</code> and be placed in the <code class="language-plaintext highlighter-rouge">_posts</code> directory.
If the data format is invalid Jekyll will not recognize the file as a post. The date and title are automatically parsed from the filename of the post file.
Additionally, each file must have <a href="https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter">YAML Front-Matter</a> prepended to its content.
YAML Front-Matter is a valid YAML syntax specifying meta-data for the given file.</p>
<p><strong>Order</strong>
Ordering is an important part of Jekyll but it is hard to specify a custom ordering strategy.
Only reverse chronological and chronological ordering is supported in Jekyll.</p>
<p>Since the date is hard-coded into the filename format, to change the order, you must change the dates in the filenames.</p>
<p><strong>Tags</strong>
Posts can have tags associated with them as part of their meta-data.
Tags may be placed on posts by providing them in the post’s YAML front matter.
You have access to the post-specific tags in the templates. These tags also get added to the sitewide collection.</p>
<p><strong>Categories</strong>
Posts may be categorized by providing one or more categories in the YAML front matter.
Categories offer more significance over tags in that they can be reflected in the URL path to the given post.
Note categories in Jekyll work in a specific way.
If you define more than one category you are defining a category hierarchy “set”.
Example:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
title : Hello World
categories : [lessons, beginner]
---
</code></pre></div></div>
<p>This defines the category hierarchy “lessons/beginner”. Note this is <em>one category</em> node in Jekyll.
You won’t find “lessons” and “beginner” as two separate categories unless you define them elsewhere as singular categories.</p>
<h3 id="working-with-pages">Working With Pages</h3>
<p><strong>Creating a Page</strong>
Pages are created by properly formatting a file and placing it anywhere in the root directory or subdirectories that do <em>not</em> start with an underscore.</p>
<p><strong>Formatting</strong>
In order to register as a Jekyll page the file must contain <a href="https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter">YAML Front-Matter</a>.
Registering a page means 1) that Jekyll will process the page and 2) that the page object will be available in the <code class="language-plaintext highlighter-rouge">site.pages</code> array for inclusion into your templates.</p>
<p><strong>Categories and Tags</strong>
Pages do not compute categories nor tags so defining them will have no effect.</p>
<p><strong>Sub-Directories</strong>
If pages are defined in sub-directories, the path to the page will be reflected in the url.
Example:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>.
|-- people
|-- bob
|-- essay.html
</code></pre></div></div>
<p>This page will be available at <code class="language-plaintext highlighter-rouge">http://yourdomain.com/people/bob/essay.html</code></p>
<p><strong>Recommended Pages</strong></p>
<ul>
<li><strong>index.html</strong>
You will always want to define the root index.html page as this will display on your root URL.</li>
<li><strong>404.html</strong>
Create a root 404.html page and GitHub Pages will serve it as your 404 response.</li>
<li><strong>sitemap.html</strong>
Generating a sitemap is good practice for SEO.</li>
<li><strong>about.html</strong>
A nice about page is easy to do and gives the human perspective to your website.</li>
</ul>
<h2 id="templates-in-jekyll">Templates in Jekyll</h2>
<p>Templates are used to contain a page’s or post’s content.
All templates have access to a global site object variable: <code class="language-plaintext highlighter-rouge">site</code> as well as a page object variable: <code class="language-plaintext highlighter-rouge">page</code>.
The site variable holds all accessible content and metadata relative to the site.
The page variable holds accessible data for the given page or post being rendered at that point.</p>
<p><strong>Create a Template</strong>
Templates are created by properly formatting a file and placing it in the <code class="language-plaintext highlighter-rouge">_layouts</code> directory.</p>
<p><strong>Formatting</strong>
Templates should be coded in HTML and contain YAML Front Matter.
All templates can contain Liquid code to work with your site’s data.</p>
<p><strong>Rending Page/Post Content in a Template</strong>
There is a special variable in all templates named : <code class="language-plaintext highlighter-rouge">content</code>.
The <code class="language-plaintext highlighter-rouge">content</code> variable holds the page/post content including any sub-template content previously defined.
Render the content variable wherever you want your main content to be injected into your template:</p>
<pre><code>...
<body>
<div id="sidebar"> ... </div>
<div id="main">
{{content}}
</div>
</body>
...</code></pre>
<h3 id="sub-templates">Sub-Templates</h3>
<p>Sub-templates are exactly templates with the only difference being they
define another “root” layout/template within their YAML Front Matter.
This essentially means a template will render inside of another template.</p>
<h3 id="includes">Includes</h3>
<p>In Jekyll you can define include files by placing them in the <code class="language-plaintext highlighter-rouge">_includes</code> folder.
Includes are NOT templates, rather they are just code snippets that get included into templates.
In this way, you can treat the code inside includes as if it was native to the parent template.</p>
<p>Any valid template code may be used in includes.</p>
<h2 id="using-liquid-for-templating">Using Liquid for Templating</h2>
<p>Templating is perhaps the most confusing and frustrating part of Jekyll.
This is mainly due to the fact that Jekyll templates must use the Liquid Templating Language.</p>
<h3 id="what-is-liquid">What is Liquid?</h3>
<p><a href="https://github.com/Shopify/liquid">Liquid</a> is a secure templating language developed by <a href="http://shopify.com">Shopify</a>.
Liquid is designed for end-users to be able to execute logic within template files
without imposing any security risk on the hosting server.</p>
<p>Jekyll uses Liquid to generate the post content within the final page layout structure and as the primary interface for working with
your site and post/page data.</p>
<h3 id="why-do-we-have-to-use-liquid">Why Do We Have to Use Liquid?</h3>
<p>GitHub uses Jekyll to power <a href="http://pages.github.com/">GitHub Pages</a>.
GitHub cannot afford to run arbitrary code on their servers so they lock developers down via Liquid.</p>
<h3 id="liquid-is-not-programmer-friendly">Liquid is Not Programmer-Friendly.</h3>
<p>The short story is liquid is not real code and its not intended to execute real code.
The point being you can’t do jackshit in liquid that hasn’t been allowed explicitly by the implementation.
What’s more you can only access data-structures that have been explicitly passed to the template.</p>
<p>In Jekyll’s case it is not possible to alter what is passed to Liquid without hacking the gem or running custom plugins.
Both of which cannot be supported by GitHub Pages.</p>
<p>As a programmer - this is very frustrating.</p>
<p>But rather than look a gift horse in the mouth we are going to
suck it up and view it as an opportunity to work around limitations and adopt client-side solutions when possible.</p>
<p><strong>Aside</strong>
My personal stance is to not invest time trying to hack liquid. It’s really unnecessary
<em>from a programmer’s</em> perspective. That is to say if you have the ability to run custom plugins (i.e. run arbitrary ruby code)
you are better off sticking with ruby. Toward that end I’ve built <a href="http://github.com/plusjade/mustache-with-jekyll">Mustache-with-Jekyll</a></p>
<h2 id="static-assets">Static Assets</h2>
<p>Static assets are any file in the root or non-underscored subfolders that are not pages.
That is they have no valid YAML Front Matter and are thus not treated as Jekyll Pages.</p>
<p>Static assets should be used for images, css, and javascript files.</p>
<h2 id="how-jekyll-parses-files">How Jekyll Parses Files</h2>
<p>Remember Jekyll is a processing engine. There are two main types of parsing in Jekyll.</p>
<ul>
<li><strong>Content parsing.</strong>
This is done with textile or markdown.</li>
<li><strong>Template parsing.</strong>
This is done with the liquid templating language.</li>
</ul>
<p>And thus there are two main types of file formats needed for this parsing.</p>
<ul>
<li><strong>Post and Page files.</strong>
All content in Jekyll is either a post or a page so valid posts and pages are parsed with markdown or textile.</li>
<li><strong>Template files.</strong>
These files go in <code class="language-plaintext highlighter-rouge">_layouts</code> folder and contain your blogs <strong>templates</strong>. They should be made in HTML with the help of Liquid syntax.
Since include files are simply injected into templates they are essentially parsed as if they were native to the template.</li>
</ul>
<p><strong>Arbitrary files and folders.</strong>
Files that <em>are not</em> valid pages are treated as static content and pass through
Jekyll untouched and reside on your blog in the exact structure and format they originally existed in.</p>
<h3 id="formatting-files-for-parsing">Formatting Files for Parsing.</h3>
<p>We’ve outlined the need for valid formatting using <strong>YAML Front Matter</strong>.
Templates, posts, and pages all need to provide valid YAML Front Matter even if the Matter is empty.
This is the only way Jekyll knows you want the file processed.</p>
<p>YAML Front Matter must be prepended to the top of template/post/page files:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>---
layout: post
category : pages
tags : [how-to, jekyll]
---
... contents ...
</code></pre></div></div>
<p>Three hyphens on a new line start the Front-Matter block and three hyphens on a new line end the block.
The data inside the block must be valid YAML.</p>
<p>Configuration parameters for YAML Front-Matter is outlined here:
<a href="https://github.com/mojombo/jekyll/wiki/YAML-Front-Matter">A comprehensive explanation of YAML Front Matter</a></p>
<h4 id="defining-layouts-for-posts-and-templates-parsing">Defining Layouts for Posts and Templates Parsing.</h4>
<p>The <code class="language-plaintext highlighter-rouge">layout</code> parameter in the YAML Front Matter defines the template file for which the given post or template should be injected into.
If a template file specifies its own layout, it is effectively being used as a <code class="language-plaintext highlighter-rouge">sub-template.</code>
That is to say loading a post file into a template file that refers to another template file with work in the way you’d expect; as a nested sub-template.</p>
<h2 id="how-jekyll-generates-the-final-static-files">How Jekyll Generates the Final Static Files.</h2>
<p>Ultimately, Jekyll’s job is to generate a static representation of your website.
The following is an outline of how that’s done:</p>
<ol>
<li>
<p><strong>Jekyll collects data.</strong>
Jekyll scans the posts directory and collects all posts files as post objects. It then scans the layout assets and collects those and finally scans other directories in search of pages.</p>
</li>
<li>
<p><strong>Jekyll computes data.</strong>
Jekyll takes these objects, computes metadata (permalinks, tags, categories, titles, dates) from them and constructs one
big <code class="language-plaintext highlighter-rouge">site</code> object that holds all the posts, pages, layouts, and respective metadata.
At this stage your site is one big computed ruby object.</p>
</li>
<li>
<p><strong>Jekyll liquifies posts and templates.</strong>
Next jekyll loops through each post file and converts (through markdown or textile) and <strong>liquifies</strong> the post inside of its respective layout(s).
Once the post is parsed and liquified inside the the proper layout structure, the layout itself is “liquified”.
<strong>Liquification</strong> is defined as follows: Jekyll initiates a Liquid template, and passes a simpler hash representation of the ruby site object as well as a simpler
hash representation of the ruby post object. These simplified data structures are what you have access to in the templates.</p>
</li>
<li>
<p><strong>Jekyll generates output.</strong>
Finally the liquid templates are “rendered”, thereby processing any liquid syntax provided in the templates
and saving the final, static representation of the file.</p>
</li>
</ol>
<p><strong>Notes.</strong>
Because Jekyll computes the entire site in one fell swoop, each template is given access to
a global <code class="language-plaintext highlighter-rouge">site</code> hash that contains useful data. It is this data that you’ll iterate through and format
using the Liquid tags and filters in order to render it onto a given page.</p>
<p>Remember, in Jekyll you are an end-user. Your API has only two components:</p>
<ol>
<li>The manner in which you setup your directory.</li>
<li>The liquid syntax and variables passed into the liquid templates.</li>
</ol>
<p>All the data objects available to you in the templates via Liquid are outlined in the <strong>API Section</strong> of Jekyll-Bootstrap.
You can also read the original documentation here: <a href="https://github.com/mojombo/jekyll/wiki/Template-Data">https://github.com/mojombo/jekyll/wiki/Template-Data</a></p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope this paints a clearer picture of what Jekyll is doing and why it works the way it does.
As noted, our main programming constraint is the fact that our API is limited to what is accessible via Liquid and Liquid only.</p>
<p>Jekyll-bootstrap is intended to provide helper methods and strategies aimed at making it more intuitive and easier to work with Jekyll =)</p>
<p><strong>Thank you</strong> for reading this far.</p>
<h2 id="next-steps">Next Steps</h2>
<p>Please take a look at <a href=""></a>
or jump right into <a href="">Usage</a> if you’d like.</p>