I have a volume variable that I want to be protected from modification unless the person calls a certain function. Is there a way to make it to where it can only be modified by that function other than creating a private class within the class. I suppose that creating a private class is a good idea, but I would be interested if someone else has a different approach. AudioPlayer should never be allowed to change the volume without calling SetVolume. That's the code I have here, but I wondered if people had a different way.
public class AudioPlayer
{
private class VolumeManager
{
private AudioPlayer mAudioPlayer;
public VolumeManager(AudioPlayer audioPlayer)
{
mAudioPlayer = audioPlayer;
}
private float volume;
public void SetVolume(float _volume)
{
volume = _volume;
//Do other necessary things that must happen when volume is changed
//This is the point of the question
mAudioPlayer.ModifyChannelVolume(Volume);
}
public float GetVolume()
{
return volume;
}
}
private VolumeManager mVolumeManager;
public AudioPlayer()
{
mVolumeManager = new VolumeManager(this);
}
public void ModifyVolume(float volume)
{
mVolumeManager.SetVolume(volume);
}
}
The problem, as I see it, is that even with a private field it's still somewhat intuitive and natural to want to assign directly to the field. We want to make very sure this doesn't happen. In that case, I recommend building this as a property, rather than a field, and just being disciplined about only assigning to the property:
public class AudioPlayer
{
public float Volume
{
get { return _volume_NeverSetThisDirectly;}
set
{
_volume = value;
//Do other necessary things that must happen when volume is changed
ModifyChannelVolume(_volume_NeverSetThisDirectly);
}
}
[Browsable(false)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
[EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
private float _volume_NeverSetThisDirectly; //Never assign to this directly!
}
This won't enforce it to the degree that you're asking for, but it does flip the intuitive and natural way someone will work in this class to use the value in the right way, rather than the wrong way. It's also a heck of a lot less code and complexity to maintain. The addition of the attributes largely won't effect things for someone working in this class already, but since we're changing to use social pressures rather than technical prohibitions, the more warning signs we have up, the better.
This also gives you an opening in the future when you find that one weird case where you do want to change the volume field without all of that other stuff happening, that you can do so without needing to do strange things to a private class instance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments