Modern and on demand

I don’t know if the name makes sense, but basically I’m interested in the opinion of people about whether public members should be counted when they should be changed, or as soon as they are available?

Let's say you have a class like CustomCollectionthat has a property Count. Should be Countupdated for each operation Add, Removeetc. Or should it just be calculated during his conversion?

Maintaining relevance seems intuitive, but then you wonder how often people call Add, Removeetc. vs .Count.

There is also a hybrid version where you can cache it when accessing a property? I think another update will be needed for the update?

+3
source share
6 answers

Most information about the state of a class should always be relevant as a side effect of data manipulation. For example, the Count property is based on internal data memory (i.e., array length).

You may need to calculate other properties that depend on certain conditions of the class state. For exaple, the property ContainsValidOrdermay depend on orders in the class. For these properties, you should evaluate the use of the class and decide whether to calculate the cost when adding and removing elements from the collection, and then scan the entire collection each time it is accessed.

.NET , , . , , , GetXXX. , , 1. 2. duratino .

+4

, , , . count , , , . , count .

-, count , false, true. add, remove .. false.

- :

Class CachedCount 
   int count = 0;
   boolean count_is_valid = false;

   int getCount()
       if count_is_valid
           return count;
       else
           count = calculate_count();
           count_is_valid = true;
           return count;

    void Add(item)
        count_is_valid = false;
        ...

    ...

: , count add, remove .. add, remove .. count. , . : add, add, add, remove, remove, add, count, count, count, count, count, count, add, count, add, count, remove, count, remove, count, add, count.

+4

, , , Count, , , .

+2

. .

count " ", , .

, (, , , )

+1

, - , , , , . , , , , , .

+1

, , , , , .

, , , . ; , (, , , , ), , , . , , .

, , , .Net.

+1

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


All Articles