Monday, October 29, 2007

My reason for blogging

Why I blog? There are some reasons, but they are connected with each over:
  • Develop my skills in English language — many people think I'm rather good in English, but I think there is enough space for me to develop in this direction. May be my friend think that I'm good at English but this comes mush more from that they know it worse than me, not from that I'm good.
  • Develop my speech writing capabilities. This is close to previous but it isn't connected to particular language. This is ability to shape idea into clear explanation. And the language is a tool to express it to others.
  • Develop my mind. When I write about something I think about it. And what is more I watch this from different angles and have different points of view on it. As a result my brain works and moreover I could make my opinion about something having different points of view as a base. Overall blogging trains my brain so it will give ideas. And this links to previous reason: these ideas needs to be shaped into explanation.
  • Specially for programming blog: by blogging I share my knowledge (if anybody is interested in it), that will help myself not to forget results of my programming experiments and of course as in previous reason while wring post I analyze topic and shape my opinion and develop me programming mind.
All in all: blogging is an output produced my my mind by analyzing input from books and my experience.

[Update] Well, as you see sharing knowledge isn't my goal. But I think that is a very good use of blogs. So in future I think I'll add this to my reasons. Probably after I'll train myself in English :-)

Winter session exams: Programming is already passed

It's not a secret that I love programming :). And I'm rather good at it. So I've decided not to wait end of semester to pass all laboratory works on programming and passed last this Saturday! 9 works in 8 weeks — good result I think. And I won't need to pass exam on it. Now I only need to make a documentation to my coursework. So now I'll have more free time. :)

Dynamic and static languages

As I've mentioned I'm reading a "Design Patterns" by Erich Gamma. Yesterday I've finished reading about structural patterns. I have to say that this book contributed a lot to my understanding of object-oriented programming, not only in a way of giving information about patterns, but also about whole programming. While reading I've often found examples of difference between dynamic programming languages and static ones.

In most cases dynamic languages looked better that static. Some methods hard to implement in static languages are easy to implement or built in dynamic languages: creating prototypes, changing behavior of object on-the-fly, programming by interface not implementation. It's not a secret dynamic languages such as Perl, Python, Ruby, etc. usually require less amount of code lines than static like C++. This mainly provided by different approaches to code handling: static languages are usually compiled, while dynamic are interpreted.

Dynamic nature of languages like Python provide rather wide abilities to work with classes and objects but in most cases programmers doesn't need available but rather low-level features (does we need very often put definition of function in if-statement?). And the cost is slow execution speed. Moreover if there is an error in program developer will know about it only when interpreter will reach this piece of code, while some of such errors could be caught during compilation.

As I think, is that in most cases interpreted languages are enough good for very big range of application what is proved by current trends in programming. But compiling languages still are rather popular. They are much better in implementing complex algorithms which uses a lot of resources. I agree with J. Ousterhout in article "Scripting", that static languages are useful for complex data structures from basic data types, which are often accompanied by low-level difficult to understand algorithms; and with dynamic (scripting) languages we can combine this elements to systems. Present dynamic languages (at least as I know Python and Ruby) provide an ability to plug into program modules written on C/C++. Thomas and Hunt in "Pragmatic Programmer" wrote a lot about DSL (Domain-Specific Languages). They can be thought as scripting languages with very tight integration into application. I think in future we can expect not only the expansion of using of dynamic languages but also developing of more tight integration between them and static languages.

Wednesday, October 24, 2007

My Example of Factory Method Pattern

I found rather useful reading a "Design Patterns" and found some examples of those patterns in programs I've written or read. And some days ago I've used one of the patterns - Factory Method.

What was the case? I've wrote two types of collections for C#: Vector (casual array) and LList (Linked List). They have the same interface ISequence and sane base abstract class SequenceBase which implements most of operations leaving virtual only basic operations, such as Insert, Remove, etc. And I wanted to have tests for all methods for both implementations. I'm using NUnit, and I didn't wanted to have two test classes with identical content, in except of operation new. So what I've made:
  1. Wrote an abstract class with all test cases (e.g. SequenceTester). All test methods have their Test tag.
  2. Class defines an abstract method Instance, which returns an object of tested interface, ISequence in my case.
  3. In all test methods I use Instance instead of operation new.
  4. For each tested class I define a test class derived from SequenceTester. In have to implement only Instance method that returns an instance of tested class and tests for an implementation of interface is ready!
The only thing I need to care is to add a test class for each implementation. Rather easy? ;) And moreover generation of concrete test classes could be delegated to special tool run before test process and building of tests.

Whats is good, as I think, is that such an approach could be used to test all implementations of each interface. Write tests for interface in abstract class, write tool to search implementations and generate required test classes and you can be sure that this interface work well in all cases, or in other case you get a pointer(s) to error(s).

I think I'll try to use this approach in my practice and write such a tool to make concrete classes for tests of interface implementations.

Off-topic: While writing this post I again faced the question: why implement array and linked list with same interface? The difference in the way they work make some operations unsuitable for one type while be good for other, so why include these operation in common interface? I think it's the question worth its own article, so I'll explore this question in future.

Monday, October 15, 2007

What I've done and haven't done

Firstly, I had written this post to my software blog, but then I've decided that it isn't software-specific and should be posted here. However I'm too lazy to revise it and remove "programmisms" from beginning part.

It is useful sometimes to take a pause and look at what you wanted to make some time ago, what you have done, what you are doing, what's the progress on it and what you want to do.

What I've wanted and what's the result?
  • I've wanted to pass all these labs in different subjects. Success.
  • Successfully finish study at courses of databases. Success.
  • Daily read news from internet. Successful in whole, thought I've sacrificed some news-feeds because it is too hard to read 'em all. Success (may be not full, not sure)
  • Regularly write to my blog (now I have two blogs). Not very good results: I don't write much to them. Thought I haven't dropped and forgotten them, so Partial Success.
  • I've wanted to read a lot of books. From those in list I've read only "Code Complete". But I've read two another books: about C# and "Pragmatic programmer" (Aahh, I haven't written about that! Need to fix that in near future!). And now I'm reading "Design Patterns". And I really want to read any book about UML. Result: All in all I think that's a success, however not following first plan.
  • Write some software to practice. During summer I worked on Egnoly text editor. And now I continue to work with .NET Framework, have some projects in mind and write some code for libraries on C#. Success, not 100% but about 90%... :) Or I'm not objective and too love myself??? May be...
  • I still haven't got a girlfriend. It isn't programming of course but has an effect on mind and mental condition.
  • I still have got chaos on shelves I don't use regularly. Terrible, but there is a relative order on my desk :)
  • I haven't made my programming language. May be I'm too young for that. But this idea still in my head and don't want to go away, instead it becomes stronger and stronger after reading Pragmatic Programmer.
  • I wanted to use Test-Driven Development, nut still don't use it actively. However I regularly try to write tests for my applications. And they give the result! So I think that's a matter of time. May be I'll not become a TDD programmer, but the one who actively and properly uses tests. Result: 40% of Success.
  • I've taught myself to actively use scheduling. Now I use not a calendar but a Todoist and I often don't follow it but I've already have a place where my wishes and plans on this day are written.
  • Something more that a achieved and haven't achieved. Couldn't remember all of them.

What I'm doing by now?
  • Studying
  • Writing some soft on C#, not very useful, but some practice
  • Also reading Design Patterns: useful book, sure I'll write review about it!
  • Participating in open source project Battle for Wesnoth as a translator.

What I want?
  • Make such list and judgement of results rather regular.
  • Follow schedule that I'm making for myself. And make this schedule more wisely and realistic!
  • Develop my relations with human beings :). I don't want to communicate only with computers.
  • Still want to make scripting programming language.
  • Write software on C#: develop Egnoly, common stuff for .NET, and something new, i.e. tool to synchronise my desktop PC and laptop.
  • Study well in university.
  • Continue and develop my participation in OSS projects. May soon I'll be able to contribute to Wesnoth as a programmer? Or contribute to another project either as a programmer or translator.
  • Start project with my fellows. There is no concrete plans on it, now it's a long-distance target.
And again: I want to make this list more clear. At least more clear for me :) And update it regularly.

[Update] Add target to communicate more with people. Just forgot about it :(.

Thursday, October 11, 2007

Some major tasks for close period finished

During last week I've spent much time visiting hospital and passing some physical examinations. It took rather a lot of time especially because of long distance between my home and hospital.

During last weekend I've made a lot of study work and for now has lesser major tasks to do. I've done functionality of my coursework on programming and now need to make program look good and make report for it.

Coursework is one of big projects that lasts more than a few days. What other big projects do I have? At first it is reading books. Now I'm reading "Design Patterns" about programming. My programming projects got some attention on last week but on this week they have lacked it. Hope I'll correct this in next days.

Eh... No any ideas more for now, I'm going to sleep... I've slept rather a small time during last days.

Sunday, October 07, 2007

Implementing custom tool in Visual Studio 2008

I've recently wrote about making tool to generate C# code. We may say that are macros for C# (it fact it is only one defined macro — for fields and properties).

And how to implement this tool? There can be two ways: write tool on scripting language that generates C# code file and is called before compilation. Another way is to use ability of Visual Studio to switch user custom tool for generating files. Firstly I've implemented tool by first way on Python and now I want to make a custom tool for Visual Studio written on C#. But how to plug custom tools in Visual Studio? Now I've got an answer, though I've spent much time to understand this.

Firstly, to develop plug-ins for Visual Studio it is needed to download Visual Studio SDK (for appropriate version of Visual Studio). I have to say that after installing it my Visual Studio 2008 Beta 2 became very unstable: IntelliSense regularly produces errors which crashes the whole Visual Studio.

After that Visual Studio will add templates of its addins. That's a base for future project (although may be addin can be created without all that stuff that is in template).

To make custom tool for generation of files the one must implement IVsSingleFileGenerator interface. I've spent a lot of time trying to make this and fails mainly because if this problem: in some places of documentation it is said that function generate gets a parameter of type out IntPtr[], in some it is said that it is out IntPtr and in fact interface has just IntPtr[]. Not any out! So how should I return value of pointer? Ok, I'm not a great specialist in .NET and arrays a sent be reference. Even if this is not a problem why there is an array not one pointer? Another outgoing parameter of function on exit must contain an amount of bytes in that array but how this will help if I'll allocate a different amount of bytes in different pointers in array. However I don't see a use for an array and just tried to allocate it and use only index 0. But this doesn't helped me and I failed in implementing that interface. May be that a bug in SDK and interface must have out IntPtr[]? Don't know I'm not a guru in Visual Studio.

I've failed to get a proper answer from MSDN documentation and my attempts so I've googled this problem.I've found some solutions but the most notable part is that in Visual Studio 2003 there was an abstract class which covered that horrible interface under much more comfortable interface. However "evil" Microsoft removed that class from version 2005. But good guys placed dll with it in Internet, i.e. here. So It's needed to implement function GetCode from that class and tool is ready to use!

However it is still needed to plug it in Visual Studio. First step is to register it as a package. This can be done by tool regpkg. It is placed in <%MVS SDK Dir%>\Tools\Bin\ directory. Just run it with a path to our compiled tool as a argument. This step can also be done manually,

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\<%MVSVersion%>\CLSID\{<%guid%>}]
@=<%Tool name%>
"InprocServer32"="C:\\WINDOWS\\system32\\mscoree.dll"
"ThreadingModel"="Both" "Class"=<%class name of tool%>
"Assembly"="<%asm name%>, Version=<%asm version%>, Culture=<%culture%>, PublicKeyToken=<%public key%>"


As you may noticed custom tool must be in GAC. May be there is a way to keep it somewhere else but I don't know.

What is next? Registered custom tool need to be registered as a generator. In registry dir of Visual Studio there is a directory Generators. There is some dirs in it: FA... is a C#, 16... is a VB.NET. It is needed to register tool for each language separately. In directory of proper language add directory with name of your tool, i.e. for my tool called CSGen:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\9.0\Generators\{fae04ec1-301f-11d3-bf4b-00c04f79efbc}\CSGen] @="CSGen tool to generate code on C#"
"CLSID"="{<%clsid registed in \CLSID\%>}"
"GeneratesDesignTimeSource"=dword:00000001


After that start Visual Studio choose file in project and in properties type name of custom tool. After each save file will be regenerated. It is also can be forced manually: right-click on file in Solution Explorer and "Run custom tool".

These articles with examples could be helpful (I'm not a good explainer, just learning):

Wednesday, October 03, 2007

Tool to generate code on C#

While reading in "Pragmatic programmer" chapter about automation I've formed an idea of creating a tool for C# which will reduce amount of manual typed code and as a result help to avoid errors.

Now I've got only one idea for this tool, but maybe in future I've got some more. So that's an idea? In many cases I've needed to create a public property and private field to keep value of property. In some cases I also need to create an event which will happen when value of property is changed. It is a lot of similar typing work. Of course it can be made easier by Visual Studio snippets and I've used them, but this still leaves much work during maintenance:
  • while renaming I need to rename field, property and if exists event. Of course refactoring capabilities of IDE free me from necessity to search of uses of this names, but I still have to rename 2-3 elements of class.
  • I have to have separate snippets to cases when I don't want to have an event, or want to make set private. Also when this details are changed during refactoring it is needed to make them by hand.
  • It takes a lot of locs. If it be possible to write all of necessary data in one line it will be much better to read and understand.
So I've written a tool on Python which eliminates these problems. It parsers file and search for special marker in commentaries. When it founds it, tool reads options and replaces this code with a valid C# code. Lets look at example:

public event EventHandler DoubleFieldChanged;
private double _doubleField;
public double DoubleField {
get { return _doubleField; }
set {
this._doubleField = value;
if ( this.DoubleFieldChanged != null )
this.DoubleFieldChanged(this, new EventArgs());
}
}

Is an original code on C#. Most of these tokens are just speaking what is already said by others. It can be replaced by just one line:

    // @Field double Double Field

Note that name is written not as identifier but as a casual name. My tool automatically forms valid identifiers for field, property and event. And if field is renamed all identifiers are changed by program not by programmer. Moreover 10 lines are replaced by 1! Of course not in all cases such tool can give so good results.

Moreover my tool already can read some parameters of created field. Want to have set be private? No problem:

    // @Field double Double Field( private set )

And tool will make the rest. The same way I can command it not to generate event (and of course not to call it!). Of course both options can be combined together.

My tool (arrrhhh... I call it csgen!) also provides basic customization to format of output identifiers. But now csgen couldn't make complex generations. In some cases it is needed to manually create all of this code on C#.

Though I nave some ideas of making csgen more useful. For example if set needs to check incoming value. Just add to description something like: // @Field: set requires Checker.IsValid(value) and throw an ArgumentException in case of invalid value. To implement this feature I csgen will need all text after requires and paste it into if condition. Moreover in such way can be implemented some other features.

But there will be a problem: compiler will point to errors in generated code and show its line numbers. So programmer have to read faulty code in generated file and then match it with content of original file and fix errors there. Not very good.

However to finish on good news I have to say that tried to implement this feature as a 'custom tool' in Visual Studio. I'll soon write post about it, but I can say that succeeded to write module that returns IDE text and it works with it!