02 December 2011

Coding tip: i++ vs. ++i

Using the index i is very popular in coding, and as every developer knows, there are two ways to increment it:
  1. i++: increments i, but returns the pre-increment value.
  2. ++i: increments i, and returns the post-increment value.
Now, suppose you have a generic for loop, what would you use to increment i?

for(int i = 0; i < N; i++)
{
    doSomething();
}

OR

for(int i = 0; i < N; ++i)
{
    doSomething();
}

The school way says using i++, but let's think about it...

Compiling "i++" will be something like that (assembly pseudo-code):
      tmp = i
      i = i + 1
      return tmp

However, compiling "++i" will look like this:
      i = i + 1
      return i

So, using ++i will save one assembly assignment command and therefore, it's better to use ++i to increment the index in cases you don't use the pre-increment value.

Note1: I'm pretty sure that most of the compilers will optimize using i++ and convert it to ++i automatically, but coding the right way shows understanding which is valuable.

Note2: While I tried to write i < N w/o the spaces, blogger popped-up a warning says that my text has no ending delimiter, although I'm under "Compose" tab and not "HTML" tab... nice BUG :)



05 November 2011

What the IF?

If you had these both if conditions, what would you choose to put in your code?

The one:
if(rc == STATUS_SUCCESS)
{
    doSomething();
}

The other:
if(STATUS_SUCCESS == rc)
{
    doSomething();
}


Intuitively, the answer would be (rc == STATUS_SUCCESS), but! What if you forgot one = and wrote (rc = STATUS_SUCCESS) instead? This will be an assignment inside the condition, which will compile, but definitely not what you want to. Now look at the the second option, if you wrote (STATUS_SUCCESS = rc), this will not compile (since STATUS_SUCCESS  is a const) and you'll know you've a bug in compilation.

Note1: you may say: it's not gonna happen to me, I won't forget that =. But believe me, you will forget it and if you didn't go with the second option, you'll be up all night searching for that = (like I did).
Note2: using a Static Analysis Tools (aka Lint-like tools) can expose an assignment within an if-condition warning.

19 October 2011

Threads Question

I heard a question this week, and I thought it would be nice sharing it here, I did solve it, however, I'm not 100% sure I did it right :), so here it is:
What is the maximum value the variable i can get in each case below, assuming that it's a global int initialized by zero (int i=0) and the code in each case is running on 2 threads?

case1:
while(i < 1000)
{
    i++;
}
case2:
while(i < 1000)
{
    ++i;
}

case3:
while(i++ < 1000);

case4:
while(++i < 1000);

10 June 2011

Ethernet packet generator: packEth


Recently at work, I had to debug some Tx flows for transmitting Ethernet packets, and pings didn't help since I needed to build a specific packet with some parameters. After searching the web I found this tool called pachEth, which allows you to simply build 802.3, ver II and 802.1q packets and transfer them using interfaces supports Ethernet in your machine.

S&M (Simple and Main, not this S&M)

03 February 2011

الأيوبيون

أضحى وركب المؤمنين قران

وشاكر الرب العظيم جلاله

ولم يأتي على نعم بشكران

رحاب القلب متسع فلم يشمل

هنيئ القلب لا يخلو من الأمل

وهاني القلب مسرور بهمته

تآخى العلم والأخلاق إخوانا

علي في مكانته لنا علم

كريم شاكر في القلب إيمان

وفرق في خواتمهم وحاتمنا

وما للزهر من بد بخسران

أريج الزهر والريحان شابهها

دموع القلب أفراح ووجدان

عنان سماءها يدنو وتثقله

وفي القلب لها عرش وعنوان

وان تسألني عن سمها فعائشة

زهور النرجس الحاني وريحان

ملوك الغاب تخشاها وتحسدها

شعر: محمد غازي عبد الرحمن

16 January 2011

Zhuangzi - Discussion on making all things equal

Now I am going to make a statement here. I don't know whether it fits into the category of other people's statements or not. But whether it fits into their category or whether it doesn't, it obviously fits into some category. So in that respect it is no different from their statements. However, let me try making my statement.
There is a beginning. There is a not yet beginning to be a beginning. There is a not yet beginning to be a not yet beginning to be a beginning. There is being. There is nonbeing. There is a not yet beginning to be nonbeing. There is a not yet beginning to be a not yet beginning to be nonbeing. Suddenly there is nonbeing. But I do not know, when it comes to nonbeing, which is really being and which is nonbeing. Now I have just said something. But I don't know whether what I have said has really said something or whether it hasn't said something.
Zhuangzi - Discussion on making all things equal.

Hebrew Version:
עתה אומר משהו. כשאני אומר משהו – האם אני טוען משהו? האם אין אני טוען משהו? איני יודע.. ובכן, אנסה לומר משהו: הבה נניח שיש התחלה. אם כך יש "עדיין אין התחלה". אם כך יש "עדיין אין עדיין אין התחלה" אם כך יש "יש" ויש "אין". אם כך יש גם "עדיין אין יש ואין אין" אם כך יש "עדיין אין אין יש ואין אין אין" הנה בדרך זאת מופיעים היש והאין. איני יודע איזה מהם ישנו ואיזה מהם איננו. הנה אמרתי משהו. אבל באמרי זאת האם אמרתי משהו? האם לא אמרתי דבר? אינני יודע.

קולות האדמה - החכם הסיני צ'ואנג-צה

22 July 2010

Continuous Deployment (a new Culture)

Eishay Smith introduced Continuous Deployment methodology last week at IBM Haifa and I think that once this methodology is adopted, it can turn your whole work (and life?) experience, that's why I'm sharing this.
Continuous Deployment (CD) takes "Release early, release often" to the limit, as long as the build is green, you can push code to production (see difference between release and production in Eishay's presentation), agility at its best. The talk presented architecture, tools and culture needed for successful CD which is not trivial, OTOH, realizing its power makes it very easy to be convinced that adapting CD will only be useful (of-course, when it make sense - not all systems can be developed using this methodology - I think).
Best analogy to CD (as presented in the presentation and here) is the answer to the question: "What's better to use to irrigate a ground? Bucket or Hose?". I'll keep finding the answer to you.

Will it work for you? Dilbert will answer that


Useful links:

21 July 2010

Nice Design Patterns question

Question:
Rewrite Item, Paper, Scissors, Rock classes without using reflection (instanceof in particular).

========================================
public abstract class Item {
//return 1 if the receiver wins, -1 if it looses,
//0 otherwise.
public abstract int play(Item that);
}
public class Paper extends Item {
@override public int play(Item that) {
if(that instanceof Rock) return 1;
if(that instanceof Scissors) return -1;
return 0;
}
}
public class Scissors extends Item {
@override public int play(Item that) {
if(that instanceof Rock) return -1;
if(that instanceof Paper) return 1;
return 0;
}
}
public class Rock extends Item {
@override public int play(Item that) {
if(that instanceof Scissors) return 1;
if(that instanceof Paper) return -1;
return 0;
}
}
public static void main(String[] args)
{
Item rock = new Rock();
Item scissors = new Scissors();
if(rock.play(scissors) > 0)
System.out.println("Rock Wins");
else if(rock.play(scissors)
System.out.println("Rock Looses");
else
System.out.println("Tie");
}
========================================

19 July 2010

99 Bottles of Beer in 1342 different programming languages

99 Bottles of Beer is a popular easy-to-memorize song to sing on long trips to pass some time. This site includes programs in 1342 different programming languages that simply generates the lyrics of this song.

The JS version is cool :-)


09 July 2010

Code Smells

I believe that writing a well structured code is one of the hardest important capabilities that a programmer should develop to achieve high quality code, however, sometimes we are forced to code dirtily since time equals money, not to mention how hard is it to understand and modify someone's code who didn't think that others would read it.
Code Smells are some rule thumbs that helps pin-pointing to a location of weak code, some code smells are contradictory, but learning them will help pointing to a code which needs improvements, and more important, keeping them in mind will prevent you from writing stinky code in the first place.
Here you can find a list of the most frequent code smells, simply and well explained, and here you may find some more detailed info.