I'm interested in optimizing my code. Can someone help me understand the best way to trim this code down with DRY methodology?
So I've got these two classes here preforming WMI queries on two separate Win32 classes. My questions are:
- Should I keep them separated in different classes based on the Win32 class for organizational purposes?
- Should I use a parent partial class and split these into different files?
- Should I use methods with optional parameters or overloads in order to reduce the number of classes here?
- Why is the selected method best?
public class Win32OperatingSystem
{
public ulong GetFreePhysicalMemory()
{
return GetProperty("FreePhysicalMemory");
}
public ulong GetTotalVirtualMemorySize()
{
return GetProperty("TotalVirtualMemorySize");
}
public ulong GetFreeVirtualMemory()
{
return GetProperty("FreeVirtualMemory");
}
private ulong GetProperty(string propertyName)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM Win32_OperatingSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return 0;
return BytesToMegaBytes((ulong)enu.Current[propertyName]);
}
}
private ulong BytesToMegaBytes(ulong bytes)
{
return bytes / (ulong)1024;
}
}
public class Win32ComputerSystem
{
public string GetName()
{
return GetProperty("Name");
}
public string GetManufacturer()
{
return GetProperty("Manufacturer");
}
public string GetModel()
{
return GetProperty("Model");
}
private string GetProperty(string propertyName)
{
ManagementObjectSearcher moSearcher = new ManagementObjectSearcher
("SELECT " + propertyName + " FROM Win32_ComputerSystem");
using (var enu = moSearcher.Get().GetEnumerator())
{
if (!enu.MoveNext()) return "Unable to retrieve " + propertyName + " from Win32_ComputerSystem!";
return enu.Current[propertyName].ToString();
}
}
}
Questions in this series
This is the first question in the series.
First iteration of DRY refactoring