IntelliJ / Adroid Studio / CLion / GoLand / PyCharm / PHPStorm keymap shortcuts I can’t live without

Download settings.jar (Import with `File -> Import Settings`)

I got to IntelliJ after years of using Emacs and Eclipse. Here’s how my keymap looks now that I work with Jetbrains tools, these are the keyboard shortcuts I can’t live without as a programmer.

 

Legend (Mac keyboard)
⌘ Command
⇧ Shift

⌘1 Show Intent Actions (Things like assign to local variable)
⌘- Decrease font size
⌘= Increase font size
⌘0 Reset font size
⌘↓ Scroll to botom
⌘↑ Scroll to top
⌘f Find in text
⌘. Find next highlighted error
^⇧F Find in path (searches in all files, like a grep)
⌘⇧G Find Usages (Find all Occurrences of selected symbol [variable, method, class, identifier])
⌘I Show current function/method parameter info
F3 Jump to source (go inside function’s code)
⌘E Show list of recent files
⌘B Build
⌘L Jump to line number
⌘[ Back
⌘] Forward
⌘T Show implementations of an interface.
⌘⇧F Format (selected) code
⌘⇧O Organize/Optimize imports
⌘⌥R Rename current symbol
^K Kill line
⌘D Duplicate line
Ctrl+G on selected token – repeats selection and enables multiple cursors
Alt+Up | Alt+Down – Move the current line up or down

Debugger shortcuts
F5 Step Into
F6 Step Over
F7 Step Out
F9 Resume Program

^K Cut up to Line End. (Deletes everything to the right of where the text cursor or caret is)

How to create a list that holds different object types using `void*` in C.

I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out.

In this exercise I store elements of different types in a forward linked list.
In order to know what to dereference as I iterate through the list’s elements, I’ve put a “.type” field, which has an int value representing the type of the object stored.

The “.value” is simply a void*, which lets me store a pointer of any kind, and it works pretty well.

Here’s the code for your enjoyment, I hope this is useful to C apprentices.

The example shows how you can store native types like int, or more complex char* or even a struct person* (which is the more useful probably to your purposes)

It’s a good exercise to see the uses of the “address of” operator “&”, which is used to initialize pointers (the ‘&’ can also be used differently to create references, which I call in my mind as ‘aliases’, but this is not shown in this example)

I also play with a not so popular syntax to access a pointer’s sub-fields:

(*myPointer).structField == myPointer->structField

to teach you that the -> is a short hand for dereferencing a pointer and accessing one of its fields.

//                                                                                                                                                                                          
// An exercise to play with a struct that stores anything using a void* field.                                                                                                              
//                                                                                                                                                                                          

#include <stdio.h>

#define TRUE 1

int TYPE_INT = 0;
int TYPE_STRING = 1;
int TYPE_BOOLEAN = 2;
int TYPE_PERSON = 3;

struct node {
  struct node* next;
  int type;
  void* value;
};

struct person {
  char* name;
  int age;
};

int main(int args, char **argv) {

  struct person aPerson;
  aPerson.name = "Angel";
  aPerson.age = 35;

  // Define a linked list of objects.                                                                                                                                                       
  // We use that .type field to know what we're dealing                                                                                                                                     
  // with on every iteration. On .value we store our values.                                                                                                                                
  struct node nodes[] = {
    { .next = &nodes[1], .type = TYPE_INT    , .value=1                   },
    { .next = &nodes[2], .type = TYPE_STRING , .value="anyfing, anyfing!" },
    { .next = &nodes[3], .type = TYPE_PERSON , .value=&aPerson            },
    { .next = NULL     , .type = TYPE_BOOLEAN, .value=TRUE                }
  };

  // We iterate through the list                                                                                                                                                            
  for ( struct node *currentNode = &nodes[0]; currentNode;  currentNode = currentNode->next) {
    int currentType = (*currentNode).type;
    if (currentType == TYPE_INT) {
      printf("%s: %dn", "- INTEGER", (*currentNode).value); // just playing with syntax, same as currentNode->value                                                                        
    } else if (currentType == TYPE_STRING) {
      printf("%s: %sn", "- STRING", currentNode->value);
    } else if (currentType == TYPE_BOOLEAN) {
      printf("%s: %dn", "- BOOLEAN (true:1, false:0)", currentNode->value);
    } else if (currentType == TYPE_PERSON) {
        // since we're using void*, we end up with a pointer to struct person, which we *dereference                                                                                        
        // into a struct in the stack.                                                                                                                                                      
        struct person currentPerson = *(struct person*) currentNode->value;
        printf("%s: %s (%d)n","- TYPE_PERSON", currentPerson.name, currentPerson.age);
      }
  }

    return 0;
}

The output is this:

- INTEGER: 1
- STRING: anyfing, anyfing!
- TYPE_PERSON: Angel (35)
- BOOLEAN (true:1, false:0): 1

Top Eclipse (IDE) features I can’t live without

(If you are in Windows, replace “Cmd” for “Ctrl”, and “Option” for “Alt”)

Cmd + 1: Create variables out of function’s outputs, get suggestions to fix issues.

“Shift + Cmd + T”: Open Type.

“Shift + Cmd + R”: Open Resource.

Select element and press “Option + Cmd + R” to rename a class, variable, method, the refactor will be performed throughout the entire project flawlessly.

Select element and press “Cmd + T”: Show Type Hierarchy, great to know what classes implement an interface, or what classes extend an abstract class.

5 Object Oriented Programming Principles learned during the last 15 years

It was about 15 years ago when I first created my first class.

I went from thinking of Object Oriented programming as this awesome paradigm I should know about, I remember having all these mental models of what objects where and learning all this new vocabulary that I really didn’t fully grasp until years later when I was designing and implementing bigger more complex systems.

At first I remember looking at objects as a collection of functions that kept a common reference to keep internal states and missing out on all the great features of inheritance and abstract classes. Looking at “interfaces” and using them like a recipe without really knowing their true power, I look at the past and I was so limited, hopefully I’ll look at this post 15 years from now and think the same.

There’s lots of books out there on best programming practices you should follow, on this short post I’ll share with you 6 principles that I follow that I promise you will make your code behave really well, less bug prone, simple and elegant when it comes to Object Oriented design. This advice will probably apply better if you code in a language like Java or C#, I’m not sure if you can say these principles will apply 100% to other OO languages (for instance those that allow multiple inheritance)

1. DRY principle.
This is one of the most preached ones, and I will also preach it. DO NOT REPEAT YOURSELF. Really, don’t. It ALWAYS comes to bite you in the ass if you have repeated code. Only repeat yourself if it’s too hard to not do so or if you’re absolutely sure that you won’t repeat yourself a third time, but I promise you that third time will come if it’s not for you for the next guy maintaining that code.

The obvious benefit of not repeating yourself is that you get to maintain code only in one place, the added benefit will be that your code will almost start being written by itself like a perfect equation as it grows. DRY code will be reusable, maintainable and the other principles I’ll talk about are related to the DRY principle in one way or another.

2. Keep the scope at the minimum, be as private as possible.

Keep your variables as close to your local scope as possible. This will save you many headaches, will protect you from bugs in logic because you did something to a variable in place where it shouldn’t have been in the first place, and it will keep things simpler.

This also tells you that your classes should expose as little as possible. Keep your variables local, if they can’t be local, try to keep them as private members, if they have to be used by extending classes keep them private, only use public when you really know it’s ok to make something public and that nobody is going to break the behavior of your object if they play with things at any point in time.

Keeping scope at a minimum can also prevent issues on longer lived objects like singletons that might be accessed by different objects. If you abuse the use of object properties you could have one object changing the internal state of the object while another tries to do something and you’ll get unexpected behavior, this tends to happen a lot in multithreaded environments where programmers are not careful and forget objects might be accessed by different threads/clients at the same time, tight scopes will protect you.

3. Be functional
Sometimes you’ll be tempted to be lazy and not pass parameters on a method and think that you’re so clever by changing an internal property of an object so that another function in the object will then get it. Big mistake buddy. This can be equivalent to that advice from functional programming languages where you’re told that using global variables are a bad idea.
Yes, we have object properties for several reasons, but if the logic of a method depends on the state of a variable, you might as well be explicit and pass it in the method.

This is in a way related to keeping scope at the minimum, and to some extend related to the advice some give of keeping your objects as immutable as possible.

4. Only abstract classes are worth extending.
If you have control over the class you are about to extend (if it’s in your codebase) before you extend that class take a look and make sure that it’s an abstract class. Abstract classes are MEANT to be extended, so you can be safe that you’re doing the right thing here.

If you’re extending a non abstract class, you should probably be composing it instead. If you don’t have access to the code of the class you are extending, things could not behave as expected when you extend, not all programmers are as thoughtful as you are.

5. Keep Object lifetime as short as possible.
This goes back to keeping scopes tight and trying to avoid singletons as much as possible (as convenient as they might be), in the case of java the JRE has a better time collecting garbage and will save you from memory leak headaches. Put those factories to work.

Feel free to disent and share your favorite principles, If you’ve coded long enough I’m sure you tend to think about these things too and I’d love to learn from your experiences.

[SCREENCAST] How to do Unit Testing on Android with Eclipse

I was going to make a tutorial, but then I figured that making a video would be a much better way to show this.
As for the code that you could grab from a tutorial, there’s a link at the end of the post with all the code shown in the video demo.

The video demo covers how to create and run Unit Test classes for regular Java classes on Android, and also how to create and run Unit Test classes that test classes that depend on Android “Context” or “Activity” objects.

If your Android unit tests are not running because of frustrating error messages, the time spent watching this video will save you a lot of reading and headaches.

Check the screencast after the break

Continue reading

Programming Languages Popularity by the number of Tagged Questions at StackOverflow.com

Caught a Bug - by Gubatron

1. C# 73,833
2. Java 43,006
3. PHP 35,371
4. Javascript 31,244
5. C++ 27,340
6. Python 22,070
7. Objective-C 10,350
8. Ruby 8,773
9. VB.net 7,778
10. ActionScript (Flash) 5,230
11. Perl 4,496

What do these numbers mean to you? Languages on the rise of popularity among programmers, or lack of good documentation?

[buzz href=”http://www.google.com/buzz/gubatron2/UJr3LGeN53k/Programming-Languages-Popularity-by-the-number-of” liked=”14″]