C# naming convention for enum and matching property

前端 未结 8 1088
鱼传尺愫
鱼传尺愫 2020-12-02 07:03

I often find myself implementing a class maintaining some kind of own status property as an enum: I have a Status enum and ONE Status property of Status type. How should I s

8条回答
  •  伪装坚强ぢ
    2020-12-02 07:32

    I think the real problem here is that the enum Status is encapsulated within your class, such that Car.Status is ambiguous to both the property Status and the enum Status

    Better yet, put your enum outside of the class:

    public enum Status
    {
        Off,
        Starting,
        Moving
    }
    
    public class Car
    {
        public Status Status
        { ... }
    }
    

    UPDATE

    Due to the comments below, I'll explain my design above.

    I'm one who doesn't believe that enums or classes or any other object should reside inside another class, unless it will be totally private within that class. Take the above example, for instance:

    public class Car
    {
        public enum Status
        {...}
        ...
        public Status CarStatus { get; set;}
    }
    

    While some commenters would argue that Status doesn't have any meaning outside the scope of the class Car, the fact that you are setting a public property means that there are other parts of the program that will use that enum:

    public Car myCar = new Car();
    myCar.CarStatus = Car.Status.Off;
    

    And that to me is a code smell. If I'm going to look at that status outside of Car, I might as well define it outside as well.

    As such, I will probably just rename it as:

    public enum CarStatus
    {...}
    
    public class Car
    {
        ...
        public CarStatus Status { get; set; }
    }
    

    However, if that enum will be used within and only within the car class, then I'm fine with declaring the enum there.

提交回复
热议问题