Fixing Monitors in LXDE

Since I installed Fedora, I’ve been unable to run the computer with both, the external monitor, and the laptop monitor at the same time. So, I’ve decided to just run the external monitor, since it is bigger. I haven’t really spent too much time looking for a solution to this problem, but the times I’ve tried fixing it, I haven’t had any success.

Earlier this week, after getting tired of seeing a high amount or RAM usage, I decided to stop using GNOME, and use OpenBox without a desktop environment instead. This was easy to do. In the log screen, there is an option on the bottom where I have the options to use GNOME, LXDE, and OpenBox. I simply chose OpenBox. However, despite seeing a huge improvement on memory consumption, I was rather soon disappointed by the amount of configuration I had to do every time I turned the computer on. Sometimes I would have to log out, log into LXDE, change the monitor settings there, and see if that would work. The problem was that OpenBox would try to use both monitors, even when the external monitor was not plugged in! This cause me to not be able to see the windows, which by default would get placed in the area of the external monitor, but this would not get any signal.

As you may imagine, this quickly became too much trouble. Especially since there were no actual memory problems while running GNOME, I was just simply trying to reduce memory consumption.

Motivated by these inconveniences, I decided to give LXDE a try. LXDE also uses OpenBox as the window manager, but LXDE is a desktop environment, which means there is a lot of added benefit, such as a desktop, and a panel. All of this, while keeping memory consumption surprisingly low.

However, I made a mistake. I opened the Monitor Settings, and set the laptop monitor off by default, and the external monitor on by default. This had the same effect as OpenBox did. This time, however, I could not log into LXDE to fix it, since I was already in LXDE. I was effectively unable to see anything, since the output was being sent to the external monitor, but the monitor was receiving no signal.

Knowing that the settings must be saved somewhere, I decided to look into it. I opened the tty (ctrl+alt+F1), which fortunately runs on the laptop monitor, logged in, and decided to look in the ~/.config directory. I reviewed a couple of files before I decided to open ~/.config/autostart/lxrandr-autostart.desktop

This file has settings to start xrandr. Once I opened this file, it was just a matter of turning off the VGA-0 monitor, and turning on the LVDS monitor, which was turned off. Once I did this, I restarted the computer (sudo shutdown -r now), and I was able to login with a desktop. Then I opened the Monitor Settings again, and set the monitors to show only the external one, and apply the settings, but not save them.

I think I will have to do this every time I turn the computer on, but it may be worth it.

I still need to look for a solution that allows me to have both monitors at the same time, but for now that is not something I want to spend a lot of time on.

Iterating over an HTMLCollection

I have always expressed my lack of interest in jQuery. I don’t like it as a framework, but I like even less the fact that it contributed to the creation of a wave of bloated websites. There are countless of sites that load jQuery just to do a transition, or to hide an object.

jQuery also contributed to the proliferation of plugins that don’t really do anything other than providing eye candy, but don’t improve the overall usability of a site, sometimes they even worsen it. jQuery also created a culture of instantaneous code, where people think everything is as easy as doing $().

Despite all its faults, jQuery did great things. It hid away the complexities of dealing with the DOM, it helped many people enter the world of Javascript, and it demonstrated that there are better ways to do things.

One of the things I like about jQuery is the fact that you can almost effortlessly apply changes to a collection of elements. Think for example, that you had to move all elements that had a certain class name to the left by 10px. Now, lets say you must do it with javascript. With jQuery you would do something like:


$('.className').css('left', '10px');

Compare that to the amount of code you have to use to do the same thing with vanilla js:


var nodes = document.querySelectorAll('.className');
for (var i = 0; nodes[i]; i++) {
  nodes[i].style.left = "10px";
}

That is not too bad, but it is not as simple as the online jQuery code. The for loop is just boilerplate code. There is a better way to do it:


function iterateCollection (collection) {
  return function(f) {
    for(var i = 0; collection[i]; i++) {
      f(collection[i], i);
    }
  }
}

This is a nice little function that will allow you to iterate over a collection of nodes, or an array even, and then it will call a function passing it the current index, and the element at that index. To call it, you simple do this:


iterateCollection(nodes)(function(node, i) {
  node.style.left = "10px";
});

While it may not be as little as the jQuery code, it eliminates the need for the library. Also, the function can be used with other functions to create more interesting patters.

I am currently working on a DOM library that takes advantage of this kind of patter as an implementation of functional programming for DOM manipulation.

Fix it Wrong: the Hyperlink Shortcomings

Catching up with my reading, and trying to free my browser of all those tabs open, I came across an article that covers an interesting problem, and offers a weird solution. This article introduces Sparkicons.

Sparkicons are a proposed solution to a real problem. How many times have you clicked something just to be disappointed with where the link takes you? I have been a victim of this a few times. Some time ago, I was using my tablet, and clicked on the download button of the Aviator Browser home page. I am so used to download buttons taking me to a page where the actual download button exists. For example, the wordpress.org site has a download button that when you click it, it takes you to another page where there is another download button. I don’t download many things from the web, and maybe that is why I have a this wrong idea in my head. But the sites where I download things from make use of this bad pattern that I now think any download button in a homepage is just a link to the download page where the actual download button is.

On Bad Patterns, and Worst Practices

This problem that I have highlights the effects of using bad patterns in Interaction Design. If the people deciding what happens when I click something decided to layout the correct behavior this problem would not exist, and I chose to believe I’m not the only one who has it. This problem extends far beyond download buttons. There is, for example, the issue where many popular download sites have too many download buttons that you don’t know which one is the real one, and which one will just download some virus or scam. This is bad interaction, and UX design, but there are also bad practices that are used in the name of SEO.

In my opinion SEO is one of the worst things that has happened to the web. Sites should be indexed by their importance, not by their clever usage of technology and language. However, sites like google encourage abusive practices. One time I sent a criticism to a popular site regarding their poor chose of wording when creating hyperlinks, even when better words where in the text. For example, they would have something like this:

This article presents the advantages of using modern tools.

and they would put the link on “This article”, and not on “the advantages of using modern tools”. The second set of words is obviously a better choice, but when I pointed this out, I got a response saying that they know that, but they used the first set of words because of SEO. I lost a lot of respect for the site, the editors, and anybody involved in that decision. I decided that if they cared more about SEO than about being explicit to their readers, and using best practices in favor of their readers, I did not want anything to do with them.

Taking Responsibility

Anybody who creates content needs to be responsible for that content. Creating high-quality content should be our ultimate goal. I don’t see any need to do anything more than what wikipedia, and the BBC are doing (reffer to the article about sparkicons linked at the beginning). There is no need to add anything else because the text of the link should be always explicit. I cannot imagine a situation where being explicit is not possible. It is the content creator’s responsibility to make sure that the created content is clear, explicit, and easy to understand. This is what wikipedia, and the BBC are doing. There is no need for any sparkicon, which by the way is just the same idea, but on steroids.

I Think you Need a Button

Another big problem is that we want links to do too much. We use links to link documents together, to download things, to put things in full screen, to create new content, to delete content, to show and hide content, and maybe others that I’m forgetting right now. Links have one job: to link documents. If you need to do something different, then you need something different. For example, to go fullscreen, and to download content, you should be using buttons. We use tools wrong, and then complain that they don’t work well.

The Browser Fault

One thing I don’t understand is why in the world mobile browsers just donwload things. I like desktop browsers, because when you click a download button, they ask you if you want to download the thing, and where you want to put it. This is great. Sometimes you clicked by accident, or the link was miss-leading, or your cat stepped on the click button, or something else happened, but you did not intend to click on that button. That is why browsers should not assume you want to click on it, and download something. This is even more true with mobile devices where you have to touch the screen, and there are many reason why you could touch it without it meaning you want to click on the button to start a download. Browsers are breaking an established flow, and creating one that does not offer any added benefits. I don’t understand this logic.

Finally, while I appreciate the effort that was put into thinking about sparkicons, I don’t think they offer any real benefit over what some websites are already doing. I honestly believe that it all comes down to the same thing I’ve been saying for a long time now, the web technologies are unfixable. We need to start anew considering the current state of things and where technology is going. It is not a matter of adding more sugar on top of a broken model, but rather about letting go of the old , broken model, and create one that suits the current state of technology and that is more future friendly.

CSS Variables, Yet Another Step in the Wrong Direction

From the first time I learned about CSS variables some time ago, I noticed it was a stupid implementation. This is what we get when the people writing the specifications are not one bit close to the real world development scene. How can a person who doesn’t write CSS on a daily basis know what the best way to implement something is. Add to that the fact that variables in CSS are completely useless by nature. However, the “developers” asked for them, and they got them.

CSS variables are still something that lives in the future. They are like an incredibly stupid monster that lives in another dimension, but that has managed to open a portal, and is now showing one of its ugly paws through it. But I’m not the type to mix science fiction with reality, and I don’t usually write in this style, so I’m going to stop now.

Going back to my usual ranting style, let me tell you why CSS variables are stupid, and dangerous. But first, lets take a look at the motivation.

I Want to Feel Like a Big Pants Geek Boy
Or Why CSS Variables

It is my belief that CSS variables come deep from the need of designers to feel like developers. I’m not trying to insult designers here. I have great respect for some of the work that great designers have done, but now that the web has given birth to the front-end wave, there are a lot of designers out there who want to feel like they can call themselves front-end engineers. This is not a good thing. Designers should be proud of being designers simply because their work is amazing. But being geek, nerd, and coder is the fashion now, so many designers want to be that too.

Today I read this on a blog post:

If there is one thing a language needs to qualify as a programming language, it’s variables; they’re incredibly useful, save us a bunch of work and typing, and improve coding all-round.

This is simply a demonstration of both, the need of some designers to feel like they can program, and their lack of knowledge of programming languages. But I’m not going to start attacking people just to make me feel better. I think I should just continue attacking CSS because after all, that is what is ultimately wrong. If we really want to make CSS better, we need to throw the current specs out the window, and start anew.

The Nightmare of CSS Variables

I wanted to have a bit of a better base for my arguments, so I decided to head to the source of the problem. I searched for the W3C specification of CSS variables. It is still an Editor’s Draft, but in this stage we can begin to see some of what is wrong with CSS variables. Take a look at this example, taken from the W3C site:


:root { var-color: blue; }
div { var-color: green; }
#alert { var-color: red; }
* { color: var(color); }

<p>I inherited blue from the root element!</p>
<div>I got green set directly on me!</div>
<div id='alert'>
  While I got red set directly on me!
  <p>I’m red too, because of inheritance!</p>
</div>

I really hope you see what is wrong there, but if you don’t, I’ll give you a hint: the paragraph element can be a different color depending on where it is, event though you specify a “specific” color for all elements. This is because of the stupid implementation of scope.

The scope of the variable is resolved in terms of the location of the element in the HTML structure. What!? This is wrong, and you can go and find as many justifications for this as you want, but it won’t change the fact that this is just wrong. It would have been better to implement namespaces rather than this kind of scope.

This behavior is defined as “cascading variables”. In a sense, it is not even a scope chain. It is a freaking cascade! Why would you want your variable values to cascade? This should be called randoms instead of variables, because the value of the variables will change almost randomly depending on where the element is in the html.

This cascading behavior introduces inconsistency. Inconsistency is enemy of robustness because it creates unexpected behavior. However, CSS variables introduce a whole lot of inconsistency and complexity to an already complex language. The bad thing about this complexity is that the complexity is not in the language itself, but in the way the language has to be written in order to be efficient. In other words, writing complex, hard-to-maintain, CSS is a requirement so much they almost advertise it as a feature.

Who Needs Variables Anyway?

I like to believe there is a better way to write CSS. I’ve been recently experimenting with what I call Subscription Based CSS. It has allowed me to create more consistent behavior, easier-to-maintain CSS, and a smaller code base. Explaining Subscription Based CSS is out of the scope of this entry, but the basic idea is to develop sets of styles, and simply add selectors to them. This eliminates completely the need for variables. Think of this example:


{
color: #bada55;
}

We have defined a color set. Now, whenever you need a certain element to have that text color, you simply add a selector to the rule set. For example, if you want all your h1 elements to have this color, you simply subscribe them:


h1 {
color: #bada55;
}

If you also want elements with the class “badass” to have this color, you subscribe that selector too:


.badass,
h1 {
color: #bada55;
}

There is no need for a variable called var-badass, and there is no unexpected behavior. The .badass elements, and the h1 elements will always have the same color regarding of cascade values.

You can apply this same principle to any CSS property, and you can do more than variable can do. For example, if you want elements to have the badass background color, and white font color for nice contrast, you define that set:


.badass,
h1 {
background-color: #bada55;
color: #fff;
}

This is a much better way to deal with constant values.

F! Semantics

In my early days, I was pro-semantics. Semantics were the hype back then, and I saw a lot of value in that. Semantics rely heavily in class names, and we learned that using class names that described the visual representation of the element was bad. This means that if you have a class like “centered_text” you are doing it wrong. Why? For the sake of semantics, of course.

Nowadays I’m not as big a fan of semantics as I used to be. Class-based semantics are a redundant task that has little added benefit for the end user. They are of great benefit for robots, and automated machines, but we do web for users, not robots. Once you forget semantics, writing subscription based css is really easy.

I don’t think CSS variables will go away. They are just another feature in the web that takes us a bit further from where we should be, and that diverges us a bit more from the direction we should be following, but like everything else, it is up to the developer to use the feature or not. I’m sure they will be loved by many because we tend to see any new feature like a new toy we must use as much as possible. I think we will start seeing CSS frameworks that claim to be the perfect solution for CSS variables, just like it happened with grids. With that in mind, I can safely say that I saw the future, and it was awful.

grumpy cat

Scanning with Canon N1220U on Fedora 18

I needed to scan a document today. Scanning is something I do very rarely, so I don’t need to buy a fancy scanner. I have a Canon N1220U that I got from my father over 6 years ago. I don’t know how long he had it for before passing it on, but it works well. It has decent quality image, and it is not bulky, so I can easily put it away in a little box. I used it a few times back when I was using ubuntu on my Dell laptop. It just worked out of the box, or at least that is what I remember.

However, today, when I tried to used it it would not work. Fedora comes with simple scan, which is the same applications I used in Ubuntu, but simple scan was not detecting the device. I decided to open the console and fire up a search for scan utilities:

yum search scanner

I got back a bunch of results. The promising one was sane-backends-drivers-scanners.x86_64, so I did a sudo yum install, but that reported that the package was already installed, and up to date. There was nothing to do.

I decided to do a quick search, and I found this: https://www.linuxquestions.org/questions/linux-hardware-18/fedora-18-x64-xsane-won%27t-detect-scanner-even-though-sane-find-scanner-does-4175452309/ but I didn’t think it would help so I skipped it and went back to the terminal. I decided to see what packages were available by the sane package, so I typed san and then hit tab twice. I got this list:

sanbox saned sane-find-scanner

I decided to give sane-find-scanner a try. sane was detecting the scanner, so the problem should be somewhere else. I decided to install another package from the list I got when I did the yum search.

sudo yum install xsane.x86_64

This installs the xsane package and the dependency xsane-common. I had tried xsane before, although at the moment I didn’t remember it. xsane is insane. It has lots of options, and getting the document to scan cleanly can be hard, you may need to play around with the contrast, and light settings. Heck, xsane even has histograms!

xsane is great if you are doing some high quality scanning, but if you just want to scan a document to email it, xsane is a bit of an overkill. I decided to give simple scan another try. I opened it again, hit scan, and it worked. Why? I don’t know. It thought maybe something to do with xsane, but it continued working even after xsane and its dependency were uninstalled, so I don’t know what made it work, but I’m glad that it works now.

CSS Hover Intents

Hover intents were the fuzz word for a little while some time ago. The basic idea is that you should not fire a hover event handler as soon as the event happens, because the user may not actually intent to hover over the element, but he might just be rolling the mouse over in order to get somewhere else.

The javascript implementation was simple, involving some king of timer. Someone even created a hover intent jquery plugin. But to me it seems excessive to use Javascript to manage hover intents, specially now that most of our animations are handled by CSS.

A few weeks ago I was thinking about implementing hover intents in CSS. I’m not sure if anybody has come with this patter before, but I had never seen it until I came up with it. The idea is the same as in javascript, but you can implement it in pure CSS.

The “trick” is to take advantage of the transition property of CSS elements. After all, we usually want to do hover intent on animations and transitions, like when we are sliding down a menu, or adding some hover state to an element.

The code is simple:


.selector {
transition: .5s .3s linear;
}

Here we are specifying a transition that should take .5 seconds to complete, but should start with a .3 seconds delay. This effectively creates the hover intent effect.

Look at this demo to see it in action:
http://codepen.io/anon/pen/itvKm

Notice that I made the delay 1 second just to make it more obvious. This has been tested on Google Chrome and Firefox. You can even specify a different delay for the mouse enter, and mouse leave events by re-defining the transition property on the :hover rule with different values.

The Slider Problem

Browsing through the popular items in theme forest, I’ve come to realize that there is a horrible anti-patter out there. I’ve noticed this before, but I didn’t realize the full extent of it until I browsed many different templates. The anti-pattern is image sliders, or slideshows. There is actually nothing wrong with the sliders themselves, the problem comes when they have a dynamic height. What most people do is calculate the height of every slide and re-size the element accordingly. When the element is re-sized, anything that is placed bellow it in the document is pushed down, or pulled up. This is a problem.

Sometimes the slider is not even visible anymore, and you are just reading the content, and all the sudden it moves up or down making it really hard and annoying to read. This is an anti-pattern.

The solution is really simple. Pause the slider when it is obvious the user is not interested in it anymore, like when half of it is not visible anymore. If half of the slider is not visible, then it is safe to assume the user has moved onto something else, and is probably now concentrating on the content bellow the slider.

To solve this problem, I’ve created a jQuery plugin called scrollWatch. It is easy to use. You can call scrollWatch on any element passing a callback to scrollWatch. Every time the window scrolls, the callback is called and an object is passed to it. The object contains some information about the current state of the element, such as the amount of pixels hidden on each direction (top, left, right and bottom), the percentage hidden, the width and height of the element, it’s position on all 4 corners, and other window related information. For now it works only on window scroll, but it could be easily adapted to work for other elements as well.

There are many things that can bone when you have the option to know how much of an element is hidden because of scrolling at all times.

I will release the plugin through git hub at some point this week, stay tuned!

using Declarations in C++

Now that we have a complete understanding of using directives in C++, lets take a look at using declarations. Using declarations are easier to understand, especially now that we’ve gained an understanding of other concepts such as scope, and namespaces.

using declarations serve a similar purpose than using directives: we want to use something that is within a namespace without having to write the fully qualified name every time we want to use it. A using declaration looks like this:

using nsName::entityName;

As you can see, all you do is refer to an entity using its fully qualified name. After this, you can use that entity by calling it by its simple name.

How using Declarations Work

As with using directives, we need to understand what happens when we use a using declaration. We already know that a using directive works by placing everything withing the referred namespace into the closest namespace shared by the referred namespace and the curent scope. using declarations, however, work by placing the referred entity into the current scope. This distinction is important because knowing it will help us determine where to place our using declarations.

A Rule of Thumb

A good rule of thumb when working in C++ is to declare variables close to where they will be used. For example, if a variable will be used in an function, then you should declare it in that function. If it will be used in an if statement, then declare it in that if statement. We can apply the same rule to using declarations because they place the referred entity into the current scope.

This time I won’t go into much detail, because I think that understanding how using declarations work is very easy. However, I do want to show an example of when, and why using declarations coule be problematic. Consider the following code:


namespace myNs {
  int number = 0;
}

int main() {
  int number = 1;
  using myNs::number;
  return 0;
}

If you tried to compile this code, you would get an error. The problem is that when the using declaration tries to move myNs::number into the scope of the main function, it finds that there is already a variable in there that has been declared with the same name.

I want to end this short entry with a few links where you can read some more about real-world instances where using directives and declarations come into play:

http://stackoverflow.com/questions/16152750/using-directive-vs-using-declaration-swap-in-c
http://stackoverflow.com/questions/3039615/exceptional-cbug
http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

using Directives by Example

A deep understanding of the features of a programming language is key in order to become a good programmer. With that philosophy in mind, lets take a closer look at using directives in C++.

Last time we said that:

A using directive works by placing everything belonging to the referred namespace inside the closest namespace shared by the referred namespace and the current scope.

The Referred Namespaces and the Current Scope

In order to better understand what that sentence means, lets take a look at what the current scope and the referred namespace are. Consider the following code:


int main() {
  using namespace std;
}

This code doesn’t do anything, but it will serve well for our purpose. In the using directive, the referred namespace is std. This is the namespace that we want to use. Note that you can use more than one using directive to refer different namespaces. When the main function executes, we enter into the scope of the main function, and that becomes the current scope. This means that the current scope is the scope of the block where the using directive is.

Now, you should be able to understand a little bit better what I meant. However, I’m going to go the extra mile here and show some examples that, both, demonstrate that the statement is true, and clarify the statement even further.

The Examples

Consider the following code:


#include 
int number = 0;

namespace outer {
  int number = 1;
  namespace inner_one {
    int number = 2;
  }
  namespace inner_two {
    int number = 3;
  }
}

int main() {
  return 0;
}

Here we have a namespace outer which contains a variable declaration, and two more namespaces. Each of these nested namespaces contains a variable declaration as well. There is also a variable defined in the global scope, outside of any namespace. All variables share the same name, but since they are in different scope, and more importantly, in different namespaces, they are all different entities. This example doesn’t do anything, and if you compile this program and run it, it won’t do anything. This is just our basic code. We will use this for all of our examples.

Lets first use a using directive that applies to the whole document:


#include 
int number = 0;

namespace outer {
  int number = 1;
  namespace inner_one {
    int number = 2;
  }
  namespace inner_two {
    int number = 3;
  }
}
using namespace outer;

int main() {
  std::cout << number;
  return 0;
}

Notice we’ve also added a cout statement. We are using the qualified name of cout so that we don’t have to use a using directive. I’m doing this so that the examples are not confusing.

If you try to compile that code you will get an error. Depending on the compiler you are using, the error may be different. In the g++ compiler, the error says “reference to ‘number’ is ambiguous”, and then it gives the line number where the two candidates are: 2, and 5. It also gives me the fully qualified names of the two candidates: int number, and int outer::number.

What does it mean anyway? The message is basically telling us that there are two different number variables, and that there is no way to know which one you mean. At first sight you would think that this happens because we have the using directive in the global scope, so when the members of outer are “imported” to be used without specifying their fully qualified name, they come to the global scope, and that is where the conflict happens. Following this logic, we would think that placing the using directive in the main function would solve the problem, since the members of the referred namespace would be placed in the scope of the main function, thus preventing the variables from conflicting with each other:


#include 
int number = 0;

namespace outer {
  int number = 1;
  namespace inner_one {
    int number = 2;
  }
  namespace inner_two {
    int number = 3;
  }
}

int main() {
  using namespace outer;
  std::cout << number;
  return 0;
}

If you do this, you may be surprised when you try to compile the program to see the same error you were seeing before. It made no difference. This means, then, that the members of the referred namespaces are not being placed in the current scope, but if they don’t go into the current scope, where do they go? As I said before, they go into the namespace share between the referred namespace and the current scope.

The Global Namespace

Lets take a break from the examples, and talk about the global namespace. Everything in C++ is in a namespace, even if you don’t explicitly put it there. If you don’t specify a namespace, things go into the global namepsace, which is referred to as ::. This means that the fully qualified name of the variable defined in the global scope (int number = 0) is ::number.

In our previous example, the closest shared namespace between the referred namespace and the current scope is the global namespace, so all the members of the referred namespace go into the global namespace, but in the global namespace there is already a variable named number, thus the conflict of ambiguity.

But, how do we know that everything in fact goes into the closest namespace rather than the global namepsace all the time? We can prove that quite easily:


#include 
int number = 0;

namespace outer {
  int number = 1;
  namespace inner_one {
    int number = 2;
  }
  namespace inner_two {
    int func() {
      using namespace inner_one;
      return number;
    }
  }
}

int main() {
  std::cout << outer::inner_two::func();
  return 0;
}

Here we have created a function in inner_two. We also removed the variable declaration, otherwise name lookup would find that variable first, and use it without giving us a chance to get to the ambiguous definitions.

If you try to compile this program you will see the same ambiguity problem, but this time the candidates are different: outer::number and outer::inner_one::number. This effectively demonstrates that the members of the referred namespace were placed in outer, which is the closest share namespace, rather than in the global space.

Getting Real

Why do conceptual things like this matter? Well, it all comes down to understanding of the language. The better you understand a language, the better prepared you are to write programs that have lesser chances of doing unexpected things. There are real life problems that derive from a poor understanding of the features of a language, and these are some of the worst kind of problems, because if you don’t understand how something works, you could be thinking that it works in a different way, and this will make it really hard to fix bugs because you cannot see why something is not working.

This is not just trivia knowledge. In fact, chances are no one will ever ask you to explain what a using directive does or how it works. This is knowledge that will prevent you from making mistakes. Knowing where to put something, like a using directive or a variable declaration within your code is essential in order to create good programs.

Next time, we will take a look at using declarations, how they work, and why you may want to use them in favor of using directive in some instances.

Using Directives in C++

Last time I talked about namespaces in C++ and I touched a little on the subject of using directives, and using declarations. Since I think it is very important to understand the difference between the two, I’ve decided to talk about them. Before you continue, however, you need to really have understood the concepts that we talked about before, specially those of namespaces, and scope, as well as how name resolution works.

Scope — A Second Look

Lets give scope a second look. We’ve already said that the scope of a variable is everywhere that variable is available, or visible. This time, we will talk about variables, but you should assume that this applies to all kinds of entities that have an identifier, such as functions, constants, and classes.

C++ has block scope. This means that a new scope is defined for every block of code. A block of code is usually delimited by curly braces. Following this logic, we can see that if you create an if statement, everything in the if branch is in its own scope, and if you have an else branch, everything in it is in its own scope as well. If you define a function, that function creates its own scope, and everything inside that function is in the scope of that function.

It is really important to understand this, because scope will usually determine where the best place to define a variable is. For example, if you want a variable to be accessible only from withing a function, then the best place to define that variable is inside the function. Scope will prevent the variable from being accessed from outside the function.

Another example would be if you want to create a variable and work with it only if some condition is met. In this case, the best place to define that variable is inside the if statement. However, if you want to have a variable and change its value depending on a certain condition being met, then you would have to define the variable outside of the if statement, and only change its value if the condition is met. This way you can access the variable from outside the if statement once its value has been changed.

The Scope Chain

We didn’t talk about the scope chain last time, and it is time we talk about it. As blocks get nested, scopes get nested as well, and this forms a scope chain. Think for example of a function that has an if statement inside of it:


int main() {
  if (1 == 1) {
    //do something here.
  }
}

In this code we have two different levels of scope. One is the scope defined by the main function, and the other one is define by the block of the if statement. The scope of the if statement is inside of that of the main function. We can say that the scope of the if statement is bellow the scope of the function in the scope chain.

In most programming languages you can move up the scope chain, but not downwards.This means that the code in the if statement has access to anything defined before the if statement in the main function. However, nothing in the main function can access anything defined inside the if statement unless it is also in the if statement. Lets take a look at some examples:


int main() {
  int number = 1;
  if (1 == 1) {
    int if_number = 2
  }
  cout << number << endl;
}

Note that I’ve omitted some boilerplate code here, like the inclusion of the iostream header, as well as the return statement of the main function.

In this example, cout can access the variable number because it was defined in the same scope, that of the main function. Now take a look at the next example:


int number = 1;
int main() {
  if (1 == 1) {
    int if_number = 2
  }
  cout << number << endl;
}

In this example, number was defined outside of the scope of the main function, but cout can still navigate up the scope chain and have access to the number variable. Now, consider the following:


int number = 1;
int main() {
  if (1 == 1) {
    int if_number = 2
  }
  cout << if_number << endl;
}

Here, there is an problem. cout is now trying to access if_number which was defined in the scope of the if statement. cout cannot navigate down the scope chain, therefore it does not have access to the if_number variable. Now consider this example:


int number = 1;
int main() {
  if (1 == 1) {
    int if_number = 2
  }
  if (2 == 2) {
    cout << if_number << endl;
  }
}

In this example, it looks like if cout had access to the if_number variable, because it is defined up the scope chain. However, that is not the case. When name lookup starts, it goes up the scope chain, to the scope of the main function, however, if we wanted to access the variable, we would have to go down into the scope of the if statement, and that is not possible.

The using Directive

Now that we have a better understanding of scope, lets look at the using directive.

A using directive is a way to specify that we are going to be accessing members contained within a namespace using only their name, rather than their fully qualified names, which would include the namespace as well as the name. Consider this:


namespace myNs {
  int myNumber = 9001; // myNumber is over 9000!
}

The name of the variable in this case is “myNumber”, and its fully qualified name is “myNs::myNumber”.

By using the using directive using namespace myNs we can refer to the variable by its name without specifying the namespace that it belongs to.

How does this work anyway?

A using directive works by placing everything belonging to the referred namespace inside the closest namespace shared by the referred namespace and the current scope. Good luck understanding what that means…

But if you don’t understand it, don’t worry. I will explain it by example in my next post.