Showing posts with label c-sharp. Show all posts
Showing posts with label c-sharp. Show all posts

Monday, June 30, 2008

When Properties Are Overkill

When you define publicly accessible state for a class, the first thing you proceed to do is define it as properties or accessor-mutator (get-set) methods. In cases where you have to perform checks on the values for code that can be used outside your assembly (or in large teams), properties do make sense because they keep the system sane.

However, if there's a class that is never going to be used by anyone except for the small group of programmers building it or does not have any checks on the input, regular public member variables are enough. If you do implement a property, it's just going to clutter up your code making it look something like this:


private string m_Name;
public string Name {
get {
return m_Name;
}
Set {
m_Name = value;
}
}
//it's a little shorter with C# 3.0 in .NET 3.5


When it should have been like this:


public string Name;


In .NET, accessing a variable and accessing a property have the same syntax, so there's almost no reason why you should have to implement all the the state as public properties when a simple variable will do. If needed, you can simply go back to the declaration and turn it into a property, something that can be easily accomplished using the refactoring features of the IDE.

In the Java world, it's a bit different - you have to write those get and set methods in the event that you decide to implement some more logic later, because you'll end up modifying a lot of code to add the "set" prefix. (Using the IDE to replace ".name" with ".setName" can change some of the string literal too, so you've got to watch out... Unless you're using an IDE that can go over the entire code that can refactor all references to the variable for you... And assuming you have access to that source code with authorization to modify... We need a new version of Java).

Tuesday, May 13, 2008

Static Classes in C#

When you create methods that do not require access to any instance variables, you would turn it into a static method. If you've got a class with only static methods, it would be easier for other developers to tell right away that the class was never meant to be instantiated - this is done by marking the class as static. Static classes cannot have a non-static constructor and cannot contain any non-static methods. They are also sealed (implicitly) and therefore cannot be inherited.

An alternative to using static classes is to create a private constructor, although this doesn't prevent you from declaring non-static methods with the class.