.NET’s CultureInfo do not support all languages in ISO 639-1

July 4, 2009

When I wanna replace the Language enum in Google translate API for .NET, I found that, there are at two three language that Google supported but .NET Framework not.

The Filipino (tl) or Tagalog;

The Maltese (mt).

And the Hebrew, Google use “iw” as the code for its language api, but .NET and ISO 639 use “he”.

Well, where is the Babel?!

Reset your firefox location bar search if it changed by AVG

July 4, 2009

When you install the latest AVG free, it will install two firefox addons, AVG safe search and AVG security toolbar.

Disable them by Tools->Addons, click the Disable on them.

But AVG also change your location bar. When you input some keyword, it used to go to that website directly or search it as keywords by google. Now it becomes yahoo search!!!

If you don’t like yahoo or you just wanna another search engine, you can change by the steps below:

  1. Type “about:config” in the location bar and click “enter”. Now you can see the configuration page for your firefox.
  2. Find out the “keyword.URL” and reset or modify the value.
  3. Close the configuration page. Then your old location bar comes back.

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

Google Search API for .NET 0.2 beta and Google Translate API for .NET 0.2 beta released

October 8, 2008

Update4

No more default http referrer. User must set it as a parameter of constructor.

Delete old Translator and Searcher classes.

Updated comments for better document.

Update3

Change all API Using string parameter instead of enum parameter.

Add new Enumeration class and enumerations for API parameters.

The API changed a lot this time. Please let me know whether you like these changes or not.

Update2

All codes are refacted (StyleCop format).

Update the APIs to support latest Google APIs.

Now can customize referrer, accept language, API key and timeout times.

Update1

Update the supported language list for Google translate api.

Set “http://code.google.com/p/google-api-for-dotnet/” as the default http referrer. (Now you cannot set your own http referrer)

No more v0.2, new features will come with v0.3.

Google APIs for .NET

Provides simple, unofficial, .NET Framework APIs for using Google Ajax RestFULL APIs (Search API, Language API etc.)

How LAZY I am. I should release nearly a month ago.

Indeed, 99+% of source have been finished when I release the Google Search API for .NET 0.1 and Google Translate API for .NET 0.1.1.

I just wait some bugs from the last versioin, so I can do some change.

I do fixed one bug, only one.

Ok, see what’s new.

The new versions are nearly no different for using, but the foundation is changed.

Replace Json.NET 2.0 by Microsoft official WCF.

And implement the HttpUtility, so not need the System.Web any more.

It now support .NET 3.5 sp1 Client Profile.

You can download here:

GoogleSearchAPI_0.3.1.zip

GoogleTranslateAPI_0.3.1.zip

More in formations, please visit the project’s site:

http://code.google.com/p/google-api-for-dotnet/

How to excute a LINQ Expression

October 8, 2008

Linq for .NET 3.5 is a very interesting new feature. It provide you some abilities that compiler has.

Thanks for Expression (under System.Linq.Expressions namespace), we can keep the expression tree but not compiled MSIL code.

When you use Linq like this,


var count = from dataItem in data where dataItem.Value > 100 select data.Value2;

You do not need to know the expression tree (You even do not need to add the using of System.Linq.Expressions), .NET compiler and runtime to all the things for you.

That good most of the times.

Sometimes, you need to do something by yourself. Just like my current project, I need get the result directly from a expression tree.


object GetResult(Expression m);

T GetResult<T>(Expression m);

The only one I can find to do this directly is Excute method in IQueryProvider interface.


public interface IQueryProvider
{
Object Excute(Expression expression);

TResult Excute
(Expression expression);
}

Looks great, but useless. It use an interface, and I cannot find a impliment in the framework.

Ok, it’s time to show you the truth. No more words. Just the code below.


public static object GetResult(this Expression m)
{
    if (m == null)
        throw new ArgumentException("m");
    Type type = typeof (Func<>).MakeGenericType(m.Type);
    LambdaExpression lambda = Expression.Lambda(type, m);
    Delegate callback = lambda.Compile();
    object result = callback.DynamicInvoke();
    return result;
}

public static T GetResult<T>(this Expression m)
{
    if (m == null)
        throw new ArgumentNullException("m");
    Expression<Func<T>> lambda = Expression.Lambda<Func<T>>(m);
    Func<T> callback = lambda.Compile();
    T result = callback();
    return result;
}

Compile to MSIL at runtime, isn’t it cool?!

Google Search API for .NET 0.1 released

September 17, 2008

Well! Use this API to search Lehman Brothers.

Google Search API for .NET is a part of Goolge APIs for .NET project.

This project provides simple, unofficial, .NET Framework APIs for using Google Ajax RestFULL APIs (Search API, Language API etc.)

Description:

Provides a simple, unofficial, .NET Framework API for using Google Ajax Search API service.

Feature:

  • Support all 8 Google Search APIs.
  • CLS compatible. It can be used by any .NET languages (VB.NET, C++/CLI etc.)
Google Search APIs State
Google Web Search API supported
Google Local Search API supported
Google Video Search API supported
Google Blog Search API supported
Google News Search API supported
Google Book Search API supported
Google Image Search API supported
Google Patent Search API supported

Required:

  • .NET Framework 3.5. (You can build your own project on .NET 2.0, but you need to install .NET 3.5 to run this library).

Update:

You can download here:

GoogleSearchAPI_0.1.zip

You can visit the site of the project for all downloads, source,  examples and other information.

http://code.google.com/p/google-api-for-dotnet/

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 🙂