Mr. TA Inherited C# code to communicate with humidity and temperature sensors. Each sensor logs a set of data points at runtime and can provide them as an array of data points.
This leads to this code:
DataPoint[] humidDataPointArray = null;
DataPoint[] tempDataPointArray = null;
if (sensorType == (int)SensorTypeID.HUMIDITY)
humidDataPointArray = new DataPoint[ttPlusData.SecondarySensorData.GetDataPoints().Count];
humidDataPointArray = ttPlusData.SecondarySensorData.GetDataPoints().ToArray();
else
if (sensorNum == 1)
tempDataPointArray = new DataPoint[((SingleSensorTemptale)ttData).PrimarySensorData.GetDataPoints().Count];
tempDataPointArray = ((SingleSensorTemptale)ttData).PrimarySensorData.GetDataPoints().ToArray();
else
tempDataPointArray = new DataPoint[ttPlusData.SecondarySensorData.GetDataPoints().Count];
tempDataPointArray = ttPlusData.SecondarySensorData.GetDataPoints().ToArray();
It is okay. Create an array to hold your data. next, sensorType
for enums. And that’s where things start to go wrong.
Initialize an empty array with the same size as the number of data points, and set the array equal to the array of data points.
I’m having trouble deciding whether this is someone with no real experience, or a C programmer trying to transition from pointers to references. C# uses references so you don’t have to new
– Just set it up humidPointsArray
Same as the result of a function call.
Speaking of the result of the function call, it looks like this GetDataPoints()
Returns a C# enum. This means there’s really no good reason to convert it to an array. I’m not sure about that. Maybe you really need an array, but I doubt that’s the case. It is a C# best practice to use more abstract interfaces for collections.
But things get even worse.
we, else
and if
In that, instead else if
. This second condition avoids the nice enum we used earlier and just checks. sensorNum == 1
. Then you repeat the same unnecessary assignment, with a spelling error to boot. SingleSensorTemptale
This will never cause any problems for developers in the future.
As a bonus, this code runs in a tight loop, giving the garbage collector lots of practice cleaning up memory it didn’t need in the first place.
Move the pleb away from the main body. Restrict NuGet feed permissions using ProGet. learn more.