开发者

Frequent Functions: How to Structure?

How should one structure thei开发者_开发百科r frequently used non-important functions (conversions, etc) in C# since everything must be contained in an object? Usually I take all these functions and put them in a static Utility class. Is this a good practice? How do most developers do it?


This tends to be what most developers end up doing, myself included.

The only pitfall is when you start having a massive set utilities that shouldn't really all belong together (conversion, database access, logging you name it...).

Try to structure these as different assemblies, so projects that do not need a set of utilities will not have to import a large set of extraneous code.


An elegant method for doing that in C# is using extension methods (Link). You can then only import the relevant namespace if you need your utility functions.

On the technical side this is basically just a static utility class as you described it, but in C# you get nice syntactic sugar for using them.


Depending on the particular need, I'll normally use a static structure or a registered service provider. For example, for logging, I'll normally use a service provider and a logging class with an interface or base logger type, and then in dev mode I'll register a message box provider so that I can see all the logged lines for a particular log level, whereas for getting a particular List.find predicate for an object list I'll build a utility class that has a static method which returns a type-appropriate predicate class.


I second the notion of using extension methods for this. I generally have classes, in a .Extensions namespace, like StringExtensions, IEnumerableExtensions, etc. Basically, I try and create a separate class for each logical grouping of functionality. Normally that means I group them by the type they extend, the type they produce, or the overarching feature they support (converting, formatting, etc).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜