Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WriteOnly Property or Method?

Is there a particular scenario where a WriteOnly property makes more sense then a method? The method approach feels much more natural to me.

What is the right approach?

Using Properties:

Public WriteOnly Property MyProperty As String
   Set(ByVal value as String)
      m_myField = value
   End Set
End Property
public string MyProperty
{
   set{ m_myField = value;}
}

Using Methods:

Public Sub SetMyProperty(ByVal value as String)
   m_myField = value
End Sub
public void SetMyProperty(string value)
{
   m_myField = value;
}

EDIT Just to clarify I am referring to "WriteOnly" properties.

like image 646
Micah Avatar asked Nov 27 '08 04:11

Micah


People also ask

What is a write only property?

A write only property is a property that we can assign a value to but can't get that value because that property doesn't have a get accessor. For example we have a Person class that has the property FirstName that has a set accessor but doesn't have a get accessor so it is a write only property.

How can you make a property write only?

You can use WriteOnly only at module level. This means the declaration context for a WriteOnly property must be a class, structure, or module, and cannot be a source file, namespace, or procedure. You can declare a property as WriteOnly , but not a variable.

What is read only property in C sharp?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

What is a property Visual Basic?

A property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color. Properties can be set at design time by using the Properties window or at run time by using statements in the program code. Object.


2 Answers

I think a property indicates something that can be read-only or read/write. The behaviour of a write-only property is not obvious so I avoid creating them.

As an example, setting a list of values in a drop-down on a view and accessing the selected item:

public interface IWidgetSelector
{
  void SetAvailableWidgets(string[] widgets);

  string SelectedWidget { get; set; }
}

Makes more sense than:

public interface IWidgetSelector
{
  string[] AvailableWidgets { set; }

  string SelectedWidget { get; set; }
}
like image 76
Andrew Kennan Avatar answered Sep 21 '22 06:09

Andrew Kennan


For what it's worth, the Microsoft Framework Design Guidelines (as embodied in their FxCop tool) discourage Write-Only Properties and flag their presence as an API design issue, due to the unintuitiveness of that approach.

like image 45
Matt Campbell Avatar answered Sep 18 '22 06:09

Matt Campbell