The "One Shot" Getters property is considered an acceptable standard for coding in .NET (or in general)

Recently, while doing some work with C # and ActiveMQ (via Apache.NMS libraries), I came across the following property on ActiveMQBytesMessage

public new byte[] Content
{
  get
  {
    byte[] buffer = (byte[]) null;
    this.InitializeReading();
    if (this.length != 0)
    {
      buffer = new byte[this.length];
      this.dataIn.Read(buffer, 0, buffer.Length);
    }
    return buffer;
  }
  ..(setter omitted)
}

The method InitialiseReadinghandled the connection and data streams from the active MQ in the field .dataIn. The problem, however, was that IT DID THIS EVERYTIME . And once this data has been read, it can never be read again, and the dataIn field was zero and reset. Therefore, simply by observing the property and observing it again, you have lost the data. This was made for some very strange errors, such as:

byte [] myBytes = new byte[msg.Content.Length]; 
//Touched the property. Data read in.

msg.Content.CopyTo(myBytes,0); 
//Uh oh! touched it again, copying a zero'd array.

or when you were debugging and you were stuck in the watch variable, or accidentally hovering over a property.

.

+5
6

.

, . set, , . get twicwe, .

GetContent , id , .

+6

. .

getNextContent.

+2

, Command Query Separation (CQS).

The idea is that the request should be repeated without any side effects. Teams / Actions should not provide any information about the object, just make changes. (although in practice this can be done for a chain of commands)

+2
source

Its bad code, obviously, and I haven't seen it.

+1
source

Obviously, this is terrible code for exactly the reasons you gave.

+1
source

You must indicate an error. No matter how unlikely they are to fix it.

+1
source

All Articles