Oct 18, 2013

Assertions

Assertions represent Boolean expressions that a programmer believes to be true at specific points in a program. Assertions were included in Java 1.4, they are often confused as exception handling aids but in essence they help you validate, or better said, evaluate conditions on runtime; they are for debugging not for exception handling. 
Assertion properties commonly fall into one of these three categories:
  • Preconditions that a property holds before a code block executes
  • Postconditions that a property holds after a code block executes
  • Invariants that a property holds before and after a code block executes
 The role of assertions is to identify bugs in a program. Assertions frequently involve writing macros that compile into real-time checks when a debug flag is set.
Note: Assertions are disabled on runtime by default, to enable them you must use the -debug flag 

Programming assertions
Constructors:
assert booleanExpression;
assert booleanExpression : message;

Sample:
assert time>12 : "The value of time must be greater than 12. Time is +"time;

The use of assertion programming can be adopted slowly. Use assertions first around the entry points of functions or methods. Then move on to conditions executed within the code before advancing to manipulations and function returns. As you increase the usage of assertions, the quality of the code will improve.

Oct 15, 2013

Unit Testing

Before jumping into topic, a quick definition of what is Testing (google "definition of testing", I'm just saving you some time here):
A procedure for critical evaluation; a means of determining the presence, quality, or truth of something. According to the The Free Dictionary
So now that you know what testing is... there are different levels of testing:
  • Unit testing. The most basic of them, is a test to verify the functionality of individual components before they are integrated with the other components.
  • Build verification testing (BVT). Is a test to validate that the product build is installable and performs basic functions required by the product.
  • Functional verification testing (FVT). Is used to verify that each function operates in accordance with the written requirements
  • System verification testing (SVT). Is the test of the entire product or a set of products in predefined system environments. During this step you can also perform some Performance Testing (how fast does the program executes) and Usability Testing (how usable is my program).
  • Integration testing. Is a test to evaluate how the products interact together for a whole solution.
  • Acceptance testing. Is used to identify whether or not the system satisfies a set of acceptance criteria.
Unit testing is the lowest level of dynamic testing that occurs during software development. Developers test their individual units of software in isolation from the overall product, ensuring that each component or module that is separately testable is functionally correct
There are five activities essential for successful unit testing:
  • All inputs validated
  • All code paths and branches executed at least once
  • All exception handling cases triggered
  • All data and variables are initialized before use
  • Simple regression tests created
Some things to have in mind while doing unit testing:
  • White-box testing. it requires explicit knowledge of the code been tested. Developers use this knowledge to determine what test cases and test data to use and execute.
  • Test coverage: When designing white-box test cases, one critical factor determines test validity: are all possible paths, decision points, and loops in the code tested? You can measure this coverage in a number of ways:
    • Statement coverage measures the number of lines of code invoked.
    • Branch coverage measures the number of decisions or yes/no expressions invoked.
    • Path coverage measures the number of paths executed.
  • Basis path testing: The basis path testing technique provides a way to guarantee that all independent paths are tested. This technique consists of four steps:
    • Create a control flow graph.
    • Determine the cyclomatic complexity of the graph.
    • Determine the basis path set.
    • Create the test cases by determining which inputs will exercise each basis path.
  • Condition coverage: Another white-box testing technique is the condition coverage method. This technique produces enough test cases that each condition in a decision generates each possible outcome at least once, and each point of entry to a program or subroutine invokes at least once.

Oct 4, 2013

Observer pattern in a nutshell

The Observer is also a behavioural pattern
 
The book definition reads:
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

This are the components needed to apply this pattern,  usually two interfaces and concrete instances for each of them (another sample is the java implementation, look at the foot note).

Components:

Subject

  • Knows its observers
  • Has any number of observer
  • Provides an interface to attach and detaching observer object at run time

Observer

  • Provides an update interface to receive signal from subject

ConcreteSubject

  • Stores state of interest to ConcreteObserver objects.
  • Send notification to it's observer

ConcreteObserver

  • Maintains reference to a ConcreteSubject object
  • Maintains observer state consistent with subjects.
  • Implements update operation
observer pattern diagram
 

When to use it:

  • When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
  • When subject doesn't know about number of observers it has.
  • When an object should be able to notify other objects without knowing who objects are.
 
So, how this really works?
Well in essence you have a subject (the object been listened or followed) that implements a subject interface. In this interface you need to provide a way for other objects to listen to your actions or subscribe, also you must provide another method for objects to stop listening to your non-sense actions and finally provide a method to notify all the objects listening to you, what are you doing.
You also need an observer interface, which must be implemented by the objects listening to your updates. With the update method they will be notified when your subject publishes new data.
 
Some examples where you may find this pattern:
  • RSS feeds
  • Twitter
  • Facebook
 
Note:
Java has it's own implementation.
  • java.util.Observable (which is a concrete class you have to extend)
  • java.util.Observer (which is an interface that you have to implement)

Oct 1, 2013

Strategy pattern in a nutshell

The strategy pattern is a behavioural pattern. According to Wikipedia is  also known as the policy pattern (not sure by whom, but Wikipedia holds a lot of untold truths)

The book definition reads:

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour
 
To be able to use this pattern properly, take a minute to think about this three things:
  1. Isolate the behaviors you need and define an interface that applies to all of them.
  2. Implement the different behaviors. Each behavior IMPLEMENTS the interface.
  3. The main object HAS-A behavior interface container from which the selected behavior will be called.

Diagram:

Strategy Pattern Diagram

Where Would I Use This Pattern?

The Strategy pattern is to be used where you want to choose from algorithms used at runtime
 
Some examples where you may find this pattern:
  • Save to different formats
  • Payment methods
  • Sorting algorithms
  • File compression

 

References:

http://en.wikipedia.org/wiki/Strategy_pattern

Jul 17, 2013

Easily parallelizing code with Executors

Many times I've had to make some code work in parallel and I ended up doing things manually... You know a thread and a class to handle them with some funky logic that I have to check 100 times to get it right... that is usually what we end up doing because is the way we know (because it's the first thing we learn when dealing with parallelism). 

A few weeks ago I had to do the same thing again but this time I decides to do some reading before getting hands with the knowledge I have (yes, I know there is a first time for everything!). I read the concurrency chapter of Effective Java 2nd Edition and I noticed something really interesting that was enabled on java 5 the Executors
This cute little class allows you to specify the amount of threads you want to use to run some tasks, plain and simple!. Then you only have to create the tasks and submit them to the Executor,  after that you can either iterate the results or just let them be and wait for the Executor to finish. Yes it sounds really simple but if you are the same as I am, this is just pure words with no meaning, show me some code!

Well here it is, how to create and execute tasks with Executors:

  1. First you create an Executor,
    ExecutorService executor = Executors.newFixedThreadPool(cores);
    there a different kinds for different purposes (choose carefully to your needs). If you want to schedule a task instead of using timers take a look at the Scheduled Thread Pool, if you don't need a pool check the Single Thread Scheduled Executor. There are different kind of executor services and you can pass many things to them so take a deep dive before picking the right one.
  2. Identify if you will need results back from the tasks if so create a class and implement Callable, otherwise implement Runnable, both of them work perfectly fine with the Executor. DO NOT, I repeat DO NOT implement thread, there are many thing improved along the way in Java so you don't have to do this any more.
    • If you just want your task processed and she will do what she needs and then die in peace, use the Runnable interface and just execute your task
      executor.execute(new RunnableTask());
    • If you need the results Callable is the way to go, when you execute this tasks you have to use
      executor.submit(new CallableTask());
      this will give back a Future object that will contain the result for your task so don't lose it!
      One interesting fact is that to get the result from the Future object you have to call the get method on it, what is interesting is that if your task has not been processed yet the code will wait for it to execute! And you don't have to code those nasty synchronized methods and joining threads to get this, it's free so enjoy it!
  3. If you chose the Callable task you may want to iterate the results to process them, if not well basically you're done!
Note that the tasks will not be executed in order, if you want to do so, you can take a look at Google Guava that provides such capability. You can read more about it in here

And finally here is a small sample that you can download to check what happens.

Jun 28, 2013

Here we go!

I've had this idea of creating a blog where I can store, keep track and never lose tips for programming, best practices, code snippets, apps that help you do great stuff and that is something I would like to share with all of you.
In this blog you will (eventually) find code snippets, utilities, programming references, histories and anything related to programming and technology that (whishfully) will help someone on their day by day or  entretain you with some cool technology and stuff like that.
Since this is the first time I've ever done something like this, I beg you to be patient while I get a grip of this new role as blogger (that if you decide to read some of my posts in the future, which I hope you do)
So as the title says... here we go!!