Sunday, 15 August 2010

java - Why should I not give null a meaning? -



java - Why should I not give null a meaning? -

i reading tom hawtin - tackline's profile other day , read commandment:

please don't give nulls meaning. throw npe.

and wondered 2 things regarding first sentence: how why?

first, why. why?

second, how. allow me give example:

bigdecimal sales = ...; bigdecimal cost = ...; bigdecimal turn a profit = sales.subtract(cost); // turn a profit margin = turn a profit / sales bigdecimal profitmargin = profit.divide(sales, 20, roundingmode.half_up);

here, calculating turn a profit margin. yet sometimes, sales 0. so, in case:

bigdecimal profitmargin = sales.compareto(bigdecimal.zero) == 0 ? null : profit.divide(sales, 20, roundingmode.half_up);

we profitmargin null when there no sales. makes sense, right? there improve solution? maybe argue turn a profit margin 0 when there no sales, that's not exclusively accurate. argued 0 sales gives infinite turn a profit margin. neither 0 nor infinity accurately describes zero-sales turn a profit margin. undefined works best. exactly null communicates.

this 1 of many instances imagine null having useful meaning communicates lot.

am misunderstanding commandment? how handle above situation without null ??

java null

No comments:

Post a Comment