Saturday, June 1, 2013

New blog

For quite a long time I've been looking for simple blogging service with Markdown support and finally discovered that Github has Jekyll support on their Github Pages. So, my new blog is now part of my personal page:

http://loki2302.me/blog/

Monday, May 20, 2013

The Power Of "Hello World"

There are 2 kinds of things you write, when you write a program:
1. Things you're absolutely sure about
2. The rest

Point 1 is things you write 10 times a day. You definitely know how to declare a string variable. You definitely know how to write a for loop. There's a bunch of other things you're firmly sure about. Point 2 is things you don't do every day. Or even things you never did before.

I'm pretty sure, there are only 2 points. There's no point 1.5 where you "well... sure" - it's always either you're sure or not.

Point 2 is when you feel uncertainty.

The worst thing one can do in this case is get some coffee, turn the brain off and try to do whatever needed. In most cases, it won't work. You write some code, you run your program and see it doesn't do what you expect. You make changes, you rerun it, same story. 10 minutes later you start thinking if it's not your issue, but some other code, you spend 20 minutes more to check it and so on.

There's a trick. If there's at least a minimal uncertainty, the best thing to do is just start a new project aimed to increase your confidence. Think out the simplest task possible and get it done. Make it more and more complex unless it becomes what you really need. One can think it requires much more time, but the funny thing is - it always takes less than approach I described before.

Discover the power of "Hello World"

Whenever you start learning something new (or just about to do something you don't do every day), the best thing to do first is write a "Hello World". It's not because there's a tradition. It's because you need to test your adequacy first. You make sure you understand what you do. You make sure your environment is ready.

The power of "Hello World" is in its simplicity. The key point here is to take a task you're absolutely sure about and then get it done. If your confidence was reasonable, you'll get it confirmed. Otherwise, you'll realize that even a simplest program doesn't do what you expect it to do and this means that something is wrong.

Let's say you've never tried unit testing before and so one day you decide to check what JUnit is. It's a tool that runs pieces of code and every piece of code either fails or succeeds. It's that simple. So, the good "Hello World" is to write 2 tests: the empty one (to make sure it will never fail) and the failing one (to make sure it always fails). When you run these tests, you know what to expect. If your expectations were right, you'll make sure everything is fine. Otherwise, you'll have a great small illustration of how to make it not work.

Another good example is ORMs. You decided to learn Entity Framework. ORM is basically a tool to make your database interactions look like there are no database interactions at all. What you normally do to database is CRUD operations. So just take NUnit and write a test where you create something, read it, update it and then delete it. It's 20 lines of code and at most 1 hour of your time including googling, but you're now confident you know how to do it.

As long as you write Hello Worlds before making changes to the real code, there are just no complicated tasks for you. Don't be a hero. Just simplify the way you do it.

Sunday, May 19, 2013

Meet Retask - an ultimate productivity tool

I'm very enthusiastic for achieving better productivity and making sure things expected to be done are done. I've recently decided to build a simple online tool for task management, because I just wanted to have list of things to do available from everywhere.

So, here's is Retask: http://retask.me
Feel free to sign up and use it.

Here's what it looks like:

The big idea behind Retask is simplicity. It doesn't make you follow the specific approach, nor it says what and how you should do. There are just 3 swimlanes, that indicate things to do, things you're working on at the moment and things already done. Retask provides advanced formatting capabilities - you can use Markdown to emphasize important points and structurize task descriptions.

Saturday, July 14, 2012

Dependency inversion principle (DIP)


SOLID principles:

Depend explicitly, require explicitly, but only require what you really need.

Consider an example:

(not for production, illustrative purposes only)
public class ConsoleLogger {
  public static void log(String text)  {...}
}

public class SomethingDoer {
  public void doSomething() {
    // I won't show you the code      
  }
}

Is there a connection between SomethingDoer and Logger? You'll never know unless you have a code for SomethingDoer. OK, I'll show you:

public class SomethingDoer {
  public void doSomething() {
    ConsoleLogger.log(new Date().toString());
  }
}

This may not look that bad as long as you have the code. But what if this SomethingDoer is in a 3rd-party library and it sends some stuff to the console while you don't want it? The solution is to explicitly say: "SomethingDoer depends on Logger". Here is a possible solution:

public class ConsoleLogger {
  public void log(String text)  {...}
}

public class SomethingDoer {
  private final ConsoleLogger logger;

  public SomethingDoer(ConsoleLogger logger) {
    this.logger = logger;
  }

  public void doSomething() {
    logger.log(new Date().toString());
  }
}

Logger logger = new Logger();
SomethingDoer somethingDoer = new SomethingDoer(logger);

In this code, you just can't make an instance of SomethingDoer without giving it an instance of Logger. But still, what should we do in case we don't want any output at all? SomethingDoer doesn't basically require any particular logger, it requires something that IS a logger, but no further details are required. So, here's the next step:

public interface Logger {
  void log(String text);
}

public class ConsoleLogger implements Logger {
  public void log(String text) {...}
}

public class NullLogger implements Logger {
  public void log(String text) { /* do nothing here */ }
}

public class SomethingDoer {
  private final Logger logger;

  public SomethingDoer(Logger logger) {
    this.logger = logger;
  }

  public void doSomething() {
    logger.log(new Date().toString());
  }
}

// if we want to enable output:
Logger logger = new ConsoleLogger();
SomethingDoer somethingDoer = new SomethingDoer(logger);
somethingDoer.doSomething(); // got output

// if we want to disable output:
Logger logger = new NullLogger();
SomethingDoer somethingDoer = new SomethingDoer(logger);
somethingDoer.doSomething(); // no output

In next posts I'm going to cover this topic in more details.

Interface segregation principle (ISP)


SOLID principles:

The smaller interface is, the better it is.

The idea of interfaces is to say "implement me to say others that your class can do what I define". When you see something like:

class Button implements Clickable, Focusable, HasPosition, HasText, Widget {
  ...
}

In pure English it reads as "You can click button, it can be focused or not, it has position and text". On the other hand, when you see something like this:

class PushButton implements Button {...}

It doesn't give you any idea about what the PushButton is. There are mechanisms in Java and C# to describe the type constraints when you need to pass something that is a widget+has text+focusable.

Another point here is that classes often depend on interfaces (they require objects implementing interfaces to be passed as their constructor arguments). So, when you see something like:
...
void processItems(Iterable<Integer> items) {
  ...
}
...
You can easily tell that this method doesn't really care about order of items, it doesn't care about the number of these items, and for sure it is not going to add any new items to whatever you pass there. You can easily pass an ArrayList<T> there, but still this method says: "I don't really care if you give me a Set or an ArrayList, I just need items".

Liskov substitution principle (LSP)


SOLID principles:

Use inheritance when you want to alter the behavior implemented by the non-abstract class.
Use inheritance when you want to define the behavior not implemented, but specified by the abstract class.
Implement interface when your class conforms to that interface.
There are no other cases when you should want to do it. In other words, when you use extends/implements the interface/protocol should remain the same.

Let's consider an example:

(not for production, illustrative purposes only)
// there's a standard class ArrayList in Java

public class MyList<T> extends ArrayList<T> {
  public void dumpFancily() {
    System.out.printf("I have %d items and here they are:\n", size());
    for(T item : this) {
      System.out.printf("I have %s\n", item);
    }
  }
}

The only aim of MyList is just to add a convenient method dumpFancily(). This convenience will only remain as long as your references to the objects of this class have a type of MyList. As soon as you use something like Collections.unmodifiableList() against your MyList, you'll lose your dumpFancily(), since unmodifiableList() returns List<T>:

MyList<Integer> myList = new MyList();
myList.add(123);
myList.dumpFancily(); // OK, you rock

MyList<Integer> myReadonlyList = Collections.unmodifiableList(myList); // ERROR, won't compile
Collections.unmodifiableList(myList).dumpFancily(); // ERROR, won't compile

So, what's the big idea of your MyList<T> if you can't work with the standard library?

Open/closed principle (OCP)


SOLID principles:
Classes should be easy to extend and alter without changing their code.

Let's consider the calculator example once again:

class CalculatingMachine {
  public static void add(int x, int y) {
    System.out.println(x + y);
  }
}

How do I change its behavior? What if want it to use something else but System.out for printing? Looks like OCP is violated here, there's no explicit way I can do it. One of the possible solutions here is to make this class abstract.

(not for production, illustrative purposes only)

abstract class AbstractCalculatingMachine {
  public void add(int x, int y) { // cant use static anymore
    getPrintStream().print(x + y);
  }
  
  protected abstract PrintStream getPrintStream();
}

class ConsoleCalculatingMachine extends AbstractCalculatingMachine {
  @Override
  protected PrintStream getPrintStream() {
    return System.out;
  }
}

I have all the calculator machine-specific behavior implemented in abstract class AbstractCalculatingMachine. I also have ConsoleCalculatingMachine that uses System.out for printing the results. As soon as I need a way to print results to file, I'll just subclass AbstractCalculatingMachine once again and will return file-based PrintStream in getPrintStream(). This can be done without altering AbstractCalculatingMachine class' code.