Saturday, December 12, 2009

Weekly Source Code: C# DateTime Developer Pitfall

Base upon my previous blog post that every language has some pitfalls I had a production issue and saw one of the pitfalls that C# have with the DateTime class which is part of the .Net framework.

I renamed this title since its more a pitfall of the developer not understanding the proper use of the DateTime class. The all point is that your telling the constructor to create a date, you don't tell it to work with increments.

In the next code you want to get the 1ste date of the following month:

DateTime currentDate = new DateTime(2009, 11, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.AddMonths(1).Month, 1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

So the answer is 01/12/2009 which is correct but what if you do the following:

DateTime currentDate = new DateTime(2009, 12, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.AddMonths(1).Month, 1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

Code is exactly the same, I just change the month to December since you want to get the day for the 1ste of Jan 2010 but the end result is: 01/01/2009. Ouch!!

Yes the DateTime object doesn't increment the year (2009 -> 2010).

To fix:

DateTime currentDate = new DateTime(2009, 12, 05);
DateTime nextDate = new DateTime(currentDate.Year, currentDate.Month, 1);
nextDate = nextDate.AddMonths(1);
Console.WriteLine("nextDate: " + nextDate.ToString("dd/MM/yyyy"));

You see that you can't increment in a DateTime.

Friday, December 4, 2009

For The Love Of C++

Alot of programmers that use more modern programming langauges (C#, VB.Net, Java, Python, Delphi etc) dish C++ by saying what bad language it is, how its the worse thing ever created etc.. But they don't know it (have you ever code any C++? have you ever even see any C++ code?) Don't dish something that you don't know...

Languages like C#/Java is very abstract, they hide things from a programmer like memory management that get managed by a garbage collector etc Where in C++ memory management get done by yourself via pointers (yes pointers are very difficult!) C++ have pitfalls, very bad once aswell yes but they can be privented by putting rules in place, use 3rd party libraries like Boost that support smart pointers for memory management (for this artical am not going to explain what smart pointers are) have code reviews etc. A programmer can write crap in any language, in C++ its just more easy for this you need serious programmers that take there job seriously that are willing to learn the C++ pitfalls and how to deal with them, are willing to read books like Effective C++.

C++ is powerful it teach you how to come close to understanding how the machine works, you learn new things / new ways of doing things all the time... its fun! Think abit beyond... The OS that you use (MS Window/Linux), your mouse driver, your Webcam, your iPod, your iPhone, your IM program like Skype etc are all written in C++ or some dialect of it (like Objective C)... the C# / VB.Net etc geeks can also stop moaning since do you guys know? the compiler for your language is written in C / C++.

So why does C++ have so many pitfalls?

To start, every language has some form of pitfalls... am studying for my Java Programmer Sun Certification and let me tell you, even Java got alot of pitfalls. C# aswell! So don't think C++ is the only language that you can write crap in, you can write crap in any language and any language can make you scream from frustration when you struggle with some weird issue that is actually a language pitfall.

C++ have alot of pitfalls, full books are written for them like Effective C++ (btw you also get Effective Java) get see the reason why we need to go back into history... (time Machine please!)

C++ was called "C for Classes" where Bjarne Stroustrup want to add object oriented programming (OOP) features to the powerful C programming language from his experience coding in Smalltalk, Simula etc. (interesting artical here) it was criptic way of adding classes but it worked and soon the name was given "C++" along with more languages features added over time... like meta programming, generics in the form of templates, run-time libaries like STL etc To keep C++ standard a standard committee formed, standards are there for a reason since it protect us my dear fellow programmers from one compiler vendor adding some language feature that isn't part of a standard meaning that when you ever wanted to move your code over to that compiler you will have issues - might not be at compile time but at run-time damaging your customer.

When adding a new langauge feature you add more complexity ontop of more complexity and you must keep backward compatiability! Why backward compatiability? Example: Python 3x isn't compatiable with Python 2x so how many developers ported there code over? Answer: Almost none, reason being that a programmer just don't have the time or resources to do a port, you can't tell the your boss/management to wait for a year for you to rewrite all the software (that can be millions lines of code) since business must go on... new products release, new customers, new features in the application etc. In the ISP world its a good example. So for C++ every new feature needs to be compatiable in different context together with other language features... its a difficult process, committee's fight about things for years... the new C++ 0x standard has been going on for over a decade now. So "0x" since you don't know when it will be release, it can be in 2020! that is why C++ has some many pitfalls and is so complex because of 30 years of history... languages like C# will go the same route or are already going the same route. The C++ standard committee just can't do what the Python guys did by "cleaning up C++" since millions of lines of code all over the world will break.

So to end this story... this the truth ladies + gentelman, don't dish something that you don't know the history about or ever even used before.


Wednesday, November 11, 2009

About SCJP Sun Certified Programmer For Java Exam

Questions from colleagues and readers of my blog, here is more information about the SCJP exam.

The SCJP exam is a theoretical exam with very tricky questions, it test your knowledge of the Java programming language which is the foundation of all future certifications like Java Developer, J2ME etc.

To study for the exam I suggest buying the SCJP Sun Certified Programmer For Java 6 Study Guide (R409.00) book and spend about a year studying, do mock exams etc until your sure you can pass the exam - its very difficult!

For help you can visit JavaRanch
Which is a website started by the authors of the SCJP book.

Phone Prometric Testing Centre on 0800 99 11 20 two weeks in advance, before writing the exams to book. Pricing can be checked with them.


Friday, November 6, 2009

Increase Visual Studio.Net 2008 Memory

For work I use Visual Studio.Net 2008 along with a lot of plugins like SQLPrompt etc also Team Foundation Server (TFS). Lately I've been getting out of memory exceptions when I try to checkin my code, after some searching I found that Visual Studio.Net only use max 2GB of RAM memory where my laptop has over 4GB of memory.

I found an article that explain how to hack Visual Studio.Net to increase its memory usage.

After trying it out it seams that its working! Hope someone else will find it helpful.

Monday, October 26, 2009

How Visual Studio.Net Upgrade Your Solution

Weekly source code for this week will be published a bit later

When opening an VS.Net 2005 solution in VS.Net 2008 to which version will the upgrade wizard try to upgrade your solution too? Answer: .Net framework 3.5

The upgrade wizard will always try to upgrade to the current .Net framework for that version of VS.Net for example:
  • VS.Net 2005: .Net Framework 2.0
  • VS.Net 2008: .Net Framework 3.5
  • VS.Net 2010: .Net Framework 4.0
You will be asked the question if you wish to upgrade but you can always say "No". If you say no then the solution will stay in the old version using the multi-target feature. if you wish to later upgrade (like making use of the new LINQ features in .Net framework 3.5) you can do so under the properties of the project.

Thursday, October 22, 2009

Follow-Up: Make Web Service Configurable

Base upon the comments of a reader on my last weekly source code posting is that there is an additional 2x ways to set the URL location of a Web Service:

string newUrl = "http://server/path/to.asmx";
MyService service = new MyService();
service.Url = newUrl;

Or in new C# 3.0 you can use object initializers:

string newUrl = "http://server/path/to.asmx";
MyService service = new MyService {Url = newUrl};

I still prefer using a constructor.

Wednesday, October 21, 2009

Tuesday, October 20, 2009

Weekly Source Code: Make Web Service Configurable

Sorry for the delay, been crazy at work.

In Visual Studio.Net you call web services like the old style ASP.Net web service (not new WCF) by adding a reference to the project using Add Web Reference option. In the pop up dialog you point it to the web service URL, Visual Studio.Net will then generate the required C#/VB.Net stub classes.

But its not to say that the web service will be at the same URL location expecially if you move between development - > QA -> production environments. How do you make the web service URL configurable?

The web service stub class Reference.cs (for C#) or Reference.vb (for VB.Net) has a URL property, you can always set this property in your code but its a nice way to rather do it when you call the constructor e.g.:

MyService service = new MyService(webserviceUrl);

You do this by adding the following constructor to the MyService class:

MyService(String theUrl)
{
Url = theUrl;
}

The downside (before Visual Studio.Net 2008) is that if you update the web reference (after adding an additional web method to the web service etc) the code get regenerated meaning your code will break and you will have to add the constructor again.

Fortunately Visual Studio.Net 2008 introduce partial classes which allow splitting definition of a class across multiple files.

The Reference.cs / Reference.vb class also is a partial class so you can add an additional partial class with the same name and same namespace:

public partial class MyService
{
MyService(String theUrl)
{
Url = theUrl;
}
}

Now you can update the web service reference without worrying about such problems.

So what is partial classes? Yes they allow you to split the definition of a class across multiple source files but why? In this sample it show that its for code generation mainly since you normally generate code then add your own additions (like a constructor in this case) but if you re-generate your custom code is lost. Partial classes (and later on I will introduce partial methods) resolve this problem. Why did MS add it? Look at LINQ to SQL which also generate code, now you can add custom logic like validation with partial methods without ever worrying that re-generation will break your logic.

Monday, August 31, 2009

Back From Holiday

Back from 3 weeks holiday :-(
Ready to work...

Wednesday, July 22, 2009

Java Programmer Certification, Back to MWEB and Going On Holiday

Hi :-)

A lot happened the last couple of weeks, mainly just busy with work.
I'm studying for my Java Programmer Certification (SCJP) base on JDK 6, on 1 August 2009 I'm also going back to MWEB at N1 city to work has a Java/C# developer. Still employed by Soliditech.

From 9 August 2009 my beautiful wife and I are going on a 3 week holiday

So I'm off to chat after my holiday with more interesting topics.

Thursday, June 25, 2009

Weekly Source Code: LINQ for Java Part 2

I hope everybody had a nice week, even if the winter is upon us - freezing cold with rain etc. Time to get the blankets / heaters out.

Last week I introduced JoSQL, this week I continue to show a sample JoSQL query... we start off with a keep it simple (KISS) sample with some points to remember.

Sample Query:

The goal of this JoSQL query is to get a list of contracts that all have a given product:

List contracts = .... // here we get a list of contracts

Query q = new Query();
q.parse("select * from com.sales.Contract where productId = :p");
q.setVariable("p", 5);
QueryResults qr = q.execute(contracts);
List contractResult = qr.getResults ();
  1. All JoSQL classes are kept in the org.josql package, Eclipse IDE will import these nicely for you.
  2. We start by creating a Query object instance this is where our query starts.
  3. q.parse will check your query for any issues, an exception will occure if the query is incorrect. Note that we need to provide the full package location of our Contract class else JoSQL wouldn't find the class. This can cause a problem if you refactor your code, like move the Contract class to a different package location but don't update the JoSQL query.
  4. The following line we set the :p variable using setVariable method.
  5. We then execute the query and put the results into qr which is an instance of QueryResults.
  6. contractResult will contain the result.
JoSQL uses reflection so "productId" in the query is a getter method like "getProductId()" on the Contract class.

Friday, June 19, 2009

Weekly Source Code: LINQ for Java

Its been a long couple of weeks due to my current work load, working average 12 hours+ per day isn't fun. So I finally got some free time over a lunch break to continue with my weekly source code.

At work Java is our main programming language but its not so advance like C# (not to start a language war here!) one of them are LINQ but LINQ is also available in Java!


What Is LINQ?

Language Integrated Query (LINQ) was added to C# 3.0 / VB.Net 9.0 in MS Visual Studio.Net 2008. Its a query language part of the underline language for easy query of information like a database, online resources like a webservice or in our case collections (list, arrays, hashmaps etc). Different LINQ providers existing for collections, databases, Amazon, Facebook, Twitter, LDAP etc. Visit Wikipedia for more about LINQ.

Let's Meet: JoSQL

JoSQL is LINQ for Java that allow you to easily query collections (lists, arrays etc) using a SQL line syntax.

References

Disadvantages:

  • No compile time checking since the LINQ code will only be evaluated when query.parse() method get called at run-time.
  • You need to indicate the full package + class name in your query
  • If you wish to use "NOT IN" or "IN" in the WHERE clause then you need to override the toString() method of the class since it needs to know which field to use to do the comparison with.

I will write more JoSQL samples in the next weekly source code. Also my solution to the toString() problem.


Tuesday, May 12, 2009

I'm Still Alive...

I haven't blogged for awhile but yes I'm still alive... just been very hectic with work and studying for my Java certification.

You can always follow me on Twitter to see what I'm up too.

Thursday, April 30, 2009

Looking For A Chess Partner

I love playing chess its a smart interesting game, I'm looking for a chess partner to play email chess against using Chess Rally.

If your interested send me an email.

Friday, April 24, 2009

JavaScript Isn't So Weak

Alot of developers think that JavaScript isn't a powerful programming language to be used for professional development.  

Yes JavaScript have some weak points (just like every other programming language) But if you look around you will find websites like this one where it show how powerful JavaScript is for writting online games.

JavaScript is even popular for creating ritch Web 2.0 applications that include technology like AJAX etc. 

So the lesson to learn is to never judge before you actual used it... Like you can never judge C if you never wrote a line of code in it.

There will be no weekly source code this week.

Wednesday, April 15, 2009

Weekly Source Code: JavaScript.... Big Reason Why It Sucks

Today in the Web 2.0 world you do alot of JavaScript coding being DHTML, all the set of frameworks (jQuery etc) or do AJAX. The biggest thing that all JavaScript coders (even the pros) moan about isn't how difficult it is to test/debug JavaScript (tools like Firebug or JavaScript support in MS Visual Studio.Net 2008 IE make this very easy) but the dreadful word: "browser compatibility".... Yes Internet Explorer (IE) vs Firefox etc. All the things that make you want to scream / run away crying!

Its such a pain for me, since I use Google Chrome as my main default browser so everything just works but then later I found that it doesn't work in IE because of some browser compatibility issue or a weird way that IE handle some JavaScript.... The main problem here is that the browser companies (Microsoft, Mozilla etc) doesn't come together and work on a solid JavaScript standard. Ladies & gents, that is the reason why we've language standards!! There is a promise that the next version of JavaScript will be standard accross all browsers but thats only "promises".

For example:
var name = "Lennie";
alert(name[0]);
where you want the first characters e.g. "L" but in IE (IE is always the bad child it seams...) it returns "undefined" :-(

So you need to write it:

var name = "Lennie";
alert(name.charAt(0));

this works fine in all browsers.

So something to consider when your coding in JavaScript again.


Wednesday, April 8, 2009

Weekly Source Code: PHP Say When Its The Easter Date

Today its Wednesday, 8 April 2009 in a couple of days on Sunday its Easter when we eat a lot of chocolate eggs and spend time with family.

Because Easter is always on a Sunday the date differs each year. By surprise I found that PHP has a easter_date function that returns the easter sunday date given a year or if no year parameter provided for the current year.


Nice if you want to run a special event on your website or offer free choclates on Easter (if you do please let me know!).

Happy Easter!

Tuesday, April 7, 2009

C Programming Quick Tips

David Bolton from C/C++, C# About.com created a C Programming Quick Tips page, very good if you want to see some nice C tips or post your own.

We went to Worcester to visit my parents over the weekend... was a very nice weekend beside the bad traffic because everybody is going to the KKNK.

Saturday, March 28, 2009

Weekly Source Code: No SPAM Email Link In PHP

This is a conversion of my original .Net No SPAM email trick where an email address get retreived via an AJAX call.

This sample uses PHP 5 OOP with the JQuery library written using Netbeans 6.5 IDE.

Get it here.

Monday, March 23, 2009

Weekly Source Code: The Art Of Debugging In MS Visual Studio.Net

Bruno Terkaly wrote 11 lessons (more to come) on the art of debugging in MS Visual Studio.Net 2008. Very interesting and a must read to catch some tips! Did you know that MS Visual Studio.Net can debug Javascript? :-)

Visit his blog for the 11 lessons or this list that list the first 10 lessons.

Have fun!

Saturday, March 14, 2009

Weekly Source Code: Ruby Setting Utility Class

Its a general task to store application settings so I wrote my own for the Ruby programming language

How to use:

Save the SettingUtil.rb file so that your application code can find it.

Add:

require 'SettingsUtil'
include SettingUtil

Save Example:

require 'SettingsUtil'
include SettingUtil

setting = Settings.new # create the settings object
setting.values = {"jabber_notifyme" => "true", "jabber_jid" => "lenniedg@gmail.com", "jabber_password" => "", "jabber_to" => "lenniedg@gmail.com"}
setting.save
puts setting.jabber_to

to save you need to set the values accessor which is a hashset then call the save method.

Load Example:

require 'SettingsUtil'
include SettingUtil

setting = Settings.new
puts setting.values["jabber_to"]

when creating a new object of Settings (remember its in the SettingUtil module) it will load the previous saved settings else you can just call load method directly.

Note:

There are 2x ways to get the settings value:

puts setting.jabber_to

OR

puts setting.values["jabber_to"]

in both cases it reads the setting of "jabber_to" from the values hashset.

If it can't find the setting the first option will return "none" by default where the second option will return a nil reference.

By default it save settings into a settings.config file, you might want to change that if you wish.

The source:

#
# Store application settings
# Settings get marchalled to a file and then loaded, you can refer to settings
# by getting them from the values accessor directly or calling a method
#
# Author: Lennie De Villiers
# Created: 12/03/2009

module SettingUtil
SettingsFileName = "settings.conf" # constant with the file name
attr_accessor :values
class Settings
def initialize()
values = {}
load()
end

def load()
if File.exists?(SettingsFileName)
f = open(SettingsFileName)
temp = Marshal.load(f)
self.values = temp.values
end
end

def save()
open(SettingsFileName, "w") { |f| Marshal.dump(self, f) }
end

def method_missing(method_name, *args)
if values != nil && values.key?(method_name.to_s)
return values[method_name.to_s]
else
return "none"
end
end
end
end

Tuesday, March 10, 2009

Weekly Source Code: Twitter IM Notification

Twitter has become a very populare social website where you tell the world what your doing in 140 characters.

You can always follow me on Twitter

Since I've started to teach myself the Ruby dynamic programming language you can use this Ruby script to send yourself notification to Google Talk when a friend post a message to Twitter.

Steps:

1) Download Ruby
2) Install Ruby and setup a path to C:\Ruby\bin
3) Install the twitter gem: gem install twitter
4) Install the Jabber gem: gem install xmpp4r
5) Update the script by adding your Twitter username and password, Google Talk username (like lenniedg@gmail.com), password and notification address (like lenniedg@gmail.com)
6) run the script: ruby TwitterIMNotify_share.rb

I love Ruby! :)

Friday, March 6, 2009

Write a Share Trading Bot Challenge

Programming can also be fun :-)

David Bolton from C/C++/C# About.com started a challenge where you must write a bot in C, C++ or C# where the bot must do share trading.

Visit the challenge webpage for more information.

Thursday, March 5, 2009

Weekly Source Code: PHP - Email Address Images

Sorry ladies & gents that there wasn't a weekly source code last week, work was crazy.

On beds.co.za which is one of the websites I'm working on, you will notice that the email address for an accommodation is actually an image and that there is in the HTML no "mailto:" tag. This is one way to prevent spammers from grabbing your email address from a website by converting the email address to an image and then use my No SPAM email link functionality (that I must still port over from .Net to PHP)

Here's the code that create the image

the email address get stored in $emailAddressEntity, for example "lenniedg@gmail.com"
@imagecreate is the PHP method that create the image.

After this you can refer to the image

Resources:

@imagecreate

Saturday, February 14, 2009

Weekly Source Code: Create A Table With Hyperlinks In PHP

A friend is busy with a website and asked me how to create a table with hyperlinks using PHP/mySQL so in this Weekly Source Code edition I will explain just how.

First you need to connect to the database, for this you use the mysql_connect method, then you run your select SQL query and ouput the result in HTML.

See the sample code.

If you wish to open the result in a popup window then call a Javascript function from the anchor tag's onclick event, in the Javascript function you can open a window with window.open().

Please Note:

- I pass the record id to the updateuser.php page, this is so that the page know which user I wish to update.

- I refer to the record in the row via its field name, you can also refer via its record position in the result for example: $row[1] refer to "Firstname" field.

- This will display all the records in the table, you can add some paging to the table to only display like 10 records at a time.

- For basic PHP you output HTML this way where your PHP and HTML code get mixed, its generally a good idea to use a template framework like Smarty where application code is seperated from the presentation.

References:

PHP mySQL Functions
PHP Manual

Friday, February 13, 2009

Altair 8080 - Bill Gate's Altair BASIC

The Altair was the first computer released to the public in January 1975 (check here for history) by MITS, it was a very ugly machine that could only be coded in machine/assembly language by flipping switches. Basically saying: "Real Programmer's Don't Need Keyboards!"

Bill Gates & Paul Allen wrote Altair BASIC which was Microsoft's first product.

I downloaded the Altair emulator and stuggled to get it working but after awhile I finally got it working coding my first "Hello World!" in Altair BASIC!! This is so good to use the first computer and popular programming language.

How to use:
  • Run the Altair emulator.
  • Load the disk with the Altair BASIC image.
  • Toggle (that is on e.g. binary 1) all keys from A15 - A8, A7 to A0 must be down.
  • Toggle EXAMINE
  • Toggle down A15 - A8
  • Toggle RUN
  • A console window will open with the Altair BASIC running.


Wednesday, February 11, 2009

Lucky Man: Weekly Cake

I'm a very lucky man! My wife is on a cake course so each week she must bake a cake.... so I'm lucky since it mean I'm going to get cake on a weekly basis :-)

Life is good to me!

See photo of the cake she came home with last night. Yummy!!

Tuesday, February 10, 2009

Weekly Source Code: Create A GUID In .Net

A GUID is a unique identifier that you can use as a reference since its always unique.

If you need a GUID without writting any code, then visit Get-A-GUID.com which will generate a GUID for you everytime you refresh the webpage.

The code below create a GUID in C# and then display it to the console window:

class Program
{
static void Main(string[] args)
{
System.Guid id = System.Guid.NewGuid();
Console.WriteLine(id);
Console.ReadLine();
}
}

You can also store a GUID to a database, more about that in a future post :-)

PS: Been hectic at work, will write more later.

Friday, February 6, 2009

Using God's Name

Something that has been making me really angry lately, so I just want to make an efford and talk about it.

Lately I've been hearing on the TV, in the IT world (as a programmer I'm part of the IT world) etc that people use God's name in swearing etc.

For example:

- When something good / bad happens then: "Oh My God!!" rather than just "Oh Shit!!!" or "Oh Fuck!!" I would rather use "Oh Shit!!" or "Oh Fuck!!" or some other swear word if you really want to use a swear word.

- Bill Gates (or some other rich IT guy) have "more money than God!!". Well God don't need money since everything He say happens. We need money... it anyway make us corrupt etc (what is currently happening in the economy is a good example of that)

- "A visit from God!!". Well depend upon your faith God is actually with you already or is coming. God wouldn't be interested to come ask you what is the latest programming thing you did - His more interested in your life/soul/well being etc. Not if you made another million dollars or wrote another cool application etc.

So to end.... to use God's name is not good... remember that there are people in this world that don't like it, even if you don't beleive in God that is your choice etc and myself (and we as children of God) shouldn't judge you by it but then please be considerate and not do this.

It all comes down to being considerate to someone else's beleive etc.... in goverment / by law they call it "human rights" but in plain English its called: "being a good human being" or just "doing the right thing".

Monday, February 2, 2009

Weekly Source Code: Default Controlling Access - Be Careful!

I've a general rule where I never assume defaults in a language, I always assign an initial value to a variable for example... assuming defaults caused alot of problems for me in the past expecially in languages like C or C++ where defaults can actually "hurt" you. Each language also has a diffirent default behaviour that you will see below with Java vs C#.

One of the rules is to always provide the control access level modifier in OOP languages like Java and C# (the 2x languages that I use alot).

For example:

According to the Java tutorial on Controlling Access to Members of a Class when you don't provide an access level modifier it assumes the class and package level access only. Class access is fine since you do want a member variable to be avialable in its containing class but package level access is where it can hurt you, for example:

package com.echosystem.core;

public class SystemCall
{
int status = 0;
// rest of the class continue
}

here if you've other classes in the com.echosystem.core package those classes can directly access the status member variable above so you're not following OOP rules where encaptulation is important - not to go into too much detail but encaptulation is good! Also if you've another class in another package location you will notice that you can't access this status member variable.

Its important in this case to write the above code as:

public class SystemCall
{
private int status = 0;

public int getStatus()
{
return status;
}

public void setStatus(int inStatus)
{
status = inStatus;
}

// rest of the class continue
}

Here you see that the status member variable is private (make it encaptulated into the class) and you control access to it using a getter and setter methods.

C# will continue in the next weekly source code - I do need to give you time to think about this hey! :-)

Thursday, January 29, 2009

Blog Layout Template Change

I changed the layout of my blog to a white background, this is because some readers found it difficult to read the blog.

Hope the new template is okay :-)

Tuesday, January 27, 2009

Weekly Source Code: Strings Are Immutable

Happy New Year 2009! :)

The String type that is actually a class in both Java and C# are immutable meaning that once you create it, it can't get changed and manipulating it will create a new string object.

This is import for when you want to populate a string in a loop (like a for loop) since everytime it will create a new string that have a performance impact on your code.

For example:

String val = null;
for (int i = 0; i < 100; i++)
{
val += i;
val += ", ";
}

The code above will create a new string object everytime for 100 times, you might not see or notice the impact but it does have a performance impact (test it if you wish).

Its better to use a string builder/buffer class and then append the string values to it since the object is only created once.

For example:

StringBuilder val = new StringBuilder();
for (int i = 0; i < 100; i++)
{
val.Append(i);
val.Append(",");
}

The above C# code use the string builder without performance impact.

Note that in C# its called the StringBuilder class where in Java its the StringBuffer class both is similar in functionality.

Sunday, January 25, 2009

Back From Uganda

Ladies & Gents!

I had a good trip to Uganda and is back to work today :) I was off-sick for a week since I had malaria that damaged my liver but the malaria is gone now.

I will post some photos and a story soon.