Wednesday, 30 July 2008

To singleton or not to singleton

A colleague (Jacques or David L.?) pointed out an article explaining why singletons are evil, and they should be avoided:

http://blogs.msdn.com/scottdensmore/...27.aspx

Although there are some valuable points coming from experience, I can't say that I totally agree with it. This article makes a better representing of my thoughts:

http://www.ddj.com/cpp/184401625

I'll try to come up with my own explanations as objections :)

1. "Singletons are almost like globals, and since globals are bad, singletons are bad."

In my opinion, the first reason why global variables are bad is that you have almost no control over initialization or modification operations over them. There's a global variable in the global scope who knows where it's coming from, who and when initialized it, does it contain valid information... Second, probably the strongest objection to globals is, when you keep writing code depending on globals, those globals sit in the centre of your design with an extremely tightly coupled fashion, Turning your whole code domain into a single 'deadly complex finite state machine'. [Not mentioning about debugging problems of such a code]

But they don't apply for singletons. You know when a singleton is initialized (lazy to death, if you like), and that the class initializes itself. It still only publishes an appropriate interface with read-only members, etc.

2. "Code that depends on a singleton is hard to unit-test."

Well, it's completely right. But it's not the fault of singleton objects, It's weakness of your testing framework. If you really want your objects to be stateless at the beginning, then I'm sorry but you have to well-write those Setup() and TearDown() methods, even it comes with a cost of dynamically loading and unloading many dlls.

3. "Don't use singletons, write a 'factory method'".

Well, this is possibly the most ridiculous one. A factory method, if it doesn't incorporate 'static' concept, can't do what a singleton does. And if it incorporates the static concept, it actually IS a singleton.

4. "Singletons screw polymorphism."

I don't have any objection to this. It's completely true. They do screw polymorphism. But you may have deeper problems with your design if you think an object 'will have only one instance' and there are going to be more than one objects subclassing the previous one. I better seal the singleton with a 'sealed' or 'final' keyword and take a French leave.

My objections don't eliminate the fact that singletons are abused. But I think the answer to this singleton deal is old and classic enough not to make me seem smart: "It depends.". It's always better to pass a reference to your single-instanced-object when you can, for many reasons like clear representation of coupling. But there will always be some cases you'll end up with ridiculously complex solutions just to avoid an innocent sweet singleton. It's a trade-off decision.

Tuesday, 29 July 2008

C# and beforefieldinit

C# and beforefieldinit

I didn't know that explicitly defining the static constructor could have an effect on initialization time of implicitly initialized members!

Friday, 25 July 2008

Yet another wishlist for programming languages, part 2: Inverse enumeration

How do you enumerate an IEnumerable inversely, from the last to first? Sometimes I need it. Maybe there can be a MovePrevious() method in the IEnumerator interface...

Please drop a comment if anyone thinks it's not 'doable' or why it's a bad practice :)

Thursday, 24 July 2008

Yet another wishlist for programming languages, part 1: 'local functions' or 'parameterized labels'

Well, the only languages that I can say I'm confident to talk about are c#, c++, php and vb. It means that I may be surprised to hear some languages do already have the features I wish. But I need to start from somewhere. Here we go!

I want 'local functions'. Or 'embedded functions' if you like. Javascript already has them, thanks to its functional programming basis. The problem is, I want to implement a piece of my algorithm as a function, but I don't want to publish it to other methods in that class. The think I'm looking for is written some like this in javascript:

function mainfunc()
{
var subfunc = function(args) { .... }
}

I dream about something like this in c#:

public void mainfunc()
{
bool subfunc(int args) { ... }
}

Or we can extend something we already have, labels, to 'parameterized labels'. It doesn't satisfy the requirement in my mind, because label-goto pairs cause a different impact on the program flow, which may lead to extra complexity of your overall algorithm. Parameterized labels may seem like this, in c#:

public string mainfunc(
{
if (...some condition...)
goto returnOne("foo");
else
goto returnTwo("zoo", "(two)");
// do some unrelated stuff
returnOne(string s):
return s+"(one)";
returnTwo(string s, string s2):
MessageBox.Show(s, s2);
return s+s2;
}

As you can see, it becomes something else, but it's still useful. It was also possible to do the same with the help of some variables and a couple of if statements, but I think this adds to readability and overall maintainability of the code. Of course it may also lead to that exaggerated old saying about 'spagetti code', but it depends on how careful you use labels and how much you care about overall simplicity of the code.

Thursday, 3 July 2008

Generic and efficient paging query for SqlServer and Oracle

A friend just pointed at an old post of mine in my blog
in Turkish. Basically, it's a parameterized wrapper query
which returns rows in an interval among the results
of a given query.


It's possible to implement this the same way in
both Sql Server 2005 and Oracle 10i. I had tested it quite
well to assure that it's better than alternative methods.
I had implemented this solution for our XSLT-enabled
data and view framework for asp.net 2.0, while I was
working in Netsis.


Assumed that your raw query is:

SELECT * FROM friends;

And you need just last 10 records from a 4million-records
table. (you're very popular)

You need to wrap it this way:

WITH
RawTable as ( SELECT * FROM friends ),
NumberedTable as
(SELECT *, ROW_NUMBER() OVER
(ORDER BY @@IDENTITY) AS rownum
FROM RawTable)
SELECT * FROM NumberedTable
WHERE rownum <> 3499990

As far as I can remember, It was quite better than these
alternatives:

- Server-side cursors of ADO.NET on SQL2005
- Embedded subqueries with two seperate SELECT TOP N

And using ROW_NUMBER() over @@IDENTITY keyword
had helped a lot, instead of giving it a name of a column
to order. It was both fast and generic.

Use responsibly :)

Sunday, 27 April 2008

How to switch between .H and .CPP files in visual studio.

I've written a macro for this, since I don't know any existing commands in VS.

Sub SwitchBetweenHeaderAndSource()
Dim oldFile As String
Dim newFile As String
oldFile = DTE.ActiveDocument.FullName
If (oldFile.EndsWith(".cpp")) Then
newFile = oldFile.Replace(".cpp", ".h")
Else
If (oldFile.EndsWith(".h")) Then
newFile = oldFile.Replace(".h", ".cpp")
Else
newFile = oldFile
End If
End If
Dim pi As EnvDTE.ProjectItem
pi = DTE.Solution.FindProjectItem(newFile)
If (Not pi Is Nothing) Then
pi.Open().Activate()
End If
End Sub

You can write this macro in macro explorer, which you can find in Tools->Macros menu.
To assign a keyboard shortcut, you can go to Tools->Customize and click the Keyboard button. On that window you can find the macro and assign it a keyboard shortcut. I'm using Ctrl+"

Tuesday, 1 April 2008

This summer

I had applied to Realtime Worlds for a summer placement job. I got a quiz, and an interview today. I've got an email that says I'm accepted for a summer placement, I'm quite glad to hear that :)

I'll finish my coursework earlier and go to turkey for a three-week holiday with family&friends, and from the beginning of the June, I'll be working at RTW for three and a half months. Yee-haw cowboy!

References:
A saying that Raymond Chen has used in this article:
- Yee-haw cowboy: http://blogs.msdn.com/oldnewthing/.../45481.aspx
A great latin-jazz album from Ayhan Sicimoglu:
- Friends&Family: http://www.amazon.co.uk/Friends-Family-Sicimoglu....