jenswinter.com
Software Development 24/7

Frühe Exits

August 11, 2008 23:24 by Jens

Genau wie Stefan bin ich ein Freund früher Exits. Sein Vorschlag sieht so aus:

public void DoSomething() {
    if (!a) {
        return;
}
    if (!b) {
        return;
}
    if (!c) {
        return;
}
    DoItRealy();
}

Ich hätte da aber noch einen kleinen Zusatz.

Die frühen Exits sollten so kurz wie möglich gehalten werden.
Bei frühen returns und throws handelt es sich um Guard Clauses, die nichts direkt mit dem Eigentlichen "Fleisch" der Methode zu tun haben und somit beim Lesen des Codes einen leichten Noise-Charakter haben. Das gefühlte Gewicht sollte m.M.n. so weit es geht auf dem wichtigen Teil der Methode liegen. Wenn ich z.B. wissen will, was darin passiert, will ich die Guards so schnell es geht überspringen können und nur bei Bedarf dort nachschauen.
Die Guards abzukürzen bedeutet, dass ich dabei sämtliche unnötigen Klammern weglasse. Das spart nämlich die eine oder andere Noise-Zeile ein.

public void DoSomething() {
    if (!a)
        return;
    if (!b)
        return;
    if (!c)
        return;
DoItRealy();
}

Oftmals habe ich auch die noch stärker abgekürzte Variante gesehen, in der das "return" in derselben Zeile wie das jeweils dazugehörende "if" steht:

public void DoSomething() {
    if (!a) return;
    if (!b) return;
    if (!c) return;
DoItRealy();
}

Das sieht auch sehr kompakt aus und ist ziemlich gut lesbar. Aber wie so Vieles ist das Geschmacksache.


Tags:
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

.NET Domain Driven Design with C#

May 18, 2008 21:09 by Jens

This weekend I received a copy of Tim McCarthy's ".NET Domain Driven Design with C#". I was waiting eagerly for this book. Special thanks go to my boss for sponsoring it. Smile

As I haven|t read the book yet, I cannot give a review. So I will leave the text of the back cover here:

"As the first technical book of its kind, this unique resource walks you through the process of building a real-world application using Domain-Driven Design implemented in C#. Based on a real application for an existing company, the project featured throughout the book focuses on the Domain Model and the framework that is being built to support it. Each chapter is broken down into specific modules so that you can identify the problem, decide what solution will provide the best results, and then execute that design to solve the problem. With each chapter, you'll build a complete project from beginning to end, offering you indispensable, hands-on practice at creating code that builds applications. What you will learn from this book  

  • When, why, and how to use Domain-Driven Design
  • How to design and build the initial Domain Model
  • What to do to achieve "Persistence Ignorance"
  • Ways to build a Repository framework for the Domain Model
  • Techniques for applying TDD to the Domain Model
  • How to apply the Model-View-ViewModel Pattern
  • How to build a client-side membership system
  • What to do to synchronize the client application with the server
This book is for experienced C# .NET developers who want to improve their techniques for writing applications that perform well and are highly scalable."


Since we are currently starting a brand new WPF project that will cover all of the things that come in the book, it arrived just in time. Cool And I hope it will be a good help for us.


Formatting Object Initializers

September 25, 2007 22:15 by Jens

I'm currently playing around with the Orcas Beta 2 and C# 3.0. As I'm experimenting with the new object initialization feature in C#, I'm wondering which coding style will be applicable and will prevail.

So here is the style from the C# 3.0 specification:

Project project = new Project { VersioningType = "SqlServerVersionsTable", DatabaseType = "SqlServer" };

But I'm not sure if this will be the best choice most of the time. So here some other styles to vote for:

Project project = new Project
{
    VersioningType = "SqlServerVersionsTable", DatabaseType = "SqlServer"
};

or

Project project = new Project
{
    VersioningType = "SqlServerVersionsTable",
    DatabaseType = "SqlServer"
};

or (my favorite for now)

Project project = new Project
    {
        VersioningType = "SqlServerVersionsTable",
        DatabaseType = "SqlServer"
    };

The time will tell which version really will be used by the majority of the developers.


Tags:
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed

How to: Passwort im PropertyGrid

November 25, 2005 21:16 by Jens
Wie kann das PropertyGrid verwendet werden um den Nutzer Passwörter eingeben zu lassen?
  • Die Passwort-Eigenschaft darf nicht im Klartext im Grid zu sehen sein. Stattdessen soll für jedes Zeichen ein Asterisk angezeigt werden.
  • Die korrekte Eingabe des Passwortes sollte über eine zweite Abfrage abgesichert werden.
Als Beispiel benutze ich die Klasse LoginInfo:

 

    public class LoginInfo

    {

        private string m_UserName;

        private string m_Password;

 

        [Category("Credentials")]

        public string UserName

        {

            get { return m_UserName; }

            set { m_UserName = value; }

        }

 

        [Category("Credentials")]

        public string Password

        {

            get { return m_Password; }

            set { m_Password = value; }

        }

    }

 

Eine Instanz soll vom Nutzer im PropertyGrid editiert werden können:

Man benötigt eine Klassenbibliothek, die das Formular für die Passworteingabe, eine von UITypeEditor abgeleitete Klasse und eine von StringConverter abgeleitete Klasse. Das Formular ist schnell zusammengeklickt. Nicht vergessen, die Eigenschaft PasswordChar der Textboxen auf "*" zu setzen. Das Formular erweitere ich noch um die Eigenschaft Passwor:

 

        public string Password

        {

            get { return PasswordTextBox.Text; }

        }

 

Und im Closing-Ereignis wird noch geprüft, ob die Inhalte der TextBoxen beim Klick auf den Ok-Schalter identisch sind:

 

        private void PasswordEditForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)

        {

            if (PasswordTextBox.Text != ConfirmPasswordTextBox.Text)

            {

                MessageBox.Show("Password values entered do not match.", "MyApp", MessageBoxButtons.OK, MessageBoxIcon.Error);

                e.Cancel = true;

            }

        }

 

Der Eingabedialog soll erscheinen, wenn die Eigenschaft Password im PropertyGrid zum Bearbeiten ausgewählt wird. Dafür muss eine Klasse vom Typ UITypeEditor abegeleitet werden:

 

    public class PasswordEditor : UITypeEditor

    {

        public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)

        {

            return UITypeEditorEditStyle.Modal;

        }

 

        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)

        {

            PasswordEditForm form = new PasswordEditForm();

            if (form.ShowDialog() == DialogResult.OK)

            {

                return form.Password;

            }

            else

            {

                return value;

            }

        }

    }

 

Die überschriebene Methode GetEditStyle liefert UITypeEditorEditStyle.Modal zurück, damit der kleine Schalter mit den drei Punkten im Grid erscheint. Das Überschreiben der Methode EditValue sorgt dafür, dass das Eingabeformular aufgerufen wird und dass der eingegebene Wert zurückgeliefert wird.

Zuletzt muss noch dafür gesorgt werden, dass im PropertyGrid immer nur Sternchen, und nicht der tatsächliche Inhalt der Passwort-Eigenschaft sichtbar sind. Dafür muss von der Klasse StringConverter abgeleitet werden:

 

    public class PasswordStringConverter : StringConverter

    {

        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)

        {

            return false;

        }

 

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)

        {

            return String.Empty.PadLeft(((string)value).Length, '*');

        }

    }

 

CanConvertFrom liefert false zurück. Damit wird verhindert, dass der Nutzer bei der Eigenschaft Password einen Wert direkt eingeben kann. Er wird somit gezwungen, auf den Schalter zu drücken um die Eigenschaft zu setzen. ConvertTo sorgt dafür, dass nur noch Sternchen für das Grid zurückgeliefert werden.

Damit das Ganze auch wirkt, muss die LoginInfo-Klasse noch angepasst werden. Die Eigenschaft Password erhält nur noch die entsprechenden Attribute:

 

    public class LoginInfo

    {

        private string m_UserName;

        private string m_Password;

 

        [Category("Credentials")]

        public string UserName

        {

            get { return m_UserName; }

            set { m_UserName = value; }

        }

 

        [Category("Credentials")]

        [TypeConverter(typeof(PasswordStringConverter))]

        [Editor(typeof(PasswordEditor), typeof(UITypeEditor))]

        public string Password

        {

            get { return m_Password; }

            set { m_Password = value; }

        }

    }

 


About VB.NET vs. C#

May 16, 2005 21:08 by Jens

A few weeks ago I got involved in a small project - a funny, little online game. For me what's so special about this project is that it shall be written in VB.NET. As a C# developer I didn't write a single line of VB before. So this is a special challenge for me. Ok, it is not that I didn't know anything about it. At least I read VB code from time to time in books and articles. And I have a BASIC background from my first years programming on my Commodore 64.

So I decided to just jump into the water. By all means learning another programming language can't be a bad idea.

So after the initial requirement gatherings for the project I started coding. And what then came was a very big surprise. I didn't have any problems. It only took some examples from the MSDN Library to get the hang of the VB syntax. I had to find out about event handling and the module thing. Visual Studio dealt with the rest. I am truely amazed about the help VS is giving with VB development. The automatic completion of statements allows for really fast coding. This was a whole new experience for me.

Coding VB.NET really is a pleasure for me. But to be honest the main reason for this is Visual Studio.NET and not the language itself. Getting a grip on VB hasn't been as challenging as I expected. In fact for me there is no real difference to developing in C#. Of course the syntax is different but it is still all about classes, fields and properties. So I was wandering what's all the fuss about VB.NET vs. C#. Where are the real differences where are the advantages over C#. There have to be reasons for VB developers to use VB.NET instead C#.

So I asked this Question in a VB newsgroup: "What are the advantages of VB.NET over C#?" I was hoping for some enlightening answers, but the answers haven't been very satisfactory. Of course there were the usual debates about the syntax of C# - curly brackets, semicolons and case sensitivity. But this is not what I was interested in. I expected this sort of discussion. I wanted to know about things you can do with VB.NET you can't do with C#. So when I filter out all the syntax stuff, the resulting list is this:

  • Late Binding as integrated language instrument
  • Parameterized properties
  • "With" statement
  • Optional parameters

Personally I don't like the with statement. And I can do well without optional parameters.
The list surely is far from being complete. But that's what I got. So biggest advantage is the comfort Visual Studio provides with developing VB.

Concerning the debate about VB syntax vs. C# syntax I sensed an aggressive tone on the VB camp. They stated that VB is much more readable. This may be right - for them. But this doesn't necessarily applies for everyone else. I tried to convince them that VB isn't really more readably for me. Note, that I didn't try to convince them that C# is more readable than VB. I said that I prefer curly brackets and case sensitivity.
So dear VB developer, do me a favor and don't tell me what I can read better. I will decide this for myself. Wink

To summarize: There is absolutely no need for language wars. Just try out the different languages and decide for yourself which one suits you best.

Here is a very good article on codeproject that compares VB.NET and C# (via Carl Franklin).

Oh btw, please feel free to expand my list of VB advantages over C#. I'm very interested and I'm pretty sure there are some more points.