I currently have this code written:
public class General
{
/// <summary>
/// Private variables.
/// </summary>
private const float fVersion = 1.3f;
private static bool bMonitoring = false;
/// <summary>
/// Retrieves the current version of the application.
/// </summary>
public static float Version
{
get
{
return fVersion;
}
}
/// <summary>
/// Are we monitoring performance?
/// </summary>
public static bool Monitoring
{
get
{
return bMonitoring;
}
set
{
bMonitoring = value;
}
}
}
In case I check for General.bMonitoring or General.Version often (maybe.. over 100 times a second!) and really care about performance: is it good practice to leave my class written like that, or should I simply delete these properties and make the fields public?
In this case if you aren't going to add some logic to the getter or setter then I would use static fields. Performance will be the same.
But if later you need extra logic when you set ot get values then it preffer to use properties because it allows for versioning and it gives you Encapsulation according to OOP principles. Don't care about performance
For Monitoring property you can use Auto-Implemented Property like
public static bool Monitoring { get; set; }
but in this case you need to implement a static constructor (thanks to #Mafii)
static General()
{
Monitoring = false;
}
or if you use C# 6.0 then just:
public static bool Monitoring { get; set; } = false;
Don't worry about performance. Property access is (and should be) very fast and compiler may inline them.
Property is preferred over field not because of performance, but because encapsulation and it will really helps when later you need for example checking or make property computed.
More by Jon Skeet http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx
Related
I'm using Dependency Service to get the platform specific implementation of an interface.
Let's say I have the following interface:
public interface IMyInterface
{
bool IsEnabled { get; set; }
}
And the implementing class in my Android project:
[assembly: Dependency(typeof(MyClass))]
namespace App.Droid
{
class MyClass : IMyInterface
{
public bool IsEnabled { get; set; }
}
}
At some point in the code, I set IsEnabled to true.
After that, I start a new activity that makes my app go to background:
Intent intent = new Intent();
intent.SetAction(action);
intent.SetFlags(ActivityFlags.NewTask);
MainActivity.Instance.StartActivity(intent);
When my app returns to foreground, I access the property IsEnabled and I get false instead of true. This actually happens with every single property and private field of the impementing class. Are those properties garbage collected when I leave the app for a new activity?
The only way I found to solve this issue is to make all backing fields static, but this makes a lot of overhead in the code, which might be unnecessary if I knew the reasons under this behavoiur.
Not too understanding the title of your question.
If you use the singleton pattern, you can extract the properties based on the unique instantiation object when needed.Like this:
public class Singleton
{
// Define a static variable to hold an instance of the class
private static Singleton uniqueInstance;
// Define a private constructor so that the outside world cannot create instances of the class
private Singleton()
{
}
/// <summary>
/// Define public methods to provide a global access point, and you can also define public properties to provide global access points
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
// Create if the instance of the class does not exist, otherwise return directly
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
If not, you can use Properties (https://learn.microsoft.com/en-us/dotnet/api/xamarin.forms.application.properties?view=xamarin-forms)to access the data .Like this:
private void SaveConnectionData(JSON.Connection C)
{
App.Current.Properties[Cryptography.Encryption("AccessToken")] = Cryptography.Encryption(C.Access_token);
App.Current.Properties[Cryptography.Encryption("ExpiresIn")] = Cryptography.Encryption(C.Expires_in.ToString());
App.Current.Properties[Cryptography.Encryption("TokenType")] = Cryptography.Encryption(C.Token_type);
App.Current.Properties[Cryptography.Encryption("Scope")] = Cryptography.Encryption(JsonConvert.SerializeObject(C.Scope));
App.Current.Properties[Cryptography.Encryption("RefreshToken")] = Cryptography.Encryption(C.Refresh_token);
App.Current.SavePropertiesAsync();
}
You may be involved in the use of lifecycles and notifications.Also if there is a lot of data, consider using the SQLite database to save this data .Can refer to this link here
More:In Xamarin.Android, you also can try lifecycles to show saved data.Like OnResume method to show data.
In our .NET software component we use the following naming convention. When a customer use our DLL from VB.NET, the compiler cannot distinguish distance member field from the Distance property. What workaround do you recommend?
Thanks.
public class Dimension : Text
{
private string _textPrefix;
protected double distance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance
{
get { return Math.Abs(distance); }
}
}
You should not use fields that are protected, for the reason that versioning and access cannot be guarded. See the Field Design guidelines. Change your field to a property, which will also force you to change to name (as you cannot have two properties with the same name). Or, if possible, make the protected field private.
To make setting your property accessible only to the inheriting classes, use a protected setter:
public class Dimension : Text
{
private string _textPrefix;
private double _absoluteDistance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance
{
get { return _absoluteDistance }
protected set { _absoluteDistance = Math.Abs(distance); }
}
}
Although that does cause divergence between get and set, as functionality is not the same. Perhaps a separate protected method would be better in this case:
public class Dimension : Text
{
private string _textPrefix;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double Distance { get; private set; }
protected void SetAbsoluteDistance(double distance)
{
Distance = Math.Abs(distance);
}
}
Well, summarizing of what already being said you can do something like this :
public class Dimension : Text
{
private string _textPrefix;
private double _rawDistance;
/// <summary>
/// Gets the real measured distance.
/// </summary>
public double AbsoluteDistance
{
get; private set;
}
/// <summary>
/// Gets the raw distance
/// </summary>
public double RawDistance
{
get { return _rawDistance; }
protected set { _rawDistance = value; AbsoluteDistance = Math.Abs(value); }
}
}
When RawDistance's value is set it also sets value for AbsoluteDistance and because of that there is no need to invoke Math.Abs() in getter of "AbsoluteDistance".
In a continuation of my previous thread, I have found that a lot of my classes contain collections. Eg:
Engine - contains collection of pistons - piston - contains collection of xyz parts
Thus there is a hierarchy, as every component contains a collection of parts, which goes on and on.
This is a coding scenario I have not come across before. Constantly writing code like so:
class Part (Replace Part with apt name)
{
List<APart> parts ...
}
And then the same for APart, as that contains a collection of inner parts, is very tedious and therefore making me question whether this is the right way to code.
Is there a better way to write this sort of code? Anything like AOP etc I am open to (Though AOP is for cross-cutting concerns).
One thought:
Your Engine class could contain a PistonsManager class, which manages the list of Pistons. The PistonsManager could contain all of the logic to modify the list and shield the Engine class from having to think about Pistons. By the same logic, your PistonsManager class could contain an XYZPartsManager. This way you aren't programming list logic/management into your Engine logic, but have classes to do that. It might make readability and make the logic flow nicely.
Sometimes coding is just tedious. However, there are often patterns that can be ferreted out of an implementation.
We have a situation similar to yours and discovered that there was an underlying recursive pattern. So we implemented a base class (call it Part) that itself can contain a List(Of Part). This can be as deep as needed.
The collection classes for specific class implementations are either generic collections of the specific type or implement an interface that allows us to get at specific data in the class (we had to implement the interface mechanism due to collection collisions in WCF).
The upshot is that you will probably have a lot of discrete Part inheritors, but your will will be a common way to instantiate, process, and traverse your elements with a common set of code.
Update
This is a severely contrived example, but one that should get you pointed in the right direction. In our application, we use a substantial amount of reflection and table-mapped class names in order to severely reduce the amount of repetitive code. This example reflects some of that behavior, but not all.
This example basically shows how you can have a generic part class which contains a recursive collection of parts which are indexed at the part type level. In other words, you will have Engine and Engine will have a collection of part collections indexed by part type. For example, Engine could have a collection of Pistons, a collection of hoses, etc. This design is obviously optional, but does make it somewhat easier to process.
Here are the main classes:
/// <summary>
/// The base part collection
/// </summary>
/// <remarks></remarks>
public class PartBase
{
/// <summary>
/// The key for the record, such as a recordid
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
public virtual string CollectionKey {get; set;}
public PartBase() : base()
{
m_cParts = new PartBaseCollections();
}
public virtual void InitializeFromDataRow(DataRow oRow)
{
// ToDo: Either implement generic column/datarow mapping through reflection or have each class override this method
}
private PartBaseCollections m_cParts;
public PartBaseCollections Parts
{
get
{
return m_cParts;
}
}
public PartBaseCollection GetParts(string sTableName)
{
if (this.Parts.Contains(sTableName))
{
return this.Parts(sTableName);
}
else
{
PartBaseCollection cParts = new PartBaseCollection(sTableName);
this.Parts.Add(cParts);
return cParts;
}
}
public void AddParts(DataSet dsData)
{
foreach (DataTable oTable in dsData.Tables)
{
PartBaseCollection cParts = null;
cParts = GetParts(oTable.TableName);
cParts.AddRecordsFromTable(oTable);
}
}
}
/// <summary>
/// A collection of PartBases keyed by a value, such as a table name (for example, Pistons)
/// </summary>
/// <remarks></remarks>
public class PartBaseCollection : System.Collections.ObjectModel.KeyedCollection<string, PartBase>
{
public string CollectionKey {get; set;}
public Type RecordType {get; set;}
public PartBaseCollection(string TableName)
{
this.CollectionKey = TableName;
// Assume that the TableName is a class in the current namespace
RecordType = Type.GetType(this.GetType().Namespace + "." + TableName, false, true);
}
protected override string GetKeyForItem(PartBase item)
{
return item.CollectionKey;
}
public PartBase ManufactureRecord()
{
return Activator.CreateInstance(this.RecordType);
}
public void AddRecordsFromTable(DataTable oTable)
{
foreach (DataRow oRow in oTable.Rows)
{
PartBase oPart = null;
oPart = ManufactureRecord();
oPart.InitializeFromDataRow(oRow);
this.Add(oPart);
}
}
}
/// <summary>
/// All of the PartBaseCollection elements for a given PartBase
/// </summary>
/// <remarks></remarks>
public class PartBaseCollections : System.Collections.ObjectModel.KeyedCollection<string, PartBaseCollection>
{
protected override string GetKeyForItem(PartBaseCollection item)
{
return item.CollectionKey;
}
}
public class Engine : PartBase
{
}
public class Piston : PartBase
{
}
And here is an example of creating the engine:
public void CreateEngine()
{
DataSet dsData = new DataSet();
DataTable oTable = new DataTable("Piston");
dsData.Tables.Add(oTable);
Engine oEngine = new Engine();
oEngine.AddParts(dsData);
}
sounds like the composite design pattern - consider looking at the iterator design pattern and perhaps the visitor design pattern as these usually go together.
Still learning my ways around C# generics... is it possible to achieve this functionality?
public interface ISetting<T>
{
void SetSettings(T obj);
// myTypeHere GetSettings(T obj);
}
public class RadDockSetting : ISetting<CormantRadDock>
{
public RadDockSetting()
{
}
public RadDockSetting GetSettings(CormantRadDock dock)
{
}
public void SetSettings(CormantRadDock dock)
{
}
}
I realize this is a counter-intuitive way to be using a Getter -- shouldn't have to pass anything to it. What I'm doing is creating an object, RadDockSetting, that stores the relevant properties of the CormantRadDock -- and then returns the 'got' settings.
GetSettings is currently a static method, but I realize this will need to be refactored in order to allow implementing a getter from the interface. Maybe once this occurs the 'weirdness' of the getter will fall away?
So, a little background on all of this:
I started with a class that had a lot of 'copy/pasted' functions. These functions were in charge of saving and removing controls from a manager. When I realized this I set out trying to make these functions more generic. I succeeded, with SO's help, in making remove generic.
For reference, here is remove:
public static void Remove<T>(string controlID) where T: new()
{
Logger.InfoFormat("Removing control {0}", controlID);
T states = RadControlStates.GetStates<T>();
(states as IDictionary).Remove(controlID);
RadControlStates.SetStates<T>(states);
}
and it is called like so: RadControlSave.Remove<SerializableDictionary<string, RadPaneSetting>>(ID);
Now, I am trying to extend this genericness to the rest of the methods -- the savers. Here's how one of these methods looks currently:
public static void SavePane(CormantRadPane pane)
{
Logger.InfoFormat("Saving pane {0}", pane.ID);
RadPaneSetting paneSettings = RadPaneSetting.GetSettings(pane);
SerializableDictionary<string, RadPaneSetting> paneStates = RadControlStates.GetStates<SerializableDictionary<string, RadPaneSetting>>();
bool paneIsKnown = paneStates.ContainsKey(paneSettings.ID);
if (paneIsKnown)
{
Logger.Debug("Pane is known. Overwriting data.");
paneStates[paneSettings.ID] = paneSettings;
}
else
{
Logger.Debug("Pane is unknown. Saving data.");
paneStates.Add(paneSettings.ID, paneSettings);
}
RadControlStates.SetStates<SerializableDictionary<string, RadPaneSetting>>(paneStates);
}
At the start of this code block there is a call to "RadPaneSetting.GetSettings(pane)".
RadPaneSettings implements the ISettings interface. Here is ISetting's setter being used.
/// <summary>
/// Recreates a dashboard control based off of its settings.
/// </summary>
/// <typeparam name="T"> The type of control to be recreated. </typeparam>
/// <param name="settings"> The known settings needed to recreate the control.</param>
/// <returns> The recreated control. </returns>
public static T Recreate<T>(ISetting<T> settings) where T : new()
{
T _control = new T();
settings.SetSettings(_control);
Logger.DebugFormat("Recreated control {0}", (_control as Control).ID);
return _control;
}
It looks like you just need to add another generic parameter here
public interface ISetting<T1, T2>
{
void SetSettings(T1 obj);
T2 GetSettings(T1 obj);
}
public class RadDockSettings : ISetting<CormantRadDock, RadDockSetting>
Your question is not very clear but do you need a property:
public interface ISetting<T>
{
T Setting { get; set; }
}
public class RadDockSetting : ISetting<CormantRadDock>
{
public CormantRadDock Setting { get; set; }
}
What you have would work if you define another generic parameter (as #jaredPar pointed out). You may want to consider using Extension Methods rather than the class approach, though. It would allow you to have a "cleaner" API for getting the settings.
Sample:
public static class RadDockExtensions
{
public static RadDockSetting GetSettings(this CormantRadDock dock)
{
// Implementation
}
}
Or if you want something more generic
public static class RadDockExtensions
{
public static U GetSettings<T,U>(this T dock)
{
// Implementation
}
}
Though in this case you would need to add some constraints to actually create the implementation
It's not entirely clear to me what the purpose of the SetSettings method is, since you appear to be sending in the same object your sending to GetSettings.
In both cases you would use the above code like this:
RadDockSetting mySettings = myDock.GetSettings();
hmmmm might have missed the point.
but why would a settings class have a getSettings call? would it just return this?
The set takes a dock to initialise the instance, then get is merely the instance.
I'm not really sure what you want to do.
Maybe an extension method could do the trick rather than a method inside the interface ISetting... something like that :
public static T GetSettings<T,C>(this T t, C c) where T : ISetting<C>
{
return t;
}
Hope this helps...
I created a class which allows access to global access to a variable while only creating it once, essentially a singleton.
However, it doesn't match any of the 'correct' ways to implement a singleton. I assume that it's not mentioned because there is something 'wrong' with it but I can't see any problem with it other then the lack of lazy initialization.
Any thoughts?
static class DefaultFields
{
private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private static readonly IniConfigSource Ini = GetIni();
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private static IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public static IConfig Get()
{
return Ini.Configs["default"];
}
public static void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public static void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
It doesn't follow the usual singleton patterns as your class is static and just controls access to static variables.
Where as a singleton is normally a static single instance of a class where the only static functions are that to create and access the singleton that stores variables as normal non static member variables.
Meaning the class could quite easily be changed or made to be instanced more then once but yours cannot
You are right about the singleton, its a class with a unique instance that provides global access.
It might seem like a static class but usually its implemented in a different way.
Also bear in mind that this pattern should be used with some precaution, as its really hard to refactor out a singleton once its deep in the code. Should be used primarily when you have hardware constraints or are implemented unique points of access to a factory. I would try to avoid it whenever possible.
An example of an implementation is as follows:
public class A
{
/// <summary>
/// Unique instance to access to object A
/// </summary>
public static readonly A Singleton = new A();
/// <summary>
/// private constructor so it can only be created internally.
/// </summary>
private A()
{
}
/// <summary>
/// Instance method B does B..
/// </summary>
public void B()
{
}
}
And could be used like
A.Singleton.B()
Hope that helps.
All the methods on your class are static, so you are hiding the single instance from your users. With the singleton pattern the single instance is exposed via a public property usually called Instance (in other languages like Java it might be a method called getInstance or similar).
Your code is not wrong - it's just not the singleton pattern. If you wish to implement a singleton I would recommend Jon Skeet's article Implementing the Singleton Pattern in C#.
The biggest problem I see is that you're not doing any SyncLock-ing around writes to your INI file - multiple threads that attempt to write values at the same time could end up with unpredictable results, like both making writes and only one persisting (or multiple threads attempting to write the file at once, resulting in an IO error).
I'd create a private "Locking" object of some kind and then wrap the writes to your file in a SyncLock to ensure that only one thread at a time has the ability to change values (or, at the very least, commit changes to the INI file).
I am interested in answers to this question as well. In my opinion, there is a flood of singleton examples that use lazy instantiation, but I think you have to ask yourself if it's really necessary on a case by case basis.
Although this article pertains to Java, the concepts should still apply. This provides a number of examples for different singleton implementations. http://www.shaunabram.com/singleton-implementations/
I've also seen numerous references to the book "Effective Java", Item 71 - use lazy instantiation judiciously. Basically, don't do it unless you need to.
That's not really a singleton, it's a static class.
In many ways, static classes are similar to singleton's, true. But static classes can't implement interfaces, can't inherit functionality from a base class, and you can't carry a reference to them.
Why the readonly on the Ini field?
But if you want implement the singleton pattern, it's something like this:
static DefaultFields
{
private readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
private readonly IniConfigSource Ini = GetIni();
private static DefaultFields _default;
public static DefaultFields Default
{
get { if(this._default == null){ this._default = new DefaultFields(); } return this._default; }
}
private DefaultFields()
{
}
/// <summary>
/// Creates a reference to the ini file on startup
/// </summary>
private IniConfigSource GetIni()
{
// Create Ini File if it does not exist
if (!File.Exists(IniPath))
{
using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
{
var iniConfig = new IniConfigSource(stream);
iniConfig.AddConfig("default");
iniConfig.Save(IniPath);
}
}
var source = new IniConfigSource(IniPath);
return source;
}
public IConfig Get()
{
return Ini.Configs["default"];
}
public void Remove(string key)
{
Get().Remove(key);
Ini.Save();
}
public void Set(string key, string value)
{
Get().Set(key, value ?? "");
Ini.Save();
}
}
lazy initialization is very important for a singleton class. By declaring your class to be static you implement a static class, not a singleton class.