-1

I'm currently dealing with a long enum with roughly 100+ elements, where the first word in each element is used to categorize the entries:

public enum UserPermissions{
    FilesRead,
    FilesWrite,
    FoldersRead,
    FoldersWrite,
    NotesCreate,
    NotesDelete,
    NotesModify,
    ...
    ...
}

I would like to categorize the permissions into a more organized structure using namespaces such as:

UserPermissions.Files.Read;
UserPermissions.Notes.Modify;

The main issue here is to maintain compatibility with existing code by avoiding or minimizing refactoring needed. What is the best solution?

My current idea is to convert the enum to a class:

public class UserPermissions
{
    public enum Files{
        Read  = 1,
        Write = 2,
    }

    public enum Folders
    {
        Read  = 3,
        Write = 4,
    }
    ...
    ...
}

But this will require refactoring old code such as UserPermissions.FilesRead to UserPermissions.Files.Read.

Tee
  • 414
  • 2
  • 8
  • 19

2 Answers2

1

If you realy do not want to refactor, you can provide both temporarly:

public enum UserPermissions{
    FilesRead,
    FilesWrite,
    FoldersRead,
    FoldersWrite,
    NotesCreate,
    NotesDelete,
    NotesModify,
}

public class UserPermission //Other name then enum, or the class must be under a different namespace
{
    public enum Files
    {
        Read  = UserPermissions.FilesRead,
        Write = UserPermissions.FilesWrite,
    }

    public enum Folders
    {
        Read  = UserPermissions.FoldersRead,
        Write = UserPermissions.FoldersWrite,
    }
}

If you now have a method, you could simple cast (Folders)userPermission.

But you shouldn't do this. It's error prone (casting) and not according to DRY (Don't repeat your self). You should start refactoring instead.

Simple write your new enums, compile, fix, compile, fix, compile [...] -> success.

Christian Gollhardt
  • 16,510
  • 17
  • 74
  • 111
  • i think this is the best solution for my situation as it provides a temporary solution until the code can be properly refactored later – Tee Mar 28 '17 at 19:16
  • BTW, you only want to make enums that represents flags in plural. Every other should be singular. [See here](http://stackoverflow.com/a/1405874/2441442) @Tee – Christian Gollhardt Mar 28 '17 at 19:35
  • Thanks for tip, I'll refactor that as well – Tee Mar 28 '17 at 19:50
0

if you use one of them to save it to a database you should maintain the same number you had on your legacy code, otherwise you will run in trouble, changing the structure should not affect the behavior of your code, but you will need to refactor everything, so far that is the cost I am seeing here

Zinov
  • 3,817
  • 5
  • 36
  • 70