blast2857
blast2857
CC#
Created by blast2857 on 4/7/2024 in #help
Static helper class/method design question
Hello, I have a design question. I'm writing a helper class where the purpose is solely to find types on the assembly (via reflection and making use of certain patterns) for a certain path. Since I may need to get the path multiple times for multiple files I thought that caching it would be the proper way to approach this. But I have a few concerns, I always hear that having state in a static class, in this case the cache is not a good idea. But I also don't really need an instance of the class since all it really is it's a helper so I'm not sure how would I go for designing this in a different way. Likewise, I'm not a fan of the methods existing there but never being "normally" called (only via reflection after being grabbed via the attribute)
internal class FinderAttribute : Attribute {
public string Path { get; init; }
public string Note { get; init; }
}

internal static class FinderHelper {
private static Dictionary<string, Type> _pathCache = new();

public static void FillCache() {
var finders = Assembly.GetExecutingAssembly().GetTypes().SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)).Where(m => m.GetCustomAttribute<FinderAttribute>() != null);
foreach (var finder in finders) {
var attr = finder.GetCustomAttribute<FinderAttribute>();
_pathCache[attr.Path] = (Type)finder.Invoke(null, []);
}
}

public static Type FindTypeForPath(string path) => ...;

[FinderAttribute(Path = "Path1/Path2/", Note = "...")]
private static Type Find1() {
// do logic to find the Type for path 1 in the assembly...
}

[FinderAttribute(Path = "Path1/Path3/", Note = "...")]
private static Type Find2() {
// do logic to find the Type for path 2 in the assembly...
}
}
internal class FinderAttribute : Attribute {
public string Path { get; init; }
public string Note { get; init; }
}

internal static class FinderHelper {
private static Dictionary<string, Type> _pathCache = new();

public static void FillCache() {
var finders = Assembly.GetExecutingAssembly().GetTypes().SelectMany(t => t.GetMethods(BindingFlags.Static | BindingFlags.NonPublic)).Where(m => m.GetCustomAttribute<FinderAttribute>() != null);
foreach (var finder in finders) {
var attr = finder.GetCustomAttribute<FinderAttribute>();
_pathCache[attr.Path] = (Type)finder.Invoke(null, []);
}
}

public static Type FindTypeForPath(string path) => ...;

[FinderAttribute(Path = "Path1/Path2/", Note = "...")]
private static Type Find1() {
// do logic to find the Type for path 1 in the assembly...
}

[FinderAttribute(Path = "Path1/Path3/", Note = "...")]
private static Type Find2() {
// do logic to find the Type for path 2 in the assembly...
}
}
Is this a good design or where could I improve / change it?
7 replies