Posts Tagged ‘c#’

Enumeration class for string parameter

September 4, 2009

When I write the Google API for .NET, there are a lot of string parameters, like imageColor and safeLevel etc.

So I create an enum for every kind of parameter.

public enum SafeLevel
{
    off,
    moderate = 0,
    active,
}

I even set the moderate of SafeLevel as default value. And I can use the ToString method to get the string value most of the time.

Not every string parameter are so readable. They use “r” for relevance and “d” for date for instance.

At this time, I use extension method + switch.

public string GetString(this SortType value)
{
    switch (value)
    {
        case SortType.relevance:
            return "r";
        case SortType.date:
            return "d";
        default:
            return null;
    }
}

Or I use some helper class like LanguageUtility.

Everything is OK until Google add more choices of parameters.

Someone complained Google now can translate XXX language. Then I have to release a new version to follow the pace of Google!

The bad day has gone. Now I use string parameter directly. One can translate any language Google supported without complain and waiting.

But without enum and the helper class, API user need to check every parameter code from Google (like me).

For keeping life easy for all of you, I create the simple Enumeration class

public enum SafeLevel
    /// <summary>
    /// The enumeration. For parameters of Google APIs.
    /// </summary>
    public abstract class Enumeration
    {
        private readonly string name;

        private readonly string value;

        private readonly bool isDefault;

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration"/> class.
        /// </summary>
        /// <param name="value">The value.</param>
        protected Enumeration(string value)
            : this(value, value)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        protected Enumeration(string name, string value)
            : this(name, value, false)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <param name="isDefault">if set to <c>true</c> it is default value.</param>
        protected Enumeration(string name, string value, bool isDefault)
        {
            this.name = name;
            this.isDefault = isDefault;
            this.value = value;
        }

        /// <summary>
        /// Gets a value indicating whether this instance is default.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is default; otherwise, <c>false</c>.
        /// </value>
        public bool IsDefault
        {
            get
            {
                return this.isDefault;
            }
        }

        /// <summary>
        /// Gets the value.
        /// </summary>
        /// <value>The value.</value>
        public string Value
        {
            get
            {
                return this.value;
            }
        }

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        public string Name
        {
            get
            {
                return this.name;
            }
        }

        /// <summary>
        /// Performs an implicit conversion from <see cref="Google.API.Enumeration"/> to <see cref="System.String"/>.
        /// </summary>
        /// <param name="enumeration">The enumeration.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator string(Enumeration enumeration)
        {
            if (enumeration.IsDefault)
            {
                return null;
            }

            return enumeration.Value;
        }

        /// <summary>
        /// Returns a <see cref="System.String"/> that represents this instance.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return this.Name;
        }

        /// <summary>
        /// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
        /// </summary>
        /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
        /// <returns>
        ///     <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj)
        {
            if (ReferenceEquals(this, obj))
            {
                return true;
            }

            if (obj == null)
            {
                return false;
            }

            if (!this.GetType().IsInstanceOfType(obj))
            {
                return false;
            }

            return this.Value == ((Enumeration)obj).Value;
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
        /// </returns>
        public override int GetHashCode()
        {
            Debug.Assert(this.Value != null, "Value cannot be null.");

            return this.Value.GetHashCode();
        }
    }
}

It has three readonly properties: Name, Value and IsDefault.

It can also convert to string implicitly. Then you can use it as string. Or you can make it looks like the type of parameter is Enumeration but not string.

TranslateClient client = new TranslateClient();
string translated = client.Translate(text, Language.ChineseSimplified, Language.English);

It looks the same of the old enum parameter version. But the Language is not a enum but a subclass of Enumeration and the English is a public static readonly field.

public static readonly Language English = new Language("English", "en");

Here I want add two more static method and a implicit convert method.

public static Language GetDefault();

public static ICollection<Language> GetEnums();

public static implicit operator Language(string value)

It’s not hard using reflection. But I need repeat them in every subclasses of Enumeration.

Although code template tool can help me a lot, but I do not think it’s a good I idea. Don’t repeat yourself!

So I create a generic Enumeration class:

public abstract class Enumeration<T> : Enumeration, IEquatable<T> where T : Enumeration<T>

This class has a very interesting constrain. We can only create a subclass like this:

public sealed class SortType : Enumeration<SortType>

The subclass must pass itself as the generic parameter. (Tell me if I’m wrong.) In other words, the T in Enumeration is must be the type of subclass.

Here I marked SortType as sealed, because the Enumeration can only know it subclass but not sub-subclass.

Here is the whole code of Enumeration:

    /// <summary>
    /// The enumeration. Provide more static methods and properties for every concrete enumeration.
    /// </summary>
    /// <typeparam name="T">The type of concrete enumeration.</typeparam>
    public abstract class Enumeration<T> : Enumeration, IEquatable<T>
        where T : Enumeration<T>
    {
        private static T @default;

        private static IDictionary<string, T> dictionary;

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="value">The value.</param>
        protected Enumeration(string value)
            : base(value)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        protected Enumeration(string name, string value)
            : base(name, value)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Enumeration&lt;T&gt;"/> class.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <param name="isDefault">if set to <c>true</c> it is default value.</param>
        protected Enumeration(string name, string value, bool isDefault)
            : base(name, value, isDefault)
        {
        }

        /// <summary>
        /// Gets the dictionary of value and enumeration.
        /// </summary>
        /// <value>The dictionary.</value>
        protected static IDictionary<string, T> Dictionary
        {
            get
            {
                Initialize();
                return dictionary;
            }
        }

        /// <summary>
        /// Gets the default enumeration.
        /// </summary>
        /// <returns>The default enumeration</returns>
        public static T GetDefault()
        {
            Initialize();
            return @default;
        }

        /// <summary>
        /// Gets all enumerations.
        /// </summary>
        /// <returns>All enumerations</returns>
        public static ICollection<T> GetEnums()
        {
            return Dictionary.Values;
        }

        /// <summary>
        /// Indicates whether the current object is equal to another object of the same type.
        /// </summary>
        /// <param name="other">An object to compare with this object.</param>
        /// <returns>
        /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        public bool Equals(T other)
        {
            if (other == null)
            {
                return false;
            }

            return this.Value == other.Value;
        }

        /// <summary>
        /// Initializes this instance.
        /// </summary>
        protected static void Initialize()
        {
            if (dictionary == null)
            {
                dictionary = new Dictionary<string, T>();

                var type = typeof(T);

                ////var enums =
                ////    from propertyInfo in
                ////        type.GetProperties(
                ////        BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.GetProperty)
                ////    where
                ////        propertyInfo.PropertyType.IsAssignableFrom(typeof(T)) &&
                ////        propertyInfo.GetIndexParameters().Length == 0
                ////    select propertyInfo.GetValue(null, null) as T;

                var enums =
                    from fieldInfo in
                        type.GetFields(
                        BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.GetField)
                    where fieldInfo.FieldType.IsAssignableFrom(type)
                    select fieldInfo.GetValue(null) as T;

                foreach (var @enum in enums)
                {
                    Debug.Assert(@enum != null, "enum cannot be null.");

                    dictionary[@enum.Value] = @enum;

                    if (@default == null && @enum.IsDefault)
                    {
                        @default = @enum;
                    }
                }
            }
        }

        /// <summary>
        /// Converts the specified value to this enumeration.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="construct">The constructor function.</param>
        /// <returns>The enumeration.</returns>
        protected static T Convert(string value, Func<string, T> construct)
        {
            if (value == null)
            {
                return GetDefault();
            }

            T @enum;

            if (!Dictionary.TryGetValue(value, out @enum))
            {
                @enum = construct(value);
            }

            return @enum;
        }
    }

Here I use the lazy load trick but not initialize in the static constructor, because the static constructor will run before than the static fields in subclass have been assigned.

And the implement convert operation can only defined in the subclass. So I put most of the logic into the Convert method.

Here is what a subclass looks like:

    /// <summary>
    /// The search safety level.
    /// </summary>
    public sealed class SafeLevel : Enumeration<SafeLevel>
    {
        /// <summary>
        /// Disables safe search filtering.
        /// </summary>
        public static readonly SafeLevel Off = new SafeLevel("Off", "off");

        /// <summary>
        /// Enables moderate safe search filtering. Default value.
        /// </summary>
        public static readonly SafeLevel Moderate = new SafeLevel("Moderate", "moderate", true);

        /// <summary>
        /// Enables the highest level of safe search filtering.
        /// </summary>
        public static readonly SafeLevel Active = new SafeLevel("Active", "active");

        private SafeLevel(string value)
            : base(value)
        {
        }

        private SafeLevel(string name, string value)
            : base(name, value)
        {
        }

        private SafeLevel(string name, string value, bool isDefault)
            : base(name, value, isDefault)
        {
        }

        /// <summary>
        /// Performs an implicit conversion from <see cref="System.String"/> to <see cref="SafeLevel"/>.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>The result of the conversion.</returns>
        public static implicit operator SafeLevel(string value)
        {
            return Convert(value, s => new SafeLevel(s));
        }
    }

Although the solution has some smell, like visit static method in superclass and static protected method.

I hope it can solve my problem well.

Thanks for reading.

Advertisements

Xml Serializable Session (Dictionary)

January 8, 2009

In my recent (c#) project, I need save something in a session (or dictionary) and I need save the session into a standard xml document.

XmlSession session = new XmlSession();

session["string"] = "I'm a string";

session["number"] = 42;

// Any object. Make sure it can be serialize to a standard xml document.
session["object"] = new MyObject("obj", 100, DateTime.Now);

using (Stream stream = File.Create("session.xml"))
{
session.Serialize(stream);
}

using (Stream stream = File.OpenRead("session.xml"))
{
session = XmlSession.Deserialize(stream);
}

// "I'm a string"
string s = (string)session["string"];

// 42
int num = (int)session["number"];

MyObject o = (MyObject)session["object"];

If you have encountered the same requirement, you would know that is not a easy work.

You can use the XmlSerializer to do this object-xml mapping, but you need to know all the types of value in your session, especially when you deserialize the xml document.

OK, OK. I did all these for you.

Just download and session it.

XmlSession.cs

Entry.cs

FileSystemRightsHelper

January 8, 2009

The FileSystemRightsHelper class is a utility class to get the IO permission of a directory or a file.

DirectorySecurity security = System.IO.Directory.GetAccessControl(path);

AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));

FileSystemRightsHelper rights = new FileSystemRightsHelper(rules);

if (rights.CanWrite && rights.CanRead)
{
    Console.WriteLine("R/W access");
}
else
{
    if (rights.CanWrite)
	{
        Console.WriteLine("Only Write access");
    }  
	else if (rights.CanRead) 
	{
        Console.WriteLine("Only Read access");
    }
	else
	{
        Console.WriteLine("No Read and Write accesses");
    }
}

When I want to know “Do I have permission to Read or Write this file?”, I found this article by Bruce Hatt, “Testing File Access Rights in .NET 2.0“.

Thanks Bruce Hatt, I can get the answer of this common question.

Everything is OK, exception the code itself. I DO NOT LIKE THE CODE AT ALL!

So I rewrited my FileSystemRightsHelper (not just simple refactor).

Now it’s more effective and elegent.

Check it out!

FileSystemRightsHelper.cs

Effective Java, even c# (3) Classes and Interfaces

July 25, 2008

So GREAT The new version of Effective Java(2nd edition)  is! (Better than Effective c# 1 million times)

I’m reading this book and finding that lots of the skill can be used by other language programmers, especially c#’s.

This series of notes will cover the the things for both java and c#.

Wish you like it.

Classes and Interfaces

  • Item 13: Minimize the accessibility of classes and members

All you can use the term : encapsulation.

The basic principles of object-oriented programming are encapsulation, modularity, polymorphism, and inheritance.

Let me compare the modifiers of Java and c# first.

Java                                    c#

private                                private(default)

package-private(default)    internal

protected                            protected

public                                  public

(No this modifier)                protected internal

Both of they have the package-private (internal in c#) modifier, this is new to c++ programmer (so is “finally” for exception process). It’s very useful when you wanna write test case for it.

No one wanna test a private method, even we can do so by some reflection-tool. So you can make it package-private (or internal).

To facilitate testing, you may be tempted to make a class, interface, or member more accessible. This is fine up to a point. It is acceptable to make a private member of a public class package-private in order to test it, but it is not acceptable to raise the accessibility any higher than that. In other words, it is not acceptable to make a class, interface, or member a part of a package’s exported API to facilitate testing. Luckily, it isn’t necessary either, as tests can be made to run as part of the package being tested, thus gaining access to its package-private elements.” – Effective Java 2ed

It means you should put your test code at the same package.

But for c# programmer, there’s a better choice: authorize your test assembly to visit the internal elements. It’s easy, just use the InternalsVisibleToAttribute.

I’ve used this trick in the Google APIs for .NET project.

You should always consider the interface-oriented design. Let the user get an instance of the interface (with Dependency Inject or Abstract Factory) but not know its true type. It will make your design more clear.

  • Item 14: In public classes, use accessor methods, not public fields

Indeed, I think you should always this rule even for non-public classes.

c# programmer can use properties, it looks more natural.

You don’t need to worry about the performance, the smart modern compiler will do all the things for you.

  • Item 15: Minimize mutability

It seems the same, item 7 in Effective c#: Item 7: Prefer Immutable Atomic Value Types.

Most of time, you can make your information class immutable.

It’s thread security and you can cache it.

The disadvantage is the performance problem. You need to create a new instance every time.

You can use some helper class, like the StringBuilder for String.

You can also create a mutable subclass in your package for some operate. Like the transition for a matrix.

Don’t forget to check if it the “real” immutable object.

public static BigInteger safeInstance(BigInteger val) {
    if (val.getClass() != BigInteger.class)
        return new BigInteger(val.toByteArray());
    return val;
}

If a class cannot be made immutable, limit its mutability as much as possible” – Effective Java 2ed

  • Item 16: Favor composition over inheritance

Unlike method invocation, inheritance violates encapsulation” – Effective Java 2ed

So if we don’t use inheritance, what should we do? The composition.

It’s just some wrapper classes, something like the smart pointer if you familiar with c++.

// Wrapper class - uses composition in place of inheritance
public class InstrumentedSet<E> extends ForwardingSet<E> {
	private int addCount = 0;

	public InstrumentedSet(Set<E> s) {
		super(s);
	}

	@Override
	public boolean add(E e) {
		addCount++;
		return super.add(e);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		addCount += c.size();
		return super.addAll(c);
	}

	public int getAddCount() {
		return addCount;
	}
}

One principle in Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin is that, one class inherit from its super only if it can replace it super completely. It not just means the “is-a” relationship, it means sub can do everything its super can. It means their functions. The square and rectangle is a good example, square is a rectangle in math, but you’d better let them inherit from one base class (You can read the book for more detail about this example and other things).

Writing a wrapper class is tedious in Java and c# (but easy in some dynamic language like ruby etc.), but it very useful.

One thing I like most is that it can implement multiple inheritance in Java and c# by the Decorator pattern.

Don’t be afraid of the inheritance after read this article. Some times, inheritance can make your life easier.

One case in the ASP.NET 2.0 Website Programming: Problem – Design – Solution said that, all the page classes are inherited from an abstract utility class. You can make the utility class be a static utility class. But the author of this book think this is the best way in practice. You can also find this kind of base class in the ASP.NET framework.

  • Item 17: Design and document for inheritance or else prohibit it

Someone said that, when Java lost a function there will be a corresponding annotation to fix it. This time, the lost keyword is “virtual” and its corresponding annotation after Java 1.5 is @override.

But @override cannot replace virtual,  no one can stop someone override any exposed method because every non-static method is “virtual“. So the only thing we can do is writing the document!

Even when you can mark your method virtual to let other one override it in c#, there still one problem, which methods should be virtual?

Unfortunately, there is no magic bullet. The best you can do is to think hard, take your best guess, and then test it by writing subclasses.” – Effective Java 2ed

The only way to test a class designed for inheritance is to write subclasses.” – Effective Java 2ed

Why don’t the designer of Java make the “virtual” as a key word in Java? I think they don’t wanna you mark your method as “new” as a c# programmer can do, so do c++.

The “new” method will make some mistake, you should always escape it.

“Constructors must not invoke overridable (virtual) methods” – Effective Java 2ed

You need pay more attention when the class implemented Cloneable (ICloneable) or Serializable.

If you think no one need inherit this class, mark it as “final” (sealed).

  • Item 18: Prefer interfaces to abstract classes

Both Java and c# are single inheritance (at most one direct super class), one class can implement a lot of interface. You can use this mechanism (and the Decorator pattern) to implement the multiple inheritance.

Let me say something about the diff of interface in Java and c#.

In c#, you can implement one method explicit or implicit, but in Java, all the implements are implicit.

To know how different it is, read these two articles : Dealing with Conflicting Interfaces: Part-I – Java and Dealing with Conflicting Interfaces: Part-II – .NET.

There’s no “interface” in c++. In c++ world, they use abstract classes. The interface mechanism separate the definition and implement of the abstract class.

So when you wanna define some function, prefer using interface.

Interface-based programming has a lot of benefit, it easy to TDD (Test Driven Development), DI (Dependency Injection), SOA (Service Oriented Architecture) etc.

Some one said that, there should be one interface for every three or five classes. (from Framework Design Guidelines? or IDesign c# coding standard?) The ratio of interfaces and classes in the .NET Framework obey to this rule.

You can use both interface and abstract class, but the role of interface and abstract class are different. It’s very common in practice.

There are some good examples in the Chinese book “Practical object-oriented development : c# edition” (面向对象实践之路c#版) by Li Wei (李维), the CTO of Borland, China.

This book also said that, you should use abstract class directly if no other class need to share the functions in this class. For example, the Matrix abstract class in some linear algebra library, then you can define DenceMatrix and SparseMatrix inherit from it. The MarshalByRefObject class in .NET Framework is another example.

  • Item 19: Use interfaces only to define types
// Constant interface antipattern - do not use!
public interface PhysicalConstants {
	// Avogadro's number (1/mol)
	static final double AVOGADROS_NUMBER = 6.02214199e23;
	// Boltzmann constant (J/K)
	static final double BOLTZMANN_CONSTANT = 1.3806503e-23;
	// Mass of the electron (kg)
	static final double ELECTRON_MASS = 9.10938188e-31;
}

This is something you can do in Java. Don’t do that, put the const field into a enum or utility class.

The only choice for c# programmer is put them in a static class, like Math class.

  • Item 20: Prefer class hierarchies to tagged classes
// Tagged class - vastly inferior to a class hierarchy!
class Figure {
	enum Shape {
		RECTANGLE, CIRCLE
	};

	// Tag field - the shape of this figure
	final Shape shape;
	// These fields are used only if shape is RECTANGLE
	double length;
	double width;
	// This field is used only if shape is CIRCLE
	double radius;

	// Constructor for circle
	Figure(double radius) {
		shape = Shape.CIRCLE;
		this.radius = radius;
	}

	// Constructor for rectangle
	Figure(double length, double width) {
		shape = Shape.RECTANGLE;
		this.length = length;
		this.width = width;
	}

	double area() {
		switch (shape) {
		case RECTANGLE:
			return length * width;
		case CIRCLE:
			return Math.PI * (radius * radius);
		default:
			throw new AssertionError();
		}
	}
}
// Class hierarchy replacement for a tagged class
abstract class Figure {
	abstract double area();
}

class Circle extends Figure {
	final double radius;

	Circle(double radius) {
		this.radius = radius;
	}

	double area() {
		return Math.PI * (radius * radius);
	}
}

class Rectangle extends Figure {
	final double length;
	final double width;

	Rectangle(double length, double width) {
		this.length = length;
		this.width = width;
	}

	double area() {
		return length * width;
	}
}

The code shows all the story about this theme.

OK, let say something more complex : the State Pattern (see The State Pattern: An Underappreciated Pattern)

We should always find way to replace the “if/else if/else” and “switch/case”.

I know some one use “template specializations” in c++ to do this. Woo~! Let’s go back to Java and c#.

State pattern is a good way to do this, although it is a little bit complex to implement.

The book, Agile Software Development, Principles, Patterns, and Practices, by Robert C. Martin shows you what is State Pattern.

Uncle Bob even made a tool for you to draw the state graph and automatic create the Java code for you.

  • Item 21: Use function objects to represent strategies

Remember the duck story in the famous book Head First Design Patterns? Yes, it is Strategy Pattern.

You can use delegate or lambda expression to implement the Strategy Pattern in c#.

You can also use a function class to do this for you.

When you wanna put more than one methods as one strategy, the function class is the only way to do that.

// anonymous class in Java
Arrays.sort(stringArray, new Comparator<String>() {
	public int compare(String s1, String s2) {
		return s1.length() - s2.length();
	}
});
// lambda expression in c#
Arrays.sort<string>(stringArray, (s1, s2) => s1.Length - s2.Length);
  • Item 22: Favor static member classes over nonstatic

Well, Let me show you the Null Object Pattern.

Most of time, when you wanna use a reference class, you should check whether it is null.

abstract class Figure
{
    public abstract void Draw();
}

void DrawAll(Figure[] figures)
{
    foreach (Figure figure in figures)
    {
        if(figure != null)
            figure.Draw();
    }
}

Here, I create a NullFigure inner class. When you need to return null, return Figure.NULL instead.

abstract class Figure
{
    private class NullFigure : Figure
    {
        public override void Draw()
        {
            // Do nothing.
        }
    }

    public static Figure NULL = new NullFigure();

    public abstract void Draw();
}

void DrawAll(Figure[] figures)
{
    foreach (Figure figure in figures)
        figure.Draw();
}

The implement in Java with anonymous class looks more element.

abstract class Figure {
	public static Figure NULL = new Figure() {
		@Override
		public void Draw() {
			// Do nothing.
		}
	};

	public abstract void Draw();
}
  • iron9light‘s Item: Design is always the center of software development.

So many things changed, the way to access the database, the way to build a GUI or create web pages. The way to communicate thought internet and different operation system.

There are something look the same even twenty years before now. That is design, like the object-oriented.

Design has changed everyday. But the Design as the core of software is not changed.

There are some good books :

Design Guidelines for Developing Class Libraries by microsoft

Agile Software Development, Principles, Patterns, and Practices by Robert C. Martin

You should read them a lot of times. It is worth to.

Only reading book cannot make you a master of design.

So the last thing is PRACTICE!

Effective Java, even c# (2) Methods Common to All Objects

July 24, 2008

So GREAT The new version of Effective Java(2nd edition)  is! (Better than Effective c# 1 million times)

I’m reading this book and finding that lots of the skill can be used by other language programmers, especially c#’s.

This series of notes will cover the the things for both java and c#.

Wish you like it.

Methods Common to All Objects

  • Item 8: Obey the general contract when overriding equals

It’s not a new problem.

I don’t wanna repeat the detail of how to write your new equals method.

I just wanna notice the c# programmer: when you override the equals (and the == and != operators), you should implement the IEquatable interface as well.

  • Item 9: Always override hashCode when you override equals

Nothing to say.

  • Item 10: Always override toString

Do this. You will feel good when you debug your code.

  • Item 11: Override clone judiciously

Nothing to say.

  • Item 12: Consider implementing Comparable

Nothing to say.

The methods in the Object class look so identical in Java and c#. This is why someone said that the c# is a copy of Java.

All the problem above are discussed in CLR via c# very clearly. If you are a c# programmer. Read it. It will tell you something for c# only like Equals for struct etc.

Effective Java, even c# (1) Creating and Destroying Objects

July 24, 2008

So GREAT The new version of Effective Java(2nd edition)  is! (Better than Effective c# 1 million times)

I’m reading this book and finding that lots of the skill can be used by other language programmers, especially c#’s.

This series of notes will cover the the things for both java and c#.

Wish you like it.

Creating and Destroying Objects

  • Item 1: Consider static factory methods instead of constructors

Just a static method to create the instance. It can replace the constructor. You can then make the constructor invisible(private or protected) or not.

class A{
    // constructors and others things.
    public static A newInstance(){
        return new A();
    }
}

This skill can be used by both Java and c#.

The advantages you can control more than the constructor. You can create a new instance or an old one(like the Singleton pattern). Or you can return other implement for the return type. This will make it more like the abstract factory pattern.

One more advantage I think, is that you can check the parameters. I remembered that it is not good to throw exception at the constructor in the CLR via c# by Jeffrey Richter. With this static method, you can throw anything freely.

  • Item 2: Consider a builder when faced with many constructor
    parameters

The builder is for the constructor with a lot of parameters. We used to provide some overload constructors for some default parameters. It’s named “telescope” by Bloch (the writer of this book).

Here is the example:

// Telescoping constructor pattern - does not scale well!
public class NutritionFacts {
	private final int servingSize; // (mL) required
	private final int servings; // (per container) required
	private final int calories; // optional
	private final int fat; // (g) optional
	private final int sodium; // (mg) optional
	private final int carbohydrate; // (g) optional

	public NutritionFacts(int servingSize, int servings) {
		this(servingSize, servings, 0);
	}

	public NutritionFacts(int servingSize, int servings, int calories) {
		this(servingSize, servings, calories, 0);
	}

	public NutritionFacts(int servingSize, int servings, int calories, int fat) {
		this(servingSize, servings, calories, fat, 0);
	}

	public NutritionFacts(int servingSize, int servings, int calories, int fat,
			int sodium) {
		this(servingSize, servings, calories, fat, sodium, 0);
	}

	public NutritionFacts(int servingSize, int servings, int calories, int fat,
			int sodium, int carbohydrate) {
		this.servingSize = servingSize;
		this.servings = servings;
		this.calories = calories;
		this.fat = fat;
		this.sodium = sodium;
		this.carbohydrate = carbohydrate;
	}
}

The builder can do the same things, and it looks more cool!

NutritionFacts cocaCola = new NutritionFacts(240, 8, 100, 0, 35, 27);

NutritionFacts cocaCola2 = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).carbohydrate(27).build();

The implement is so easy, and it makes the code more readable. (like the named parameters in python)

// Builder Pattern
public class NutritionFacts {
	private final int servingSize;
	private final int servings;
	private final int calories;
	private final int fat;
	private final int sodium;
	private final int carbohydrate;

	public static class Builder {
		// Required parameters
		private final int servingSize;
		private final int servings;
		// Optional parameters - initialized to default values
		private int calories = 0;
		private int fat = 0;
		private int carbohydrate = 0;
		private int sodium = 0;

		public Builder(int servingSize, int servings) {
			this.servingSize = servingSize;
			this.servings = servings;
		}

		public Builder calories(int val) {
			calories = val;
			return this;
		}

		public Builder fat(int val) {
			fat = val;
			return this;
		}

		public Builder carbohydrate(int val) {
			carbohydrate = val;
			return this;
		}

		public Builder sodium(int val) {
			sodium = val;
			return this;
		}

		public NutritionFacts build() {
			return new NutritionFacts(this);
		}
	}

	private NutritionFacts(Builder builder) {
		servingSize = builder.servingSize;
		servings = builder.servings;
		calories = builder.calories;
		fat = builder.fat;
		sodium = builder.sodium;
		carbohydrate = builder.carbohydrate;
	}
}

One more advantage for Java is you can make a Generic Builder and make sure you can use the parameterless method (like defualt constructor) to get the instance but not invoke the Class.newInstance.

// A builder for objects of type T
public interface Builder<T> {
    public T build();
}

Tree<T> buildTree(Builder<T> nodeBuilder){
    // use the nodeBuilder.build() to get a new node.
    ...
}

This is not a problem for c# because the “new()” constraint.

class Tree<T> where T : new()
{
    Tree<T> BuildTree()
    {
        // simply new T() for a new node.
        ...
    }
}

But you can also use this skill if you need to construct a new instance with some parameters.

  • Item 3: Enforce the singleton property with a private
    constructor or an enum type

Make the constructor private and set a static field or getter, it is what we said “singleton pattern”. Someone (GoF theirselfs?) said it is the worst in practice of all classic 23 design patterns.

Bloch noticed us invoking private constructor by reflection or serialization will make more than one instance here.

In the Java word, you need to make choice of  the static field and the static getter method. In the c# world, I think, you should always use the static property. it looks like the field and can do things which getter can do.

But now Java programmer can make it more elegant.

// Enum singleton - the preferred approach
public enum Elvis {
    INSTANCE;
    public void leaveTheBuilding() { ... }
}

Well…

Java wins!

  • Item 4: Enforce noninstantiability with a private constructor

Ok, it’s time for c# to beat back!

The noninstantiability class is the utility class (like Math). They just have a lot of static methods.

Java programmers need to make the default constructor private to defend someone who want to create a instance of it or inherit of it.

As a c# programmer, you just need to mark the class static!

  • Item 5: Avoid creating unnecessary objects

Make some local variable as a static field to escape create it every time.

It just a kind of refactor, no more to say.

Bloch also notice us the autobox unbox problem in the new Java.

// Hideously slow program! Can you spot the object creation?
public static void main(String[] args) {
	Long sum = 0L;
	for (long i = 0; i < Integer.MAX_VALUE; i++) {
		sum += i;
	}
	System.out.println(sum);
}
&#91;/sourcecode&#93;

Well, when you rewrite it via c#...

c# wins again!
<ul>
	<li><strong>Item 6: Eliminate obsolete object references</strong></li>
</ul>
This "obsolete" is not the ObsoleteAttribute in c#. It means some object you won't use it never.

Look the pop method below:


// Can you spot the "memory leak"?
public class Stack {
	private Object[] elements;
	private int size = 0;
	private static final int DEFAULT_INITIAL_CAPACITY = 16;

	public Stack() {
		elements = new Object[DEFAULT_INITIAL_CAPACITY];
	}

	public void push(Object e) {
		ensureCapacity();
		elements[size++] = e;
	}

	public Object pop() {
		if (size == 0)
			throw new EmptyStackException();
		return elements[--size];
	}

	/**
	 * Ensure space for at least one more element, roughly doubling the capacity
	 * each time the array needs to grow.
	 */
	private void ensureCapacity() {
		if (elements.length == size)
			elements = Arrays.copyOf(elements, 2 * size + 1);
	}
}

The new version pop is here:

public Object pop() {
	if (size == 0)
		throw new EmptyStackException();
	Object result = elements[--size];
	elements[size] = null; // Eliminate obsolete reference
	return result;
}

The pool, cache and the listeners and other callbacks (the registered even handler in c#) are mostly having this kind of memory leaks.

One word: whenever a class manages its own memory, the programmer should be alert for memory leaks.

  • Item 7: Avoid finalizers

Both Java and c# programmers should escape the using of finalizer.

Jeffrey Richter have said the same problem in the CLR via c#.

How to free the unmanaged resource?

If you are a c# programmer, you should use the disposable pattern and enjoy the “using” syntax.

As a Java programmer, you need implement your close() method and invoke it in the finally block.

If you must do something in the finalizer, don’t for get to call the super.finalize().

  • iron9light‘s item: Consider to use Dependency Injection

When you wanna create the object, you should consider to make the class interface-orianted and use Dependency Injection.

You can use the one of the exist frameworks, like Guice (by Google) for Java or Unity (by Microsoft) for c# both are open source, or you do it by yourself.

I’ve written some lightweight framework for my own project 🙂

NUnitExtension.DataDriven – an NUnit AddIn for data-driven testing

July 14, 2008

DataDriven Extension is an NUnit Addin that allows you to create test cases from any data sources (like database or plain text files etc.) and can used for parameterized test.

DataFactoryAttibute (like the FactoryAttribute in NUnit 2.5 alpha 3), indicate class of the test case factory. You can also set some arguments for creating test cases.

Test case factory class must have a defualt constructor and a method with IEnumerable as the return value for create test cases. And this method should be marked by the DataSourceAttribute (like the TestCaseFactory in NUnit 2.5 alpha 3).

TestCaseItem (like the TestCaseData in NUnit 2.5 alpha 3) is a constraint-oriented test case task class. You can set the arguments for parameterized test method or normal test method and set some constraints to check the return value or expected exception throwed by the test method.

You can download here:

NUnitExtension.DataDriven_0.1_alpha.zip

To get the source code or more information, please visit the project site:

http://code.google.com/p/nunit-extension-datadriven/

Request

  • NUnit 2.5 alpha 3 (May be compiled against other NUnit versions)
  • .NET Framework 2.0 (Not tested under .NET Framework 1.1 and mono)

Install

  1. Copy the NUnitExtension.DataDriven.AddIn.dll to “…\NUnit 2.5\net-2.0\addins\”.
  2. Add reference to NUnitExtension.DataDriven.dll and write your own data-driven tests.

Example

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.Constraints;
using NUnit.Framework.Syntax.CSharp;
using NUnitExtension.DataDriven;

[TestFixture]
public class DataDrivenTest
{
    Random random = new Random();

    [DataFactory(typeof(RandomFactory), 10)]
    public double Add(double a, double b)
    {
        return a + b;
    }

    [DataFactory(typeof(RangeFactory))]
    public double NextDouble()
    {
        return random.NextDouble();
    }

    [DataFactory(typeof(ExceptionFactory), typeof(int))]
    public void ThrowException(Type exceptionType)
    {
        if (typeof(Exception).IsAssignableFrom(exceptionType))
            if (exceptionType.GetConstructor(new Type[0]) != null)
            {
                throw (Exception) Activator.CreateInstance(exceptionType);
            }
    }
}

public class RandomFactory
{
    [DataSource]
    public IEnumerable GetTestCases(int count)
    {
        Random random = new Random();
        for(int i = 0; i

System.Web.HttpUtility for .Net Compact Framework and Sliverlight

July 4, 2008

I know some one like me wanna use the UrlEncode when he/she code on the .Net Compact Framework or Sliverlight.

Here I copy and fix the code from System.Web.dll via reflector.

Its include all the UrlEncode / UrlDecode and other utility methods.

You can use they in any .Net Frameworks.

Download the c# source code here (both files are needed):

HttpUtility.cs

HtmlEntities.cs