Inheritance overflow…

Been fiddling with Java lately when I ran into the following cute quiz about inheritance.

Reading some articles about what’s Good/Bad in Java – I ran into the following code from an article called why Java sucks?:

class Boo{}
class Buzz extends Boo{}

class Play{

    static void foo(Boo b){
        System.out.println("in foo(Boo b)");

    static void foo(Buzz b){
        System.out.println("in foo(Buzz b)");

    public static void main(String...args){
        Boo b = new Buzz();
  • What would you think will be printed ?
  • Do you know why ?

Answer: variable b is declared as a reference to object of type Boo during compilation, and that’s why foo(Boo b) is chosen over the “more intuitive” option.

The reason that it works this way is that Java (as well as many other OO languages) is single dispatch. There are other languages like Common Lisp that supports “multiple dispatch”: the decision which version of a method will be called is based both on the class of the object as well as the run-time types of the arguments!

By the way, “multiple dispatch” behavior can be achieved in “single dispatch” Languages by using the Visitor pattern (described in “design patterns” book).

I started a list of my own about the things I like/don’t-like in Java and here’s the outcome:

Plus Minus
write once – run anywhere still slower than C++
Many good libraries (both java/javax as well as 3rd parties) no multiple inheritence
Garbage collection horrible character escaping when using regex
boxing can’t pass methods as a parameter
inner classes + anonymous classes handling primitives differently (why not treat them as objects?)
reduces boilerplate code every version (generics, try with resources, filters) still too verbose (open a file…)
If inner class wants to use a variable of the parent – it must be declared final
checked exceptions can be a pain with interfaces
Inheritance overflow…

The Free Electron Legend


A few days ago I read the single most productive engineer that you’re ever going to meet – Free Electron which glorifies the ultimate hacker, for example, there’s a story about this computer geek which re-wrote the whole DAO layer in one week – something which took two other engineers approximately six months…

Personally, I don’t like the glorification that is done around coding “rock-stars” and programming geniuses. I rather have a collaborative environment, such that you won’t be afraid to make mistakes, but unfortunately in most of the organizations I ran into it’s more important to cover your butt and be a politician than actually be a good engineer (which includes to be able to make mistakes too!).

Anyways. it reminded me of another story, one that happened back in the 80’s. I heard this one from Mayer Goldbreg, a professor that taught a compilation course I took during my studies for a On that course we built all our projects using a weird language called  Scheme which is a functional programming language that has a syntax that doesn’t look very appealing to the majority of object oriented programmers:

(let loop ((n 1))
  (if (> n 10)
      (cons n
            (loop (+ n 1)))))

===> (1 2 3 4 5 6 7 8 9 10)

It took some time getting used to the weird syntax with all the nested brackets (oh god – just thinking about all the times I counted opening/closing brackets…)

But I’m diverting… so back to the story: Mayer had a friend which, not surprisingly, was such a free electron. He worked for a big company that used some low-level programming language (let’s call it X) to maintain their platform. As you can imagine, maintenance was hell, not to mention adding new features or finding bugs. But that friend came up with this great idea: he wanted to write a compiler from Scheme to X – after his project will be completed life will be sweet – everything will become much easier!

This guy had just one problem, his boss was not so enthusiastic about that idea… After a few arguments his boss told him specifically that he should forget about it – but like any good free electron he didn’t…

It didn’t take him long to build that compiler, sure enough, he had a few bugs – but he fixed them and sooner than he himself expected – he would produce so many lines of generated (and unreadable) code – and it was working great: whenever he got a new assignment – it would practically take him minutes to code it in Scheme and then he would run the compiler and take another 1 hour of coffee break. He was producing the same amount of work of the entire division!

Soon enough, his manager heard the talks and came to his cubical furious. He yelled at him and then fired him. But if you think that this is the end of the story – you’re wrong.

It didn’t take long for the higher management to find out that suddenly all the tasks were taking much longer – and after a few weeks the story got all the way up – this manager call, but now he was practically begging him to come back and maintain his compiler…
He didn’t.

UPDATE: I just ran into the following session and I couldn’t agree more with these guys!

The Free Electron Legend

Setting up Spring web-project on IntelliJ using Maven

Till yesterday I used eclipse when I wanted to work with the combination of Spring-web/Maven projects. To be more exact I was using STS which is a version of eclipse called Juno (if I’m not mistaken – but if I do – please correct me) that comes with the relevant plugins already installed (Spring and Maven’s jars for example) and it wears an ugly green skin. It also comes with vFabric server which is a web-container (like Tomcat) that was made by VMWare, which bought Spring in order to leverage Spring to push their products.

Now, if there’s an IDE that I hate – that’s Eclipse. It’s just so slow and buggy… You can spend a couple of hours on something that doesn’t work just to find out that if you create the project from scratch – everything’s peachy, and no, clean/re-built/restart/computer-restart wouldn’t have fixed it…

If IntelliJ wasn’t an option I would definitely choose Netbeans which is the fastest Java IDE I’ve experienced, but intelliJ is a tool you fall in love with

So yesterday I decided that I’ve had it, and that I’m migrating my Spring projects to IntelliJ. In case you have an existing Maven project – it’s really easy to import and start working, but then I tried setting up a project from scratch, and after fighting with it for a couple of days I finally found out how to do it (by the way, I read a few other posts in regards which didn’t help…). I know, it should be easier and that’s a couple of black-points to JetBrains, but the effort was worthy!

In order that you won’t have to go through the same painful experience which I did, here’s a short guide on how to set up a Spring Web environment on IntelliJ. So without  a further adu:

1. create a new project from scratch


2. select “Maven module” as a type and click “Next” after filling out the project name and path


3. check the option “create from archetype” and choose “maven-archetype-webapp” from under “org.apache.maven.archetypes”. If you don’t have that option go to step 4, otherwise you can skip it and go directly to step 5.


4. In case we didn’t have the archetype, we’ll click on “add archetype” and add it manually as follows:

GroupId: org.apache.maven.archetypes
ArtifactId: maven-archetype-webapp
version: RELEASE


5. before you click on “Finish” check if the parameter M2_HOME is defined, if not, you can define it as an environment variable, or alternatively you can set it up right here:


6. once you click “Finish” a pom.xml file will be generated and some, other stuff will run on your screen, you should also see the following option to enable auto-import for Maven projects – click it!


7. goto “edit configurations”, click on the “+” button and choose the local version of Tomcat



8. Name your server, check the option to “Build artifacts” and click on the “…” right next to it. Choose the .war file and continue


9. go to the “deployment” tab and click the “+” button to add an Artifact. Again, choose the war file



10. That’s it – we’re done! If you’ll expend your project you should be able to see something like the following screenshot.


Click the green “Play” button and after Tomcat starts, you should be able to view “Hello World” jsp version on localhost


Setting up Spring web-project on IntelliJ using Maven

Front-end development

I got to start by saying that I am not a front-end developer.
That said, today, when there are so many available web-stacks, it becomes inevitable to handle at least a bit of UI.

On this post, I’ll share some info that’ll help you on your way to become a front-end developer, so let’s begin:

Learn CSS!

Learning HTML is not very complicated but if you know nothing about HTML you should probably start there… I assume that you have some familiarity with HTML and that’s why we started here. CSS is a very good practice of separating styling from content. There are many web-sites that will teach you CSS and it’s very easy to Google something you’re looking for, but, if you really know little or nothing at all in regards, I recommend a course called “30 CSS Selectors You MUST memrise” in a beautiful website: memrise – a wonderful free site (there’s also a mobile app) that’ll teach you anything from languages and history to art & literature and much more. In order to dynamically change CSS on the page (and see the result without switching to the editor back and forth and refreshing the page) I highly recommend using LiveCSSEditor – a plugin to chrome which I can’t live without!

Another two plugins to Chrome I find very useful are: MeasureIt! and ColorZilla

Javascript & jQuery

Codecademy is another awesome web-site for self-education, here you can study the basics (and more) of both Javascript and jQuery. This is critical since there’s no other way to manipulate DOM elements after creation, and in fact, whenever you hear the buzz-word HTML5 it refers to Javascript!

In order to debug JS/jQuery on-page I used to use a Firefox plugin called Firebug (which is awesome!), but today I use Chrome and the same developer-toolbox is available in Chrome by pressing F12. Two relevant tabs are “sources” – which allow you to add breakpoints, inspect objects etc, and “console” which enable you to view errors in the code that ran as well as to write a Javascript/jQuery expression and see what it evaluates to. Another good resource for JS is mozilla.


Google’s PageSpeed add-on to Chrome and Firefox’s YSlow! are two excellent extensions to test the performance of your web-page. Both supply a list of recommendations which, in case you decide to implement, will improve the loading speed of the page. Two websites that offer the same analysis are the famous Pingdom and webpagetest. TMO, you should use more than one tool to have a good coverage. That said, you shouldn’t get too obsessive with the performance grades.


Firefox still has two plugins that I really like:

  1. Tamper Data is a great tool that helps viewing the parameters that were submitted/received, usually via. forms (HTTP calls). If you want to dive deeper into lower levels of protocols like TCP/IP you’re welcome to installWireShark (previously called: Ethereal), but as a web-developer you’ll probably find yourself using only the filters HTTP/HTTPS anyway.
  2. I use Poster mainly to debug REST calls which are usually less of a “UI thing” and considered more as “back-end”. But, if you use AJAX to fetch information from the server you might find this plugin helpful.

If you’re interested in SEO perspective, there are toolbars like seoquake and sites like  and that will provide a detailed analysis of your website.

keep learning!

You can do this by subscribing to weekly newsletters like Javascript weekly, online courses, reading blogs (you can search for relevant information via. redit and Hacker News), following pros on Twitter and asking questions on stackoverflow (make sure to answer some questions as well – give back to the community!)

Do you have a plugin/extension/web-site you found useful ?

Front-end development

JAX Conference 2013


A few days ago I went with a friend to JAX conference 2013, a conference in which experts & leaders from the industry share their thoughts and experience with other Java community members.

We started with a session about testing HTML5 in all browsers using Java by Kevin Nilson. He got me hooked right from the beginning with two nice Javascript riddles:

The first:

var t = ['a','b','c',]; // pay attention to the last comma

Is that a legal expression? (yes)
What’s the length? (hint: browser dependent…)

The second:

var abcData = ['a','b','c'];
var xyzData = ['X','Y','Z'];

function xyz(){
  var msg = '';
      msg += xyzData[i];

function aXYZbXYZcXYZ(){
  var msg = '';
      msg += abcData[i];
      var tmp = xyz();
      msg += tmp

What’s going to be printed ?
My guess was “aXYZbXYZcXYZ” – but it was wrong…
If you want to see the answer – you can watch the video of the session (in the link above).

After the warm-up, Kevin discussed the limitations of using selenium to test mobile and the advantages of using tools like TestSwarm and QUnit.

Getting Started with WebSocket using Java by Arun Gupta introduced a light full-duplex bi-directional communication protocol between server and client. “Upgrading” HTTP protocol to WebSocket is done using HTTP-headers:

upgrade: websocket
connection: upgrade

for which the server supposed to return HTTP code:

101 - switching protocols

Full-duplex means that once communication has been established, both sides are peers in the manner that both can send information to each other simultaneously (unlike HTTP in which only the client triggers the request and the server can only respond). Another advantage of using Websocket is the speed: the thin frame that is used by the protocol allows sending bigger chunks of data more quickly than using HTTP which carries the overhead of sending headers in every request/response. Arun benchmarked the performance of WebSocket vs. REST and the difference were (as expected) huge, for example: sending 5,000 messages of 1KB each using REST took 55 seconds and only 1.2 seconds using WebSocket.

Another interesting session was: Apache TomEE, Java EE 6 Web Profile on Tomcat by David Blevins. TomEE (pronounced: “Tommy”) is a project that aims to combine plain vanilla Tomcat with some of the more common JavaEE components, such as EJB, JPA, JMS and more (they call it “Web-profile” and it contains about half of the “full profile”). Recently they passed the TCK (Technology Compatibility Kit) of the Web-profile, David says, without increasing Java memory!

In The Road to Lambda (will be released in Java 8 – around sprint 2014) Mike Duigou showed the power of using lambdas which makes your code simpler (reduces the boilerplate), and as a bonus you get lazy evaluation and support for parallelism. Like Generics (introduced at Java 5) helps us abstract over types, the goal of Lambda is to help us better abstract over behavior (passing “behavior” = method, between objects using vars).

I got to admit that even though I like functional programming I hate the use of anonymous classes in Java, to me, it always felt like some kind of ugly hybrid between OOP and functional programming:
Lambda (closure) ties up code to data, and the equivalent to it in OO is… well, Objects.
So I was pretty skeptical about the whole idea but I’m glad to say that I was wrong!

The session started by using the fact that other languages like C++ and C# already introduced closures (bad reasoning TMO), but then Mike gave a couple of good motives, one of which was the transformation of the following code:

for(Shape s: shapes){
    if(s.getColor() == RED)


    if(s.getColor() == RED)

At first glance it looks like there’s no much difference besides the different syntax, but what really matters here is what goes under the hood: the former piece of code translates into an iterator that traverse the shapes in a serial manner, while the latter enables the library to set its own implementation which could, for instance, support parallelism.

Another example which I really liked is

int sumOfWeights =
				.filter(s->s.getColor == BLUE)

or even a bit simpler:

int sumOfWeights =
				.filter(s->s.getColor == BLUE)

but what really impressed me was how easy it is to modify the code to use parallel processing:

int sumOfWeights = shapes.parallel()
				.filter(s->s.getColor == BLUE)


Since this post is becoming too long I won’t write about other sessions, that said, I cannot not mention (and post links to) other great sessions such as Designing a Beautiful REST+JSON API by Les Hazlewood, The Spring 3.1, 3.2 and 4.0 Update by Josh Long and The Java EE 7 Platform: Boosting Productivity and Embracing HTML 5 by Arun Gupta.

See you in #JAXConf next year!

JAX Conference 2013

20 Tips for becoming a better programmer

1. There should be only one single exit point to each method (use if-else whenever needed).

2. When using if-else, make sure to place the shorter code snippet in the if:

if (cond) {
else {


3. Do not throw exceptions if you can avoid it, it makes your code much slower, if you feel like throwing something and then catching it – go play ball with your dog. If you don’t have a dog get one – they’re awesome!

4. Do not try to do many things on the same line – when you’ll get an error – it will be harder to debug, example how to NOT write your code:

String result = hasInformation()? getState() : (hasMoreInformation() ? getOtherState() : getState());

5. Look for code pieces that look the same and if you find any – refactor!

6. Meaningful names are a must. If you’re not sure, meditate on it for another minute. Still not sure? ask your colleagues for their opinion.

I’m still shocked everytime I find out that the following is not common knowledge:
7. Whenever you can use HashMap instead of List/Queue – use it!

And on the same note:
8. If you can use caching instead of I/O (usually DB) – use caching

9. If a nice and simple regex can do the job – use it!

10. Do not use regex for parsing (for example: HTML/XML/json) – there are special tools for that in every language, for example in Ruby, Java etc.

11. Print to Log. You should have at least two levels of logging: DEBUG and ERROR. The latter should be the default. Nice tip: you can send your self a text when a critical error occurs, by sending an email to your_mobile@your_carrier – look here for more details.

12. Use stackoverflow – not only for asking questions: Take a few minutes, every day, and try to answer questions – you’ll be surprised how much you’ll learn from it!

13. A rule of thumb: if your method is over 50 lines – split it. If your class is over 500 lines – split it. If you think you can’t split it – you’re doing something wrong. This recommendation is a “language dependent” and shouldn’t be taken “as is”: while 50-line method feels natural in Java/C# – it will be considered very long in more expressive languages such as Ruby & Python.

14. Writing a code which is “self explanatory” is great but also very hard, if you’re not sure how “obvious” your code is – use code-comments.

15. When writing code comments always assume that the reader doesn’t know what you’re trying to do. Be patient & explain. No one is going to *bug* you because your comment was too long…

16. You want to improve? read books, blogs, technical online newspapers join relevant groups on Linkedin, update yourself with the latest technologies, go to conferences, got the point ?

17. Practice makes perfect: solve code-challenges, join hackathons, go to meetups etc

18. Experiment with different IDEs until you find the one that “feels right”, study it carefully and make sure you know the major features (including plugins). Tune-up the keyboard shortcuts – it will make your workflow smoother.

19. Whenever you find a bug, before you fix it, write a unit-test that captures it. Make sure it does.

and my favorite:

20. Don’t get lazy – RTFM

We’ll finish with two quotes:

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”
– Brian Kernighan

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
– Rick Osborne

Many thanks for Jeff Grigg, Tom Burton and Keith M. O’Reilly for their feedback which helped me improve this post – cheers!

20 Tips for becoming a better programmer

Playing with Ruby

Ruby is a wonderful programming language, and when I say wonderful I mean that basically it just makes you happy. As a Java programmer, there are so many things that I need to check and be careful about, and Ruby just makes it easier for you, taking care of you, and if I have one more glass of wine I might get carried away and say that it almost spoils you, makes you lazy – cause now when I have to implement an algorithm, I’d rather do it in Ruby rather than Java, or even PHP, which is still easier, but with all the ugly $-signs (yes, I am lazy when it comes to hold the shift key and press ‘4’, who’s the dumb-a$$ that came up with that stupid idea anyways, ha ?)

One of the things I first do when starting to learn a programming language is implementing a few basic stuff, for example, the famous Tower of Hanoi:

def hanoi(disc, src, hlp, dst)
    if disc > 0
        hanoi(disc-1, src, dst, hlp)
        puts "moving disc #{disc} from #{src} to #{dst}"
        hanoi(disc-1, hlp, src, dst)

hanoi(3, 'src', 'hlp', 'dst')

It’s so beautiful to define factorial in one line:

def fact(n) (1..n).inject{|r,i| r*i } end 

And then I usually continue to merge-sort:

# sorting the array from _start index to the _end index
# using merge sort
def mergesort(arr)

    # stop condition
    return arr if arr.count == 0 || arr.count == 1 
    # split the range
    mid = arr.count/2

    # sort recursively both parts
    arr1 = mergesort(arr[0, mid]) 
    arr2 = mergesort(arr[mid, arr.count-mid])

    # and merge
    merged = []
    max_i, max_j = [arr1.count, arr2.count]
    i = j = 0
    while i < max_i && j < max_j
        if arr1[i] <= arr2[j]
            merged << arr1[i]
            i += 1
            merged << arr2[j]
            j += 1

    # continue copying the rest:
    while i < max_i
        merged << arr1[i]
        i += 1
    while j < max_j
        merged << arr2[j]
        j += 1

    # return

arr = [2,3,4,5,6,1,7]
puts mergesort(arr)        	

and if we didn’t have enough, let’s implement quicksort as well:

def quick(arr)
  return [] if (arr.size == 0)    
  pivot = arr.pop
  left =
  right =
  arr.each { |i|
    if i < pivot
      left << i
      right << i
  return quick(left) + [pivot] + quick(right)

a = [5,3,9,8,7,2,4,1,6,5]
p quick(a)

The downside of coding in an unfamiliar language is that your’e still captured in patterns that are perfect for other programming languages, only that in this one – you can do things in a more elegant & efficient way.

Until next time…ta-ta!

Playing with Ruby