Should I show a field with a null value or a HasFoo field?

I read some data from the XML format and put it in my classes, and I'm just wondering what is best for fields that can be empty and, if empty, have a default value. Values ​​that were not provided do not need to be written back to the file.

I was thinking about using types with a null value, however, which is the best way in the code to determine the default value (although I do not need a default value for each field, since not all fields have a default value set or default value 0)

I am currently using this:

class SomeElement { public const int DefaultFoo = 123; public int? Foo { get; set; } } 

but I don’t know if the following will be more obvious:

 class SomeElement { // Setting HasFoo to false will set Foo to the default value public bool HasFoo { get; set; } // Setting Foo to anything will set HasFoo to true public int Foo { get; set; } } 

Since some classes have many properties, the second option will create a lot more methods in classes, however it might be easier to use if you don't care if Foo matters.

The final alternative can be either a static method in the base class, or an extension method to make it easier to get by default (the idea is based on this )

 // In some method using the class int value = SomeElementBase.GetValueOrDefault(() => myObj.Foo); // or an extension method int value = myObj.GetValueOrDefault(x => x.Foo); 

I would still supply DefaultFoo fields, but could the static / extension method make access easier?

What are your thoughts? Has anyone encountered this problem before? Should I just use the default values ​​and omit the fields equal to their default values ​​when saving back to the file?

+4
source share
2 answers

I think a field with a null value is preferable. No extra code synchronizes them in your file, the goal is very clear, and you can just access Foo.HasValue, which, in my opinion, expresses your intention better than the separate HasValue property in the class.

+8
source

I would use a combination of null values ​​for values ​​that do not have a default value, and override the default value for getter for values ​​that have a default value (provided that you really do not need to know if you really get the default value or not):

 class SomeElement { public int? NoDefault { get; set; } private int? m_hasDefault; public int? HasDefault { set { m_hasDefault = value; } get { if(m_hasDefault.HasValue) return m_hasDefault; else return WhateverTheDefaultShouldBe; } } } 

Still return nullables in both cases to maintain consistency and hide any differences between properties that have default values ​​and values ​​not related to the calling code (this way you can easily change the values ​​that are set by default or not. class without affecting the code that the class uses).

+2
source

Source: https://habr.com/ru/post/1315241/


All Articles