Category Archives: programing

StackOverflow: why it succeed?

You succeed when you reach your goal. Simple at that.

Why StackOverflow is a success? It’s not because that the website has reach 560M page view/ month. It’s because it makes software developer’s life easier.

My criterion for whether Stack Overflow works: when you type your question into Google, and you’re happy to see a Stack Overflow result rather than a result at another one of those Q&A sites where you have to sign up and pay a monthly fee to see the answer. - Joel Spolsky

Once you understand the site’s goal, you would understand the hard choice that its creators have made. Many people complain how the site has been so strict in its “standard” for question and answer. When they come to the site asking for help, but leaving unsatisfied. Or worse, their question would be closed in few seconds because it’s “too broad”.

It’s because that SO “true” customer are the indirect users, those who come searching for an answer. The answer gets written only once, but it gets read millions of times years later.

The more time you spend on writing a short, clear and coherent question, the more time would be saved from your reader.

Logging or debugger?

It all begins when I read a small story over the net:

A young girl watching her mother prepare a ham to bake for dinner. As the mother cut both ends off the ham, the daughter asked why. Mom replied that her mother had always done it that way. When the daughter still insisted on knowing why, a quick call to grandma revealed the reason: “Because the pan was too small.”

The story above is exactly what I usually get when I try to present something new. Like what I’m going to do here.

Well, not exactly new. Debugging by using log vs. debugging using debugger was a long time debate. We can google dozens of articles written about the subject. And while most of them use the very political phrase “it depends” as an answer, I would confidently tell you “logging is obviously superior in 99% of the time“. Continue reading

Simple things matter

Today, out of boring, I did visit again codility to take a few tests. Their free tests aren’t much of a challenge, so I got them one by one, each in 5 minutes or so. Then I come across a test which, to my opinion, just a little trick question:

Problem: PermMissingElem

Task description
A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
Your goal is to find that missing element.
Write a function:

 class Solution { public int solution(int[] A); } 

that, given a zero-indexed array A, returns the value of the missing element.
For example, given array A such that:
A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5
the function should return 4, as it is the missing element.

Feel free to drop a few minutes to think it through. It isn’t even hard.

You finished your program? Ok, then let’s continue.
I took my 5 minutes and write a very simple script, including the unit tests:

First Solution
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int sum = 0;
int sumTotal = (A.length + 1) * (A.length + 2) / 2;

for (int i = 0; i < A.length; i++) {
sum = sum + A[i];

int result = sumTotal - sum;
return result;

Unit tests:

  • [6,5,4,3,2]
  • [2, 5, 1, 4]
  • [2]
  • [1]
  • [6,3,5,4,2,1]

All my unit tests passed. I submitted, kind of waiting for another 100%. But it was FAILED with n ~ 1,000,000.

My algorithm is right, I know that. So what’s the matter with big number?

In case you’re still wonder, here’s the program that worked and got 100% score:

Right Solution

class Solution
public int solution(int[] A) {
// write your code in Java SE 8
int sum = 0;
int sumTotal = 0;

for (int i = 0; i < A.length; i++) {
sum = sum + A[i];

for (int i = 1; i <= A.length + 1; i++) {
sumTotal = sumTotal + i;

int result = sumTotal - sum;
return result;

Can you tell the difference? :)

Don’t lose the ability to be surprised


Any fair-experienced CSS developers know that, if we want to be sure that a parent-div truly contains a child-element, we should put “overflow:hidden” in the parent div.

I was told that, too.

Ok, that solved the problem. And we continue going without truly knowing the reason “WHY”?

“Don’t fix what ain’t break” – people say.

In fact, I’m type of people who don’t like to invest time into things that aren’t useful. So I accept that trick as it is. Until today.

I was surprised (or remember that I was surprised) – like the first time I heard the trick. It took no more than 10 minutes to find an answer… but the question is that WHY I didn’t ask that question any sooner. How can I let the “magic” slip without wondering???

I suddenly remember a lot of other things that I take for granted. When I first come to this field, everything is new and shiny. After a while, things get normal bit by bit. And gradually I forgot my ability to wonder.

I remember the time when I was assigned to do OAuth 2.0 for a Facebook application. Instead using a library, I “silly” re-wrote the whole authentication process by Servlet/ HttpRequest & Response. By now I’m nearly sure that there must be pre-built library to do that thing somewhere. Whatever, I don’t regret. The time I put in studying how OAuth 2.0 works let me confidently say that I fully understand it, and I can (and did) manually write authenticate process for both Twitter & FB… They are all HTTP requests, basically.

What’s the way of your choice: learn just enough to do things – or learn intensely to truly understand how things work?

P/s: I have some ideas about “Key Concepts” (to overflow:hidden, it’s Document flow). But this post’s long enough.

Start at StackOverflow: The right time to ask


A time has passed after my last post in the series “Start at StackOverflow”. It may be because that I don’t find much time to wander there anymore. Still, it’s still a useful resource, and one of the fruitful source when I try to do things that my peers may did already.

But now I think I found a simple question, that, though it seems A LOT OF useful, not many people ask. Even I just notice it after more than a year with this site.

It is:

What is the best time to ask at StackOverflow?

Why is this question important? Answer: the answer’s ratio for your question certainly depends on the number of users who see it.

If you work in a very-narrow technology domain, and ask at the time when most SO users about that field are sleeping, surely you must wait for an answer.

If your question is on a general field (Java, .NET…), don’t feel lucky too early. There are tons of general quesions dump to StackOverflow every minutes, so your question will soon flow to the end of the list… and well, may take at most 20 views.

Reversely, if you are new to the site & want to play the reputation game, you should do the opposite: online at the time that most people are offline to answer questions with much slower speed…. and help the guy in need, ofcourse :)

When the problem is found, I realize that I’m not the first person asking that question.

But I myself come up with a fairly different answer. In the post of Jeff ArtWood (about 3 years before), the best time is around 15:00 and 22:00 GMT/UTC. In my experience, with Java-related questions, the best time is around 2pm – 5pm at Vietnamese time. In GMT, it’s about 7am – 10am.

Javascript is an object-oriented language (1) – Encapsulation

Javascript is a powerful tool. No web developer can live without it. Without Javascript, the webs will be much poorer, as most of user-experience enhancement don’t exist.

Powerful tools are often misused. Javascript is in the same fate. Easy to write, easy to mess. And it soon earn the dispute as one of the most messy language. But investigating further, Javascript is one of the most mis-understood language.

Javascript is an object-oriented language.

That maybe a suprise to some people, and so do I. You see, javascript is often written in one big files, with the statement lined up from start to end… Global variables, C-like syntax,… it just seem to be a typical procedural language.

In fact, Javascript is heavily object-based. Everything in javascript is viewed as an object. Function is an object. Array is an object. But surely, “just because a language has objects doesn’t make it OO.”

You may say: but every property in a Javascript object is public? Aren’t we told that a language can only be called object-oriented when it has “encapsulation“, “inheritance” & “polymorphism“?

For the first question, I can confirm: yes. All property in a Javascript object is public. But Javascript is still an object-oriented-able language. Following I will show you how:

1. Encapsulation

Encapsulation can be achieved by a special feature of Javascript: the closure. Simply put, that’s the ability which allow the inner function has access to local variables in the outer function. A simple piece of code should says more than I could:

var Merlin = function() {
var say = function() { alert(advice); }

// Local variable that ends up within closure
var advice = 'One must complete what he started';
return {say: say};

var apprentice = new Merlin();
apprentice.say(); // alert 'One must complete what he started'
alert(&quot;Let's look inside of Merlin: &quot; + advice); // alert nothing, since advice is not a global object

To be fully understand the concept of closure, one should study about how Javascript define scope for its object. In the above example, you can easily see that, the function say() can still access the local variable “advice”, even after function Merlin() has completed. Other languages (Java, C, for example) often requires the local variable disposed as soon as the function is complete. This is a strange mind-set, but as you see, it do the “hiding” job just well.

(to be continued)

P/s: Thanks to Mr. An to give his time explaining this to me, which most of the books never make a comment.

Unit test – call the agel out of the stone


Angel, please come out of the stone

“I saw the angel in the marble and carved until I set him free” – Michelangelo

After the previous post when I managed to make Spring context wired for Unit test to run, now there’s more thing into it. Well, I gave my Test class the ability to do IOC (Inversion of Control), and from now they can call service beans, access databases, and so on… It seems the remaining should be easy, since the hardest part has been completed.

Well, things don’t easily go as we expect, in lots of occasions.

I actually made a running code, but when I try writing my first unit tests for my current working web-application, things turn bad. It turns out that I can’t write much meaningful non-trivial test, without making test-running-time tremendous slow. Why? It’s because:

1. Most of my code logic lies in the service. AND the service (in this project) OFTEN (if not always) works with Database. And when I says Database, it means the test is not the unit test anymore. It’s an Integration Test.

2. There’s some logic in my project which doesn’t relate to database. But I feels pretty confident about them – they are mostly simple. According to Pareto’s 80/20 rule, I don’t want to write tests that doesn’t enhance maintenance ability.

Those may be (some of) the reasons that my seniors don’t encourage me to write unit test. Unit tests are meant to be fast. If it’s not fast, there’s no reason to run it frequently, to help refactoring or development.

Another problem I meet is to set up the Database to a known state before running the test. Only then the test results will have some meanings.

So… are the efforts all useless. Absolutely no. The main problem here is that I need to stop regression bugs, by regularly running some kind of test. Whatever it is, but let me find bugs soon, and stop the system broken by ill-refactoring.

“And I have found the solution. The way to call the angel out of the stone”. If I can put up an in-memory database instead of Postgres, the running-time will be fast. I can also prepare the environment by database script or bootstrap code.

DBUnit seems to be a fair choice for a solution.

Configure UnitTesting with Autowired in Spring context

/* Vietnamese:  Một bài viết trình bày cách viết Unit Test sử dụng Dependency-Injection(Autowiring) trong Spring Framework. */

Unit-testing is surely not a new idea, since it was proposed around the 1980s. But it’s still one of the core concepts of Test Driven Development, Agile programing, Scrum,… & some other “hot” programming methodology that arise recently. In “Clean code”, Robert C. Martin writes: “If you want to write a line of debug/log message, consider writing a test instead”.

Those ideas are really cool – if you want to know more about how writing tests stop regression bugs, improve productivity & help the designs overall, go on & read “Clean code”. I will return to the topic here: How to write Unit test in Spring context.

The second I read those above lines of Martin, I decided to try it right away. But to do Unit test in a Spring web project, I need a way to inject my services into the test case (well, there’s a HUGE pile of services). The way is easy, but only if you know what to do.

It took me quite a time to make a running system.

Here’s how I did it:


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

public class ActionServiceImplTest {
	private ActionService actionService;

	public void testHelloAction() {
		assert actionService.helloUnitTest().equals(&quot;Hello Unit Test, hope we have a good time together!&quot;);

Hope that should cover the topic

Source code can be found here:

Reference: (not all of these links are referred in this article. But every of them help me “go near the truth”, so I put them all here.)


A quick experiment on HTML5 Canvas


/** Vietnamese: một thử nghiệm nhỏ lên trang canvas của HTML5 **/

HTML5 is out for a while, and many people have already play with it. Inspired by the great article here, I managed to make a simple dirty experiment.

&lt;!DOCTYPE html&gt;

&lt;html lang=&quot;en&quot;&gt;


    &lt;title&gt;Good night&lt;/title&gt;


  &lt;body&gt;&lt;script type=&quot;text/javascript&quot;&gt;
  if ( !window.requestAnimationFrame ) {

    window.requestAnimationFrame = ( function() {

      return window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimationFrame ||
      function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {

        window.setTimeout( callback, 800 / 60 );


    } )();

&lt;/script&gt;&lt;script type=&quot;text/javascript&quot;&gt;
var canvas, context;
var xx = new Array();
var yy = new Array();
for (var i = 0; 40 &gt; i; i++) {
   xx[i] = Math.random()*600;
   yy[i] = Math.random()*150;

function init() {
  canvas = document.createElement( 'canvas' );
  canvas.width = 600;
  canvas.height = 400;
  context = canvas.getContext( '2d' );
  document.body.appendChild( canvas );
function animate() {
  requestAnimationFrame( animate );
function draw() {
  var time = new Date().getTime() * 0.001;
  var x = Math.cos( time ) * 250 + 300;
  var y = Math.sin( time ) * 250 + 300;
  if(150 &gt;= y) {context.fillStyle = 'rgb(250,250,250)';}
  else {
    if (200 &gt;= y) {
    } else {
      context.fillStyle='rgb(14, 14, 14)';
  context.fillRect( 0, 0, 600, 400 );
  context.fillStyle = 'rgb(255,255,0)';

  context.arc( x, y, 15, 0, Math.PI * 2, false );
  context.fillStyle = 'rgb(0,0,255)';
  context.fillRect(0, 215, 600, 400);
   for (var i = 0; 15 &gt; i; i++) {
      context.fillStyle = 'rgb(255,255,255)';
      context.arc(xx[i], yy[i], 1, 0, Math.PI * 2, false );
      if (y &gt; 200) {
          if (Math.floor(time) % 2 == 0) {
            context.fillStyle = 'rgb(255,255,255)';
            context.arc(xx[i], yy[i] + 215, 1, 0, Math.PI * 2, false );
          } else {
            context.fillStyle = 'rgb(255,255,255)';
            context.arc((yy[i] / 150) * 600, (xx[i] / 600)*150 + 215, 1, 0, Math.PI * 2, false );

You can view the example online here.

Free ads: thanks for the start-up Handcraft for letting me quickly “craft” this product.