Developing a method using ref to modify a partially immutable class

In my project, I have a header class that represents a globally unique key for a piece of information within the system, for example, to whom it belongs, what time it exists, etc. Inside the same class of headers, I also have fields for information specific to this data instance, for example, who created this version of the information, when it was created, if its new data should be stored in a database, etc.

The following is an example of storing some information in a data transport class and requesting it back.

var header = new IntvlDataHeader( datapoint: Guid.NewGuid(), element: Guid.NewGuid(), intervalUtc: DateTime.Now.Date); package.StockData_Decimal(header, 5m); decimal cloneData; package.TryGetData_Decimal(ref header, out cloneData); // header now refers to a different object, that could have different flags/information 

Notice how I did TryGetData_Decimal passed the header variable by reference. IntvlDataHeader is a class, and if the data is inside TryGetData, the link is replaced with a new instance of IntvlDataHeader, which has specific information about the instance in addition to the same unique key information.

Does the key combine with the specific data of a specific instance and use the ref parameter both in poor design and outside it? Will there be an attempt to split another class so that there are two parameters and ref parameters would be better or avoid any potential problems?

public bool TryGetData_Decimal(ref IntvlDataHeader header, out decimal data) method signature public bool TryGetData_Decimal(ref IntvlDataHeader header, out decimal data)

+4
source share
1 answer

I think that naming your TryGetData_Decimal is misleading if the ref parameter you pass in will point to a new instance when the method exits. TryGetData_Decimal , for me it sounds like a variation of TryParse methods for a number of value types (which have an out parameter containing the parsed value - similar to the cloneData parameter).

I think I'm not sure why the header object should point to a new instance, so I'm not sure I can recommend the design. If this is what you need to do, I think it could be more readable if your TryGetData_XXX methods have a signature something like this:

 IntvlDataHeader ExtractValueAndGetNewInstance_Decimal(IntvlDataHeader header, out decimal cloneData) 

where the title is passed but does not change when the method exits. The method returns a new instance, and you can use it if you need one. I would not change the cloneData parameters - I think the out parameters are fine if they are not used.

I would try to change the method name to something more meaningful.

Hope this helps.

+2
source

All Articles