Friday, June 30, 2017

iOS UI best practices



Apple always has, through every one of its systems and platforms, made a major focus on interface design and user experience, and its users have come to expect it. So, if you want your Apps to succeed in the App Store or just make a great iOS App in general, this definitely is one of the key areas to concentrate on. Luckily, Apple has provided some general guidelines on how to design a good interface, and here we will go over the most important of them and provide some examples at the end to complete this post. Everything goes with the principle of “simple is better” and being minimalist, so even if some things seem kinda evident, remember that the secret is in the basics.

General design

There are a couple aspects of an App that any mobile developer should know before starting to even think about coding and designing. Users will most likely decide if they like your App or not after just a couple seconds, and every little visual aspect will influence this decision. Mobile users are usually really temperamental with the Apps they try out, uninstalling them just according to their first impression, so you need to make it count.
Knowing this, the first screen is usually one of the key points in your App you want to focus on. As a general rule, the home screen should guide the user to how he should use the App, showing the most important information and giving the user options to go to almost anywhere in your App in an instant. Following this, intro screens that just serve a purpose to say what the App name and provide a button to continue do not follow Apple good practices. The user already knows which App is the one they opened, and just giving them the obligation to go through one more screen and one more button press to just start using the Application is not a good idea. Remember that they will see this screen every time they open it, especially the first one, and you do not want their first opinion to be “how annoying this is”.
Another aspect of design that has to be kept in mind is how or if you should prompt the user to rate your App. As a general rule, prompting the user to rate your App is a bad idea. Developers usually do this on impulse, since if you ask the user to do it you will most likely get more rates on the store, and this can, in turn, improve its position, but that is just one side of the coin. Remember that your user first wants to use your App for one purpose, and that is not to rate it. If the user is constantly asked to rate an Application, he will most likely start getting angry with this message, or just ignoring it completely depending on how intrusive it is. And, in the worst case, you do not want an angry user to be the one that reviews your App.
 
Stylish choices are good (and sometimes necessary) for some Apps, but remember that it should not in any way hinder the core purpose of your App. If you do “something” that makes your App look a little bit nicer, but it makes the App a little harder to use or a little more frustrating, it probably is not the best of ideas. 
Another aspect of the general design is to adjust to as many conventions as possible, especially when related to functionality. Apple provides many types of buttons and button images to guide the user to what each button does, and developers should really try to adjust to this. For example, if the users see a trash icon, he will assume this is for a delete functionality, as well as if he sees a curved arrow pointing to the left it most likely that corresponds to a “reply” action. UI is the best way to guide the user in your App, and a UI design that does this in the best way is one that follows UI conventions.

Layout

Chances are you will want to show many options, test, or possible actions on one screen. However, this can potentially be confusing for your final user if it is not organized properly. Luckily for us, Apple already fixes some of this issues by providing controllers and some minor restrictions to UI elements (like how the Tab Bar is at the bottom), ensuring they are used in a common and structured way.
However, many other options are left for us developers and designers, and a little thinking on the general layout and positioning of elements can go a long way.

Structure

To start with the layout, it is important to understand that screen space is one of the most important assets the UI designer has and should be used thoughtfully. This does not mean you should just fill the entire screen or leave everything in one corner. Empty or background space is an indispensable tool for design, and almost a necessity for the user to not be overwhelmed with information. 
Following this concept, things that just take up space for the sake of being there (like borders to your application) should be avoided. There may be some exceptions to this general rule, but unless you have a really good reason you should follow it. Although users like to see an appealing design and feel comfortable, it can annoy them to focus on a smaller screen than the one they could use if that border was not there. A clean appearance is usually the best appearance. 
Another aspect that should be considered is where the different elements are positioned inside the screen. The first rule here is a somewhat easy one but sometimes forgotten in favor of stylish design. Always remember to highlight the most important functionality. When a user reaches a screen in your App, chances are you have a pretty good idea as the designer to what he wants to do or where he wants to go next. As such, the thing that is most likely to be needed should be at the top and highlighted with some color, image or with another method.
Imagine you have a really long scroll screen, and the option you almost always want to press is at the bottom. The first time you see this screen you will need to read everything before finding what you were looking for, and all the following times you need to keep scrolling to the bottom even if you know exactly what you want. Design should follow the desired functionality, and not the other way round.

Buttons

Let’s stop a little bit now with one of the most common elements in UI, buttons. Buttons are almost a necessity for development if we want the user to select when he is ready to perform a certain action or follow a determined flow. How the buttons visual can vary from App to App, maintaining the general Application aesthetic, but the important part is that it needs to be focused on its purpose. Buttons are for being pressed, and therefore should be easy to press. This section also applies to any other UI element that is meant to be pressed.
 
In order to achieve this, there are a couple of basic rules that should be followed:
  • Buttons should be big enough for the user to press them without missing. Buttons that are too small tend to confuse the user after they try to press them and miss them, not knowing if their touch registered.
  • Make sure buttons have some distance between themselves. Having many buttons next to each other can generate problems if the user misses, forcing the App to do something other than what the user intended.
  • Buttons need to be evident. If you make a custom button and the user does not recognize it is a button, it was definitely not a good design choice.

Fonts

The text is likely to be prominent in your App since it is one of the most effective tools a designer has to convey meaning and guiding the user through all options and information. Being such a vital (and somewhat simple) tool, it is important it is as refined as possible.
Some key aspects to keep in mind about fonts are the following:
  • Think about the size of the text in your App. Too small font sizes should be avoided, to make sure the user is able to read all text comfortably (Apple suggests a size of at least 11px).
  • Be careful when considering font color. A key color is recommended, used in your App to draw attention to certain areas. If too many are used the user may be overwhelmed and the attention will be divided into many different areas instead of focused on one thing, which would be the thing the user wants to see.
  • Do not use many types of fonts in any App, except for very specific reasons. Using many types of fonts will confuse the user, and direct his attention almost randomly through each screen. Also, the user will need to adjust every time the font changes to understand it. This is likely to cause frustration and rejection towards the App.
 
If the user feels comfortable reading what you have to say in your App, it is much more likely he will keep using it for longer. Obviously, no one is going to use an Application just because it has some nice fonts, but someone can easily uninstall it if he finds the visually shocking. Remember that mobile users are prone to delete an App after just a couple of seconds if they do not find it nice.

Feedback

The last aspect we will cover in this post is the importance of notifying the user about what the Application is doing in the background. Mobile applications have many reasons to take some time before finishing a process. Motives can range from fetching data remotely to heavy algorithms run on not so powerful devices. This cannot be always avoided, but it may not be so bad for the final user if done correctly.
The first thing is knowing approximately how much time a given process will take. If it is an immediate action, and the user will be immediately informed that the action ended (like with navigating to another screen or removing a field) this is not so important. In fact, informing him something more in this cases can be actually confusing for them. However, if the action is quick but does not give the user feedback in itself (like adding data internally), the user should be informed in some way, like with a message, that the action has been completed. If not, the user may try doing the same action again, maybe giving more problems than intended in the long run.
On other actions that take a couple more seconds, a little more planning is in order. Hiding buttons after the user has clicked them is a common strategy, as well as showing the default Activity Indicator from Apple. This informs the user immediately that the App has received his input, and is working accordingly. The animation of the Activity Indicator (or any other indication you wish to give them) is key here, since otherwise, the user may think the App has frozen.
If the wait for the user is especially long, more powerful actions should be taken. Leaving space for progress bars and finding a way to inform the user before he starts the lengthy process is vital. The user wants to be informed that he will have to wait in order to decide if he wants to do what the App allows him to. If this is not the case, you run the risk of the user closing the Application, maybe even thinking that the App is broken or buggy.
One other aspect that is important to mention when talking about how to give feedback to the user, is that feedback should not only be given to this kind of processes. A way to clearly indicate the user that an option has been selected or that certain mode is in effect is also a necessity. A good example of this is the tab bars that come natively with iOS since they have a different color and icons for when they are selected as opposed to when they are not.

Conclusion

This was just some of the many recommendations Apple provides for designers, but some of the most important of them. Many of them may be evident to designers, especially to designers with experience, but can be really disastrous if not applied correctly. If you want to see the difference that it makes to follow these or nor, please check our GitHub repository for iOS UI Best Practices.

References

iOS Design guidelines: UI Design Do’s and Don’ts
Our post of Mobile Best Practices
GitHub link: iOS best practices
Example code: iOS-UI-best-practices on our GitHub

How to deploy a django project with Apache

In this guide, we will talk about how to deploy a Django project using Apache and its module, mod_wsgi. This two have a main role in the deploying process.
We will handle the client requests using Apache, which will be the one of delegating the requests that need logic to the Django app through mod_wsgi.

Setting a virtual environment

First, we will install pip
$ sudo easy_install pip
Next, we need to install the virtualenv command to create these environments.
$ sudo pip install virtualenv
When virtualenv gets installed we can create a Python virtual environment by typing:
$ virtualenv exampleve
Then, to be able to use it, we will have to activate it:
$ source exampleve/bin/activate
Once we activate our virtual environment we are ready to add our Django project. All the dependencies we install will be located in our "exampleve" folder.

Setting static files directives

Once our Django project is created, we need to specify the directory for both static and media files on the settings project and then generate them. First, we are going to specify the directory where the files are going to be generated. We will do that by editing the settings.py file from our project as follows:
import os


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Next, we are going to collect our static files by typing the following command:
$ python manage.py collectstatic
A folder with the static files should show up on our project

Configuring mod_wsgi

Once we have finished developing Django project we are ready to deploy it. First, we need to install the apache module mod_wsgi. If you are on MAC, be sure that XCode is updated. If you are on Linux (in this guide we show how to do it specifically in Debian distributions), be sure that apache is installed. You can install it by typing the following command:
Linux:
sudo apt-get update & sudo apt-get install apache2
Then we are going to install mod_wsgi. We will use pip for that:
$ sudo pip install mod_wsgi
Once it gets installed we will need to include it into apache’s modules by manually editing the httpd.conf file located in /etc/apache2/httpd.conf.
To do that we are going to run:
mod_wsgi-express module-location
Take the path that outputs and modify Apache configuration (httpd.conf) so it has a LoadModule line for wsgi_module with that path. Here is an example of the line we have to include:
LoadModule wsgi_module /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
Then we can check if mod_wsgi is successfully loaded by looking into Apache's loaded modules:
$ apachectl -t -D DUMP_MODULES | grep wsgi
wsgi_module should show up on the output.
Once we get mod_wsgi installed and activated, we have to take a look at our Apache server’s httpd.conf file. At the end of the file, we can see that it imports all the .conf files from “/etc/apache2/other/”. To take advantage of this, we will create a new file there, which can be called django.conf for example, with the following configuration:
WSGIScriptAlias / /path/to/wsgi.py
 
WSGIDaemonProcess example python-home=/path/to/virtualenviroment/ python-path=/path/to/project/
WSGIProcessGroup example

<directory>
     <files wsgi.py="">
        Require all granted
     </files>
</directory>   

   Alias "/static/" "/Users/andres/Desktop/example/static/"

   <directory>
     Require all granted
     Options +Indexes
   </directory>
  • WSGIScriptAlias indicates the path to the directory to our wsgi.py file on our Django project
  • WSGIDaemonProcess indicates the path to our virtual environment and the path to our project. Both grouped under the WSGIProcessGroup name
Finally, we just have to restart the apache server one more time to implement the changes made and that’s it!
$ sudo apachectl restart

Congratulations! 

Everything should be set now. Go to see your Django project working.
Mountain View
If you want a sample project you can check the link below where you have the default Django project.

Python unittest


Unit testing is an automated testing technique used to check small pieces of a project, usually called units. These units are defined by the developer so it can be from a tiny function to a whole functionality. However, there are some basic rules that every single test should follow:
  1. It has to be able to run independently.
  2. It has to run on memory
  3. It has to be consistent (always returns the same result for the same input)
  4. It should be fast
Those rules must be fulfilled to be able to run any unit at any time since it is needed to run the tests properly.
The basic idea of unit testing is to run the test every time the developer makes substantial changes to the code. By doing this you will know if a unit is still working or not after those changes, reducing the time and effort spent on bug fixing.

Unittest

Running simple tests

Unittest is a standard python library, which allows you to define and run tests in an easy way. Let’s start with a very simple example:
from unittest import TestCase, main


class TestBasicArithmeticMethods(TestCase):

    def test_add(self):
        self.assertEqual(2 + 2, 4)

    def test_subtract(self):
        self.assertEqual(3 - 2, 1)

    def test_multiply(self):
        self.assertEqual(3 * 3, 9)

    def test_equal(self):
        self.assertTrue(3 == 3)
        self.assertFalse(2 == 9)

if __name__ == '__main__':
    main()
First things first, what is defined here is a test case, which is the smallest part which can be defined using unittest. The only thing you have to do is defining unittest.TestCase as a superclass.
A test case will look for any method starting with “test_” and run it when you run the test case. Also, if you want to define only one test you can override the runTest method, which is the simplest way to do it.
The "if" statement at the bottom runs the tests every time you compile the code, which is very useful to check that recently added code does not change the correct functionality, as it was mentioned in the introduction.

Loading information

These tests are really simple and don’t need additional information to work, but in some cases, you need to load data from disk. Loading information every time you need it is inefficient and, as it was said before, the tests should run fast.
For that matter, unittest implement the setUp and tearDown methods, which allows you to load information before the tests, and then erase it after they are executed. Here you have an example:
from unittest import TestCase, main

from complex import Complex



class TestComplexArithmetic(TestCase):

    def setUp(self):
        self.zero = Complex()

    def test_add_complex(self):
        one_onei = Complex(1, 1)
        result = one_onei + self.zero
        self.assertEqual(result.r, 1)
        self.assertEqual(result.i, 1)

    def test_sub_complex(self):
        one_onei = Complex(1, 1)
        result = self.zero - one_onei
        self.assertEqual(result.r, -1)
        self.assertEqual(result.i, -1)

    def tearDown(self):
        del self.zero
As you can see here, the setUp method defines a private attribute called zero, which is used on all of the test cases. Then, that value is deleted after all the test cases are finished.
In this case, the zero value could be defined in every case because it isn’t a time-consuming operation, it is just added as an example. In general, in the setUp method, you will make queries to a database or pre-process information. Then, it will delete that information on the tearDown method to avoid filling the memory up with unnecessary data.

Skipping tests

Sometimes it is necessary to skip some tests after they are checked, for example, if they take a lot of resources, or if they are not supported by older libraries.
In that cases, you can use the unittest decorators skip and skipIf. The first decorator receives optional parameters only, where the most important is the message shown when the test is skipped. The second one needs a boolean value to check if the test is skipped or not, and then optionally the message. Let’s see an example:
from unittest import TestCase, skip, skipIf

from complex import Complex


class TestComplexArithmetic(TestCase):

    def setUp(self):
        self.zero = Complex()

    @skip("Sure that this is correct, and will never change")
    def test_default_complex_value(self):
        self.assertEqual(self.zero.r, 0)
        self.assertEqual(self.zero.i, 0)

    @skipIf(Complex.__version__ < (1, 1), "Not supported by this library")
    def test_equal_complex(self):
        zero = Complex()
        one = Complex(1)
        self.assertTrue(zero == self.zero)
        self.assertFalse(self.zero == one)

    def tearDown(self):
        del self.zero
On this example, you can see that the first test is always skipped with the skip decorator, which is used in general for time-consuming tests that have already been passed. Then the second test is skipped for older versions of the library, very useful when you use libraries in development or different libraries depending on the virtual environment.
Congratulations! You now have all the tools to do unit testing on your Python projects.
You can check a sample project here.

Monday, June 26, 2017

Getting started with React

  Building reusable components with React


React creates components that render themselves using their own properties (props) and states (state). Using these components you can create reusable, robust and dynamic state elements for your HTML.


Visuals

The first thing you would want to do is create a mock of the screen you want to build. From here you can start by drawing boxes around every component and sub-component you think you may need. The more you play around with React the better you will become at identifying what is a component and the best hierarchy they should follow.

I single out 6 components:   
  • FilterablePlayersTable: contains the entirety of the example
  • PlayerTable: renders the table
  • PlayerRow: renders each row of the table
  • SearchArea: receives all user input
  • FilterRace: area that contains the Race filter check boxes
  • FilterRaceCheckbox: the checkbox for filtering by race

The hierarchy would look something like this:


  • FilterablePlayersTable (blue)
    • PlayerTable (green)
      • PlayerRow (teal)
    • SearchArea (yellow)
      • FilterRace (orange)
        • FilterRaceCheckbox (pink)
You could make a case that the table headers could be their own component if we wanted to, for example, order by each column on click. For this basic example, I won’t be doing that. By the end of this post, you should be able to add that functionality on your own, if you feel like it.
Now that I have the component hierarchy, it’s time to build the initial static version of the app. For now, I just want to render the components. As React docs say: building a static version requires a lot of typing and no thinking, and adding interactivity requires a lot of thinking and not a lot of typing.
For the table, I’ll use Jack Rugile’s style, because it looks cool. Except with no blur effect on hover.
You can start building top-down or bottom-up. This means starting with the highest hierarchy component (FilterablePlayersTable) or starting by the lowest hierarchy component (PlayerRow or FilterRaceCheckbox).
I prefer to build bottom-up, as every new component depends on the one just created before it and you can easily write tests for each individual component.
As each React.Component renders itself, each will have its own render() method. This is where we put the HTML code that the component will have on the page. The way React works you can render common HTML stuff, like divs, or you can render other React components.
Once the components have their proper render methods, the general outlook of the app is ready. All changes we make from here on out will not alter this structure, only improve it.
See the Pen UI DotaCraft React Example by Ferdinand (@ferdibranch) on CodePen.
React is so good at reusing components that you can easily add new stuff with minimal effort.
For example, try editing this CodePen. Go to the hard coded array RACES that represents the server input. Now try adding a new String to the array. Once the Pen re-compiles you will see that a new checkbox has been created with the value you just added. React magic.

Functionality

Now that we have working visuals, it’s time to work on the functionality.
React uses two main things: props and states. Props can be passed down to child components and are usually used for rendering specific values, like data on a table row.
In this case, each row will render a specific Player from the JSON we receive so this prop will have to be passed down to PlayerTable, where I can iterate over the Players and create a PlayerRow for each and every one of them.
These props are immutable. The only time a Player’s data will change is when a new JSON array is received.
For changing values, we use “states”. In this case, the components that will be changing over time are the filters. The table will change according to the filter’s states, so the actual state will have to be saved on the highest shared parent (in this case FilterablePlayersTable) so that it can be passed down from the check boxes to the table.
What I want to do is filter the table by name with the input text field and filter the table by race when a race check box is changed.
To achieve this I will have to bind a function to a prop. React lets me do this. So now I bind a function that sets a prop of the SearchArea component as the input of the text field to the onChange event of the HTML Input element. Remember when I said that props were not supposed to change? The exception is when you need to pass the value to a parent. On the parent component, I can create a function that handles the change in state and assign it to the prop I just changed in the SearchArea. I can just keep chaining props and functions until I reach the shared parent component needed to pass down the state to the table.
For the reverse path, I send down the state to the child components until I reach the table.
On the render method, I apply the logic to filter the table according to the state I receive.  
See the Pen DotaCraft React Example by Ferdinand (@ferdibranch) on CodePen.
And there we go! All components are rendered and functional. Try adding a new Race to the initial input and add a new entry to the players with that race. You will see that the checkbox filter works perfectly.
Next time I’ll review how to integrate this component oriented front end to some backend framework.

References