Is implementing a singleton using an auto-property a good idea?

前端 未结 6 1104
时光取名叫无心
时光取名叫无心 2021-01-02 05:13

I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them e

6条回答
  •  一整个雨季
    2021-01-02 05:51

    I would approach this from a slightly different direction than Jon. Regardless of whether the object is a singleton, is it logically best modeled as a property in the first place?

    Properties are supposed to represent... properties. (Captain Obvious strikes again!) You know. Color. Length. Height. Name. Parent. All stuff that you would logically consider to be a property of a thing.

    I cannot conceive of a property of an object which is logically a singleton. Maybe you've come up with a scenario that I haven't thought of; I haven't had any Diet Dr. Pepper yet this morning. But I am suspicious that this is an abuse of the model semantics.

    Can you describe what the singleton is, and why you believe it to be a property of something?

    All that said, I myself use this pattern frequently; usually like this:

    class ImmutableStack
    {
        private static readonly ImmutableStack emptystack = whatever;
        public static ImmutableStack Empty { get { return emptystack; } }
        ...
    

    Is "Empty" logically a property of an immutable stack? No. Here the compelling benefit of being able to say

    var stack = ImmutableStack.Empty;
    

    trumps my desire for properties to logically be properties. Saying

    var stack = ImmutableStack.GetEmpty();
    

    just seems weird.

    Whether it is better in this case to have a readonly field and a regular property, or a static ctor and an autoprop, seems like less of an interesting question than whether to make it a property in the first place. In a "purist" mood I would likely side with Jon and make it a readonly field. But I also frequently use the pattern of making autoprops with private setters for logically immutable objects, just out of laziness.

    How's that for taking all sides of a question?

提交回复
热议问题