A Question of Style: Accessor Methods

B

bg_ie

Hi,

I'm not happy with the way in which I use accessors and was wondering
if there is a better way of defining them. Take the following example
-

class MyClass
{
// prepended to version names appearing in version combo box
private static string versionPrefix;

// the current version selected by user
public currentVersionName = null;

public MyClass()
{
versionPrefix = GetVersionPrefix();
}

...

// prepended to version names appearing in version combo box
public static string VersionPrefix
{
get
{
return versionPrefix;
}
}

...
}


comboBoxVersion.SelectedIndex =
comboBoxVersion.FindStringExact(MClass.VersionPrefix +
myClass.CurrentVersionName);

The problem is the amount of lines versionPrefix and its accessor
takes up within the class definition. What styles do you guys use?
Also, I don't like how the definition and accessor method is split up
and I feel like I have to repeat my comments. It feels to my that
get{} is a property of versionPrefix (you can get me but not set me),
and therefore belongs with its declaration in the same way that static
does. Perhaps I'd prefer to do something like this before my
constructor, but perhaps its not good practice -

// prepended to version names appearing in version combo box
private static string versionPrefix = "Version Name: ";
public static string VersionPrefix { get { return
versionPrefix; }}

Thanks for your suggestions,

Barry.
 
M

Marc Gravell

Re breaking up the field and property; I agree: stick them next to
eachother. This also removes the need to duplicate the comment, which
would be better as an xml comment for intellisense.

Re the number of lines... then don't use as many? Event sticking with
Allman you can reduce the line count significantly...
If something is genuinely readonly, then I suggest marking it as such
in the field definition; if you had done so you would have noticed
that you are setting the static field in the instance ctor.

Finally, regions may help (although if there are more than a members
in each I tend to use partial classes to split the instance and static
parts into a MyClass.instance.cs and MyClass.static.cs)

class MyClass
{
#region instance members
public MyClass() {} // default instance ctor
#endregion

#region static members
static MyClass() // initialise the (static) version prefix
{
versionPrefix = GetVersionPrefix();
}
private readonly static string versionPrefix;
/// <summary>Prepended to version names appearing in version combo
box</summary>
public static string VersionPrefix
{
get { return versionPrefix; }
}
#endregion
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top