How can System.String be properly wrapped for case-insensitivy?

前端 未结 5 1741
谎友^
谎友^ 2021-01-12 07:05

This question is not about managing Windows pathnames; I used that only as a specific example of a case-insensitive string. (And I if I change the example now, a w

5条回答
  •  半阙折子戏
    2021-01-12 07:08

    First, Call a Spade a Spade
    You must define what is the clear responsibility of the class.

    Either you want the class to manage Windows Path names and then you can't discard all remarks regarding that because the "code managing case" will be merged with the "code managing paths". Coupling will make you then unable to test (and ensure proper behaviour) casing without path consideration.

    Or you want to implement a CaseInvariantString and then you name it adequately (and maybe use it in another class named WindowsPathname).

    For references about Class Responbility, Cohesion, Coupling and other great concepts, I would recommend the following books:

    • Clean Code from Robert C. Martin (Uncle Bob)
    • Code Complete from Steeve McConnell

    Second, wrapping strings inside a class to check for case invariance can be viewed as wrapping integer in a PositiveInteger class. It can (and will) be considered by some as over-engineering. It is a common tendency from all developers to try to reach the pinnacle of object oriented dogma. Here it seems like the practice of wrapping all value types in class (like int into an ID class). However, don't forget to ask you questions.

    • What is the cost of adopting such practice?
    • What are the benefits?
    • What are the difficulties it may lead to?
    • Could I adopt the general approach for all my projects?
    • Do I have an enactment of my tech lead/architect (or similar authority) that it is a good practice?

    Finally, as a simple technical point. You shouldn't create a string inside your class. It's deleterious for performance. In fact, because strings are invariant, when you do a ToUpperInvariant() in GetHashCode() it creates a new String.

    And for the sake of path invariance... It doesn't work outside Windows
    (For Mono, obviously "/foo" != "/Foo").

提交回复
热议问题