It’s not magic – it’s floating point math
December 26, 2007 on 4:29 pm | In Uncategorized | No CommentsPlease remember that 3 / 12 is not always 0.25!
Take this example:
int i = 3; Console.WriteLine(i / 12);
You will get 0. I admit it could by a little confusing at first but I assure you, there is nothing wrong in the way JIT thinks. We dividing an integer over a… integer. What we are getting? Well, of course an integer! Is it not what you expected? How to fix this? Well the easiest way is to:
int i = 3; Console.WriteLine(i / 12.0);
You will get 0.25. Why? Well 12.0 is a double so the whole equation will by a double. You can check this easily with:
object o = i / 12; Console.WriteLine(o.GetType()); o = i / 12.0; Console.WriteLine(o.GetType());
So we all have to pay for strong typing and it is in your best interest to remember that!
By the way
int i = 3; int zero = 0; Console.WriteLine(3 / 0); Console.WriteLine(3 / zero); Console.WriteLine(3.0 / zero); Console.WriteLine(3.0 / 0);
3/0 won’t compile. 3/zero will throw an exception. 3.0/zero and 3.0/0 compile an run without a problem, they return +Infinity.
Oh, and one more thing (from my financial world of knowledge). 10% equals sometimes 11%!
int fullPrice = 100; float discount = 0.1F; Int32 finalPrice = (int)(fullPrice * (1-discount)); Console.WriteLine("The discounted price is ${0}.", finalPrice);
You will find this and other examples in good article about Floating Point in .NET.
The power of image – merging in SVN
October 22, 2007 on 12:08 am | In Uncategorized | 1 CommentI’ve recently read a short explanation of joining in SQL. I was simply amazed how ease it was to explain fairly complicated matter with few well chosen pictures. Please read it, no matter how good are you in SQL – it will surely help you next time you will have to explain joining in SQL to someone else.
I’ve decided to try the same way to taking SVN branching and merging as a target.
To remind you. When you are using the source control system like Subversion (SVN) you can always branch. Meaning you can take a copy of your current sandbox and check it in as a new “path of development” in your SVN server. From now on can work either on your origin branch or newly created branch. The two branches are not separated eternally. You can always merge them. But it is not so ease at the first time. It will take a while to grasp the details.
Lets say we have a main branch of development placed in /trunk and we’ve branched it at revision 101 to /branches/x (r102). Someone works on /trunk (fixing bugs) and someone else on /branches/x (making a new design). The /branches/x is to by merged someday with /trunk, but in a mean while you don’t want the two branches to drift to far apart.
What will you do? Merge your last revision in /branches/x with your last revision in /trunk right? Well it is not so easy! You have to merge the /trunk at revision you branched to the HEAD with you working copy. Not so clear, right? Lets look at this image.
You’ve branched at revision 101 and right now you are on revision 110 at you /trunk. And you want all the changes in your /branches/x – not to drift to far away. So you have to start at r101 and go all the way to r110 and apply all the changes to your working copy.
In tortoise it would like this:
The same thing is when you are merging the changes in your /branches/x with the /trunk.
You have to traverse all over you /branches/x from the time you’ve separated from /trunk to the last change you’ve made in /branches/x and apply everything to your working copy. Voila!
IProgrammable goes multilanguage
October 14, 2007 on 7:55 pm | In Uncategorized | No CommentsDobra bez żartów. Właśnie zainstalowałem plugin do WordPress o nazwie Gengo i sprawdzam jak na IProgrammable wyglądają polskie ogonki. Żeby nie zostawiać was z bezsensownym postem testowym rzucę trochę treści.
Przytoczę wam małą anegdotę. Uczestniczę w moim pierwszym kursie programistycznym Microsoftu. Prowadzący najwyraźniej programistą .NET nie jest ale myślę sobie będzie dobrze. W końcu prowadzący przede wszystkim powinien być dydaktykiem i porządnie przekazać mi wiedz, ze którą moja firma płaci prawie trzy tysiące złotych. Prowadzący pyta:
- A wiedzą państwo jak w C# tworzy się parametry opcjonalne?
Ki czort, myślę sobie. Nigdy o czymś takim w .NET nie słyszałem i próbuję naiwnie:
- Nie wiem ale spróbowałbym polimorfizmem.
- A właśnie, że nie wystarczy użyć słówka optional – odpowiada pewnie prowadzący.
Kompletnie zwątpiwszy w swoją wiedzę i po troszę ciesząc się faktem, że będę mógł pochwalić nowo zdobytą wiedzą na blogu przeskakuję do VS by przekuć metal puki gorący. Niestety efekt był opłakany. W C# nie ma czegoś takiego jak parametry opcjonalne. Po prostu!
C# 3.0 – .NET Framework ?
September 30, 2007 on 12:32 pm | In Uncategorized | No Comments
I’ve written an article about C# 3.0 for a polish programmers magazine Software Developer’s Journal. That’s not my first article but the first one to hit the cover and by the issue lead. Great, right? Well I’m afraid not! Why? Because of embarrassing mistake on the cover:
C# 3.0 has nothing to do with .NET Framework 3.0. The new C# version will by introduced with .NET Framework 3.0 that comes with new Visual Studio 2008. The third version of framework is essentially the same with the second but enriched with a bunch of foundations (WPF, WCF, WWF). This information appears in the first paragraph of my text!
I’ll ask the editorial office to consult the cover with my the nest time. I’ll spare myself the shame.
Who needs DBNull?
September 17, 2007 on 8:23 pm | In Uncategorized | No CommentsI’m currently taking part in my first MS certified .NET training. I’ll write some more about this training after it’s over, but now I have to share one thing with you. Once again I notices that DBNull is causing more confusion than it is worth. A certified .NET instructor had a hard time describing it to course attendees. Some time ago I had a long conversation about it. Both time I couldn’t help my self thinking: “who to hell needs this DBNull”. Because in .NET DBNull is not equal null. DBNull is a little extraordinary data type. It is used to describe a value from DB that does not exists in opposition to a value that exists but is null. Hmm… I don’t buy it. And a course attendee was not buying it also. We have defined a class like this
public sealed class ProductSummaryStatistics { private readonly string mDescription; private readonly int mProductCount; private readonly decimal? mMinimumPrice; private readonly decimal? mMaximumPrice; private readonly decimal? mAveragePrice; //... }
We ware told what the nullable types are. I had BTW impression that our trainer was not 100% clear about the difference between value and reference types, since with that knowledge the difference between decimal and decimal? is crystal clear in a second.
But back to our story. We were told to use a helper method co convert the “may by null” values to the fields in our class. That’s the helper code:
public static Nullable<T> DbValueToNullable<T>(object dbValue) where T : struct { Nullable<T> returnValue = null; if ((dbValue != null) && (dbValue != DBNull.Value)) { returnValue = (T)dbValue; } return returnValue; }
My coulage could not understand why do we have to convert our DB data that might by null to nullable type. And to by frank I don’t understand neither. And it is really not important that my lack of understanding is other than my colleague. We don’t need DBNull!
.NET Remoting Articles
September 11, 2007 on 7:39 pm | In Uncategorized | No Comments
The good folks at Software Developers Journal are working hard on delivering good content to polish speaking software developers community. They recently made two of my older articles available online (mid 2006). The articles are both about .NET Remoting (The basics of .NET Remoting and Extending .NET Remoting). This rather ascending technology (we have WCF) could by interesting today too. There is a lot of work done with plain old .NET Remoting. You will read there about the basic concepts, about using the communication techniques given by Microsoft, configuration them and implementing your own communication channels.
RTFM you idiot (me)
September 3, 2007 on 12:42 pm | In Uncategorized | No CommentsHave I told you lately that reading manuals is good thing? Wow, what a discovery! Believe me, reading the documentation, manuals, MSDN will save you time. One day spend on reading about .NET Framework fundamentals will save you 2 of debugging, and wandering why… I’ve recently found a nasty behavior in my search by example routine. I thought that I know enough about NHibernate to use find by example in discoverable mode (its when you are programming with Intelisense as your help and guide
. My code looked like this:
Customer exampleCustomer = new Customer(); exampleCustomer.FirstName = view.FirstName; exampleCustomer.LastName = view.LastName; string[] excludeProps = new string[] { }; CustomerList customerList = customerDao.GetByExample( exampleCustomer, excludeProps);
Nothing extraordinary. Right? the exampleCustomer object gets the FirstName and LastName property from view. Than without excluding any property I went to GetByExample to get what I wanted. It worked! Until the customer without FirstName (a company). What did I get when view.FirstName was = “”? A list of all customers with first name matching the attribute with last name ignored! Why? Because the NHibernate reference manual says:
“By default, null valued properties and properties which return empty string from the call to ToString() are excluded”.
Right!
Gotcha C# operator
August 25, 2007 on 3:13 pm | In Uncategorized | No CommentsSometimes I have a positive feeling of “what’ta f…” reading someone else code (at a contrary to negative feeling of the same sort wchich I get way to often). Recenty I’ve found the ?? operator in C#. And really I didnt know it could by used it this way:
string s = null; string s2 = s ?? "remembered"; string s3 = s2 ?? "vorgotten";
The ?? operator returns the left operand if it not equalls null and the right one when it is. Simple and usefull!
Currency dispaly tip
August 10, 2007 on 1:09 pm | In Uncategorized | No CommentsTask: print a price according to a culture information but remember “we don’t need the damn ? (or $) sign”!
Well:
public static string FormatCurrency(double price) { CultureInfo ci = new CultureInfo("de-DE"); NumberFormatInfo nfi = ci.NumberFormat; nfi.CurrencySymbol = ""; string s = price.ToString("c", nfi).Trim(); return s; } public static double FromCurrency(string price) { CultureInfo ci = new CultureInfo("de-DE"); NumberFormatInfo nfi = ci.NumberFormat; nfi.CurrencySymbol = ""; double d; double.TryParse(price, NumberStyles.Currency, nfi, out d); return d; }
An please print the percentage but without the damn % and ALWAYS with 5 decimal digits.
public static string FormatInterest(double interest) { CultureInfo ci = new CultureInfo("de-DE"); NumberFormatInfo nfi = ci.NumberFormat; nfi.NumberDecimalDigits = 5; string s = interest.ToString("n", nfi).Trim(); return s; } public static double FromInterest(string interest) { CultureInfo ci = new CultureInfo("de-DE"); NumberFormatInfo nfi = ci.NumberFormat; double d; double.TryParse(interest, NumberStyles.Number, nfi, out d); return d; }
PS. Prase the Windows Live Writer and VSPaste plugin (it lets you paste the Visual Studio code snippets with proper text highlighting).
All the fuss about FizzBuzz
July 31, 2007 on 11:23 pm | In Uncategorized | No CommentsRecently I’ve read once again about the FizzBuzz. For those not familiar with this term: Fizzbuzz is a taks that could by used while interviewing a software developer for a job. It’s is essentially a trivial task of listing all the numbers from 1 to 100 but replacing multiples of 3 with Fizz, multiples of 5 with Buzz and multiples of both with FizzBuzz. A task that an intelligent person, with some background in software development, suppose to crack in 5 (10 tops) minutes. But of course there are good solution and better solutions. I’m thinking about the solutions provided after Jeff Attwod post on his blog. People are so eager to post a solution without thinking about the problem through. They are forgetting to print the number that does not match FizzBuzz pattern. Or a white board problem: you use > instead of < in a for loop. Is it bad? Actually I think it’s not. The great idea with giving such a task, while interviewing is not to get a perfect solution. It is to see how the interviewing person thinks, how doe’s she get through analyze and “implementation”. You should seek for a perfect solution, but you have to praise the better ones. And plase! PLEASE! Give the “software developer to by” a task involving software development while interviewing. Because if you will not, you could get someone without a value. Really I’ve seen enough large mouths that could lie their way all up to the skies, but were miserable software developers.
Originally published at Sunday, May 13, 2007
Powered by WordPress with Pool theme design by Borja Fernandez.
Text © Marcin Kawalerowicz. Hosting CODEFUSION.


