Friday, December 10, 2010

Thinkings - Static Class vs Instance Class

When developing very often a developer wonder if to use a static class or a instance class. It is a decision that really depends on what you are going to do, and i think also from person to person, and because of that i would like you to tell me in wich situations you use each of them.

In my case, for example, if i have to create a business layer, typically i will use static classes. Imagine i have to develop a Content Management System, and i need the methods to write post, delete post, edit post and get posts, so my approach would be to create a static class like the following:

public static class PostsManager
{
    public static void WritePost(String user,String text) {...}
    public static void DeletePost(String user,String text) {...}
    public static void EditPost(String user,String text) {...}
    public static ICollection GetPosts(DateTime begin, DateTime end) {...}
}

and now you are wondering, what is that collection of Post?! That is my instance class, because the method GetPosts will return all the posts between two dates, and because ill need severall instances of Post than i am using a instance class.

public class Post
{
    public Post(String Author, String text) {...}

    public String Author { get; private set; }
    public String Text { get; private set; }

    public String TextTruncated(int size) {...}
}

No comments:

Post a Comment