Static members class vs. normal c-like interface

前端 未结 2 531
离开以前
离开以前 2020-12-11 19:03

Hey there.
After reading here about the Service Locator pattern, it got me thinking wether a class with only static members really is the way to go, or if a normal c-lik

相关标签:
2条回答
  • 2020-12-11 19:31

    one good reason for using class interfaces is consistency.

    often, there will be supporting implementation or subclass use of the shared data in the Locator class. therefore, it is preferable (to many people) to use one approach across their codebase, rather than combining namespaces and classes for their static data (since some implementations may extend or specialize the service).

    many people don't like dealing with static data. some issues from the above examples are: thread safety, ownership, and the lifetime of the data. the data and the implementations can be easier to maintain if these are restricted to a class scope (rather than a file scope). these issues grow as the program's complexity grows -- the example you have posted is very simple.

    namespace labels/aliases are more difficult to pass around (compared to types/typedefs/template parameters). this is useful if your interfaces are similar and you are using a good amount of generic programming, or if you simply want to implement tests.

    0 讨论(0)
  • 2020-12-11 19:45

    Your proposal with namespaces has a slight weakness in maintainability - if you need to change the interface for some reason, you have to remember to change both the interface (.h) and implementation (.cpp), or a mismatch may not be detected until link time. If you use a class, then the compiler can detect an error such as a number of parameters mismatch.

    On the other hand, since the implementation (service_) in your case only appears in the .cpp file, you may be able to change the private implementation of the locator without forcing a recompile of code that depends on the locator. (Common class-based patterns can provide this same encapsulation.)

    These are fairly minor differences. A public namespace containing functions is almost exactly the same as a class with only static member functions.

    0 讨论(0)
提交回复
热议问题