September 26, 2010 C#, Design Patterns, Java, Opinion, Personal, Success 12 comments
September 26, 2010 C#, Design Patterns, Java, Opinion, Personal, Success 12 comments
Yeah, title sounds not logically, but you will understand in a few why it is still relevant to this blog post.
It was and it is a good idea to…
In one of my blog posts I’ve decided to have all of the GoF Design Patterns written with Java. And idea itself is very good. Having all of the design patterns written by your own with you own examples gives you understanding of the DP that you cannot gain anywhere else plus to that if you have industrial experience of using all of them you can start think that you are guru of DP.
Process of writing my post on one of the Design Patterns looks like this: I read chapter of the GoF book on the particular DP, then I think up my own example if I do not have it already in my mind and after I’m done with some preliminary ideas I search over the internet for interesting articles on it and probably rethink some of the aspects of my example. After all of that I proceed to writing blog post and source code with Java.
Conclusion: Awesome and probably one of the best ways of learning DP is to have your own example of using it and industrial experience.
Design Patterns articles
One of the intents of having DP written in Java was to familiarize with that language. But it turns out that I did not learn much from Java (except of few things). Also few months ago I started keeping up Tuesday’s Design Pattern on the Lviv .NET User Group Page. Since it is .NET specific UG, I used to do following: 1) translate and 2) translate. In first place it is translation from English to Ukrainian and in second from Java to C#. When with item number one I have to apply some logic and rephrasing I cannot say the same about second item. I just copy code-paste code into Visual Studio and change few keywords. So what do I learn regarding of Java in this case?
I will continue learning Java, but I have to consider better way of doing it. I will also continue writing about Design Patterns, but with examples in C#.
Conclusion: Learning another programming language (Java) is really great idea, but be sure that you choose right approach of doing this.
First free e-book
On the road to Lviv I got perfect idea to start my first book. Of course this cannot be comprehensive stunning author’s book, but I have to start with something. In other words some probing book and this could be this “try it” case. I’m almost sure that there are no books about GoF Design Patterns in Ukrainian. (I suppose that there are in Russian, which can be easily understandable for most Ukrainians…)
How this book will be different?
Why do I need it?
I understand that this book might not be popular at all. But I have to start with something and plus to this it will help me familiarize with the whole process and build my confidence for future.
Also if you have some doubts about my idea I have a question for you: “Have you ever dreamt about your own book? If yes, do you have at least small book written?”
Conclusion: Never be skeptic about starting your first book. It might be a huge step to your success as anything else you are hesitating about but still dreaming about it!
August 11, 2010 .NET, C#, HowTo No comments
As you may know recently I got junior to mentor him. In order to understand his capabilities and knowledge I asked him to do couple of things, like explain me one Design Pattern he knows, explain SCRUM and write the simplest .NET Remoting. So that was yesterday and today I verified that he failed with .NET Remoting, but it doesn’t mean that he is bad. He just need learn googling art more. I asked that for next day, and gave him stored procedure to write. Hope he will be smart enough to finish it till I come tomorrow from my English classes.
.NET Remoting
To ensure that I’m not asshole that asks people to do what I cannot do, I decided to write it by my own and see how long will it take for me. It took me 23 minutes. Hm… too much, but I should complain at VS about “Add Reference” dialog.
So here we have three projects in Visual Studio: one for Server, one for Client and of course Proxy class shared between client and server.
Shared proxy class ChatSender in ChatProxy assembly:
Server (ChatServer):
Client (ChatClient assembly):
My results
June 9, 2010 .NET, C#, Concurrency, Performance 6 comments
I agree that title doesn’t promise a lot of interesting stuff at first glance especially for experienced .net developers. But unless you encounter some issue due to incorrect usage of timers you will never think that root is in timers.
System.Threading.Timer vs. System.Windows.Forms.Timer
In few words what are differences between Threading and Forms timers just to start with something.
System.Threading.Timer executes some method on periodic bases. But what is interesting is that execution of method is performed in separate thread taken from ThreadPool. In other words it calls QueueUserWorkItem somewhere internally for your method at specified intervals.
System.Windows.Forms.Timer ensure as that execution of our method will be in the same thread where we’ve created timer.
What if operation takes longer than period?
Let’s now think what will happen if the operation we set for execution takes longer than interval.
When I have following code:
my application behaves well – prints “a” twice a second. I took a look for number of threads in Task Manager and it stays constantly (7 threads).
Let now change following line: Thread.Sleep(500) to Thread.Sleep(8000). What will happen now? Just think before continue to read.
I’m almost completely sure that you predicted printing “a” every second after 8 seconds have passed. As you already guessed each of the “a” printings are scheduled in separate threads allocated from ThreadPool. So… amount of threads is constantly increasing… (Every 1.125 seconds :) )
Issue I’ve been investigating
Some mister X also figured out that Console.WriteLine(“a”) is critical and should run in one thread, at least because he is not sure how much does it take to execute Thread.Sleep(500). To ensure it will run in one thread he decided to have lock, like in code below:
Yes, this code ensures that section under lock is executed in one thread. And you know this code works well unless your execution takes few hours and you will be out of threads and out of memory. :) So that is an issue I’ve been investigating.
My first idea was System.Windows.Forms.Timer
My first idea was to change this timer to the System.Windows.Forms.Timer, and it worked well in application, but that application is able to run in GUI and WinService modes. But there are so many complains over interned to do not use Forms.Timer for non UI stuff. Also if you put Forms.Timer into your console application it will simply not work.
Why System.Timers.Timer is good toy?
System.Timers.Timer is just wrapper over System.Threading.Timer, but what is very interesting is that it provides us with more developer-friendly abilities like enabling and disabling it.
My final decision which fixes issue is to disable timer when we are diving into our operation and enable on exit. In my app timer executes every 30 seconds so this could not be a problem. Fix looks like:
And it looks that we don’t need lock there, but I left it there just to be sure is case if SomeOperation will be called from dozen of other threads.
MAKE DECISION ON TIMER BASING ON THIS TABLE (from msdn article)
System.Windows.Forms | System.Timers | System.Threading | |
---|---|---|---|
Timer event runs on what thread? | UI thread | UI or worker thread | Worker thread |
Instances are thread safe? | No | Yes | No |
Familiar/intuitive object model? | Yes | Yes | No |
Requires Windows Forms? | Yes | No | No |
Metronome-quality beat? | No | Yes* | Yes* |
Timer event supports state object? | No | No | Yes |
Initial timer event can be scheduled? | No | No | Yes |
Class supports inheritance? | Yes | Yes | No |
* Depending on the availability of system resources (for example, worker threads |
I hope my story is useful and when you will be searching like “C# Timer Threads issues” or “Allocation of threads when using timer” you will find my article and it will help you.
May 9, 2010 C#, Java, MasterDiploma, Opinion 4 comments
Is CLR worse than JVM or it is just because my code is bad?
Today I had conversation with one man, who is great defender and evangelist of Java related technologies.
We talked about some algorithm implemented by me with C#. That is implementation of SOM algorithm and Concurrency stuff for it. My concurrency implementation doesn’t show time improvements unless grid size is big. He was able to achive better result with small grid sizes.
There could mean two reasons:
Taking into consideration that I’m getting better results when grid is of bigger sizes I could suppose that in my algorithm there is code which takes constant (or near that) time and is not paralleled.
When I look at picture of Task Manager when my programm is executing I see that second processor has gaps when it does nothing:
This could mean only one: I need to take better look what else is executed in one thread in my application and could be paralleled.
Converting C# code to Java
But back to that man and Java. I said to myself that it is possible to move my code to Java if something.
C# to Java Converter
Download C# to Java Converter demo version from here. Since it is demo you could not convert more than 1000 lines of your code. Order costs 119$.
Because of that I was forced to remove all not necessary code. I removed all concrete classes that I’m not using and GUI, but that did not help. I did not know how much should I delete more.
Number of lines in my project/solution
I googled for line numbers in C# and found this nice tool:
Now I know that my program has about 4000 lines of code. I left about 980 lines of code in two projects that I needed and was porting them to Java separately.
Converter GUI
And converted them to Java:
Is conversion an easy task?
Conversion could be painful if you have a lot of code that interacts with system, like threads, reading and writing to files, reading configuration file, etc.
Also it was not able to recognize ‘var’ keyword. It shows me this:
I moved back to my C# code and changed all var to the explicit types. And regenerated Java code.
There were some troubles when I’m delivering from List<T> and doing some stuff around that.
This code:
I rewrote manually to:
Also Converter was not able to convert this:
The biggest challenge is ThreadPool and synchronizing threads tech-nicks. This requires lot of google search that shows me that instead of ManualResetEvent I could use CyclicBarrier and how to utilize thread queuing in Java.
P/S I need to find gaps in my code to show that at least CLR and myself are not so much bad things in this world :)
April 13, 2010 C# 2 comments
Today one of my colleagues bring me a present – a new blog post!
Please take a look on the following picture and think how could execution step into the if statement. See that oldPerson is null!
She has asked everyone if anyone knows how could this happen. Do you know?
Honestly my first thought was that it is something with Nullable<T>, or maybe method Find isn’t what we think about it. I had thought that it could be LinQ method, which is somehow wrong, whatever. But nothing of that is true. :(
She did not sent the whole picture so we did not know what is the type of oldPerson object. So far we don’t know the type and we know that “!=” behaves somehow different. That’s it! Operator is wrong and I won beer. (of course not :) )
So let’s take a look on implementation of the operator:
Do you already see where the problem is? It is definitely in line 11: if (ReferenceEquals(null, right)) return false;
if we will get null in right object it will say that null is not equal to null.
Reason why she needs that so much complicated is because she accesses properties of the object in return condition later:
return Equals(left.Name, right.Name);
April 4, 2010 .NET, C#, F# No comments
Renaissance of functional languages
We are at renaissance of functional languages. When I read blog posts I often see guys talking about functional programming and stuff related to it. Community wants more features that functional style provides for us. In response to that creators of languages and technologies are now introducing a lot of amazing cool features to make our life happier. They also create new languages, and so on.
What is going on with C# nowadays?
Let’s start with what we do have with C# nowadays. It has moved to functional side slightly. Introducing LINQ is big step in that direction. We are moving away from imperative programming to functional, for example this simple loop represents imperative way to work with list items.
Using LinQ we can have so much elegant functional syntax:
list.ForEach(Console.WriteLine);
So we pass function into function. Simply saying that is why we call this functional programming. If example above isn’t so bright take a look on next:
Another example of that C# is more close to those languages is introducing var keyword, which doesn’t mean that we can change type in further code like in dynamic languages, but that is thing which really helps us to write code without being really concerned about types, but the language itself is still strongly typed. If you would say here about C# dynamics, hm.. honestly I’m not a fan of that thing in C#, but maybe it gives some advantages for us.
Immutability
Few days ago I have heard podcast where guy from Microsoft .NET languages team spoke about different features that community had requested to language C#. One of them was immutability and it looks that they are going to introduce this in further releases (after 4.0 of course). So what is immutability? It is something that functional languages has by default and imperative hasn’t :).
For example we have
int number = 1;
number = number + 3;
We can change number as many times as we want. But the same in F# will produce compilation error:
(“<-” is assignment operator in F#). In order to make it work you will need another element result:
If you want variable with you 100% want to change you should declare this using mutable keyword:
Functions
So lets move to much interesting – declaring functions:
ten will be immutable variable which has value 10.
Are you familiar with parameter binding in C++ functors? It doesn’t matter but, currying of methods in F# reminds me that. Take a look how we get new method with mixing function multiply and using one frozen parameter.
Using F# library in other .Net languages
I did all this fun stuff with creating new F# library in Visual Studio. I viewed results of code which interested me with selecting it and pressing ‘Send To Interactive’ from context menu. Next what was interested for me is how can I use that dll in my usual C# program. So I created console application, added reference to my F# lib. Now I can use it like below:
See how things differs out there. Method is seen as method, immutable variables as properties without setter and mutable as properties with setter. Forgot to mention that FirstFSharpProgram defines with keyword module at the top of *.fs file.
Why?
When could F# be useful? Anywhere you would like. But as it creators says it has lot of multi-threading capabilities plus to that you write immutable code, which was the main root of stupid bugs in imperative programming. Plus to that you can easily use it in combination to other .NET languages.
Don’t miss chance to learn this language if you are interested in it.
Take a look on this elegant Fibbonachi solution: let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)
March 14, 2010 .NET, C#, Concurrency No comments
Here I have code that provides some explanations to the multithreading in .NET. Wrote it to refresh what I know on concurrency.
February 26, 2010 .NET, C# No comments
I have never used constraints for my generic classes. So in this article I just want to show how I’ve used it:
So for now I have ICustomer interface:
and two implementations like UsualCustomer and VipCustomer.
Also I’m going to have some OrderingProcessor which is supposed to be operating with different types of Customers. But when I want to call GetOrders method I just have not it in my list, like below:
but once I’ve changed the declaration of the OrderingProcess just a little bit, with specifying type of T
World has smiled to me and I’m getting what I want, please see:
I expect that you are laughing while reading this post. Maybe because this thing is too simple to write article/post on it if you are familiar with C#/.NET. Yes, but I have never tried it myself. Did you?
To make you laughing not so much loud let us take a look on another architecture:
As you see we can create specific VipOrderingProcessor and we are constraining it to use just VipCustomers or derived classes. This gives us opportunity to specify constraints on different levels of implementation.
But do you know what does another constraint new() mean?
This constraint specifies that TCustomer objects will have public default constructor, so you can write
var vipCustomer = new TCustomer();
This could be very useful for implementing Factory Design Pattern. I’m sure that next time I will need to develop whole family of Factories I will use constraints, since code could be much flexible in this case.
February 21, 2010 C#, Java, MasterDiploma 2 comments
Today I committed initial version of my Diploma Work Sources.
And there are few interesting things regarding to my first commit.
Thing One (Language)
I re-wrote all my last year course work from Java to C#.
And I did it all in about 12 hours. Its just amazing how my developing speed differs in eclipse and Visual Studio IDEs. As I remember same took me 50+ hours with Java + eclipse and I did all without enthusiasm.
I hate writing properties in Java
This is one thing where I do think that Java is kind more verbose than C#. There are some others, like “var”, etc. Microsoft works on improving C# language.
C#
public double[] Parameters {get; set;}
Java
private double[] parameters;
public double[] getParamateres(){
return parameters;
}
public void setParamateres(){
return parameters;
}
How important is your knowledge of IDE?
I would say that even more then knowing of language. Nowadays most of the languages are object-oriented, they all have similar principles and ideas and code looks almost the same. If we talk about C# and Java they are extremely alike.
I’m not very familiar with Java, but I can write Java code easily and if there are some Java specific gaps I quickly fulfill them with google search.
But when we talk about my speed of coding in eclipse IDE – it is really outstanding thing where my capabilities suck.
Code refactoring tool
That is another thing that could significantly increase your productivity. I’m using Resharper 5.0 Beta. Having experience of using it, I can think about what I want to have, but not how to type that.
Live templates that generates me unit test method after I just type “test”. Delivering from interface, I just created, without typing class name. Moving initialization of fields to the class constructor with single command. “Alt+Enter” just thing instead of me in contest of where mouse cursor is located and proposes me decisions. — these all are things why I love Resharper. I wrote complex architecture with about 40 classes in about 12 hours. It generates what I think.
Thing Two (Architecture)
I improved my Self-Organizing Maps implementation architecture significantly. What is did is having all implemented in really decoupled interfaces. Main learning processor is just like preparing dinner. You just add component and you do have what you want.
What is the benefit?
Now I’m able easily setup few dependency Profiles and experiment with them. So I can play with different activation, neigbourhood, metric and leaning factor functions, at the same time I can use different topologies like matrix and hexagonal.
Also learning process is now really encapsulated and to add Concurrency implementation should be easily.
Thing Three (I have same results with less effort)
To prove that I have same results I’ve used same application of my Kohonen Maps: classification of animals.
Here is input data list of different animals. Each row describes animal’s properties.
Here is result matrix:
Thing Four (Conclusion)
I’m really sorry that it is boring for me to have my Diploma written on Java. But I really think that my goal is to invent multi-threaded algorithm that could significantly improve SOM calculations. And I feel really comfortable with C#, so I can enjoy research work without spending time on convincing myself that I do need to accomplish all with Java.
But this doesn’t mean that I gave up with learning Java. No – I will continue implementing all GoF Design Patterns on this pretty language – see my table.