JuP
JuP

Reputation: 535

Singleton or static - what should I use?

I don't know what should I use. I have 3 classes. PasswordService, SettingsService, FileService. These classes each contain about 2 methods. The methods are being used in more assemblies. Now I'm using it as a singleton. But I'm not sure if I should. I think a static class would be enough. What do you think?

CODE:

public class PasswordService
{

    private PasswordService(){}

    private static PasswordService _instance;

    public static PasswordService Instance
    {
        get { return _instance ?? (_instance = new PasswordService()); }
    }

    public byte[] EncryptPassword(string password)
    {

        var protectedPass = Encoding.UTF8.GetBytes(password);
        return ProtectedData.Protect(protectedPass, null);
    }

    public string DecryptPassword(byte[] encryptedPassword)
    {
        var unprotectedPass = ProtectedData.Unprotect(encryptedPassword, null);
        return Encoding.UTF8.GetString(unprotectedPass, 0, unprotectedPass.Length);
    }
}

Upvotes: 0

Views: 167

Answers (3)

Matthias Meid
Matthias Meid

Reputation: 12521

I recommend you to keep the Singleton, unless you're using instances or DI. A Singleton can be refactored into instances quite easily, whereas static classes must be re-implemented to being non-static. Moreover, you can replace instances with test dummies, whereas replacing a static implementation is hardly possible.

For instance you might come across a situation where your programm must handle multiple FileConfiguration instances, for two distinct config files. A Singleton can be split into a two-instance pool.

I came across this issue with a DAO class which used to be static and capable of connecting to one DB. We had to refactor it, since a new requirement included supporting n>1 databases in one program instance.

As Mikhail points out, use static only for truly stateless stuff. A config file or a chosen password hashing algorithm in a static field is already a state, as well as the connection string in my example above is - even though they might never change at runtime.

Upvotes: 1

Mikhail Gubanov
Mikhail Gubanov

Reputation: 420

You don't have any state in your class, so I do not see any reason to use instance of class. I recommend you to use static classes.

Upvotes: 2

TalentTuner
TalentTuner

Reputation: 17556

1 - It is right to create a singleton for these services since these are seems to be handle one specific task.

2 - Avoid Static as much as possible as you can not mock it efficiently if you use TDD and do automatic unit testing with contineous Integration server.

Upvotes: 1

Related Questions