What to call an object that acts like an enter-only-once gate? - oop

What would you call a stateful function/object x() -> bool with the following behavior: on the first call it returns TRUE, on all consecutive calls it returns FALSE. Maybe there is a pattern name already for such functionality?

The closest concept is the read-once object pattern from the Secure by Design book. Look at the paragraph below describing the object that allows to request the password only once.
A read-once object is, as the name implies, an object designed to be read once. This object
usually represents a value or concept in your domain that’s considered to be sensitive
(for example, passport numbers, credit card numbers, or passwords). The main purpose
of the read-once object is to facilitate detection of unintentional use of the data
it encapsulates.
public final class SensitiveValue {
private transient final AtomicReference<String> value;
public SensitiveValue(final String value) {
validate(value);
this.value = new AtomicReference<>(value);
}
public String value() {
return notNull(value.getAndSet(null),
"Sensitive value has already been consumed");
}
#Override
public String toString() {
return "SensitiveValue{value=*****}";
}
}
I don't know the full context of your problem but the book suggests to use the read-once object pattern in favor of security perspective. #jaco0646 also pointed out in the comments that the concept is similar to the circuit breaker pattern. Though it doesn't force for the object to always return the same value on consecutive calls. Instead, it temporary makes to obtain the stub value to give the external service some time to recover.

Related

How to respect encapsulation when storing data in domain centric applications?

Let's say I have a class Order. An Order can be finished by calling Order.finish() method. Internally, when an Order is finished, a finishing date is set:
Order.java
public void finish() {
finishingDate = new Date();
}
In the application's business logic, there is no need to expose an Order's finishingDate, so it is a private field without a getter.
Imagine that after finishing an Order, I want to update it in a database. For instance, I could have a DAO with an update method:
OrderDao.java
public void update(Order order) {
//UPDATE FROM ORDERS SET ...
}
In that method, I need the internal state of the Order, in order to update the table fields. But I said before that there is no need in my business logic to expose Order's finishingDate field.
If I add a Order.getFinishingDate() method:
I'm changing the contract of Order class without adding business value, ubt for "technical" reasons (an UPDATE in a database)
I'm violating the principle of encapsulation of object oriented programming, since I'm exposing internal state.
How do you solve this? Do you consider adding getters (like "entity" classes in ORM do) is acceptable?
I have seen a different approach where class itself (implementation) knows even how to persist itself. Something like this (very naive example, it's just for the question):
public interface Order {
void finish();
boolean isFinished();
}
public class DbOrder implements Order {
private final int id;
private final Database db;
//ctor. An implementation of Database is injected
#Override
public void finish() {
db.update("ORDERS", "FINISHING_DATE", new Date(), "ID=" + id);
}
#Override
public boolean isFinished() {
Date finishingDate = db.select("ORDERS", "FINISHING_DATE", "ID=" + id);
return finishingDate != null;
}
}
public interface Database {
void update(String table, String columnName, Object newValue, String whereClause);
void select(String table, String columnName, String whereClause);
}
Apart from the performance issues (actually, it can be cached or something), I like this approach but it forces us to mock many things when testing, since all the logic is not "in-memory". I mean, the required data to "execute" the logic under test is not just a field in memory, but it's provided by an external component: in this case, the Database.
This is an excellent observation in my opinion. No, I don't consider adding any methods just for technical reasons acceptable, especially getters. I must admit however, that the majority of people I've worked with would just add the getters and would not think about it in detail as you do.
Ok, so how do we solve the problem of persisting something we can't get access to? Well, just ask the object to persist itself.
You can have a persist() (or whatever) method on the object itself. This is ok, since it is part of the business. If it is not, think about what is. Is it sendToBackend() maybe? This does not mean you have to put the details of persistence into the object!
The method itself can be as removed from actual persistence as you like. You can give it interfaces as parameters, or it can return some other object that can be used further down the line.
See these other answers about the same problems for presentation:
Returning a Data Structure to Display information
Encapsulation and Getters

OO Software desing handling constraints - which design pattern to use?

I'm looking at a well-known problem and therefore there has to be a design pattern or a mix of patterns to solve it.
With the following classes and properties:
CTask
Name
Duration
TaskArea
CTaskArea
Name
CPerson
Name
Abilities
CAbility
Name
CTool
Name
CleaningTime
CConstraint
Name
Constraint
CTask, CPerson, CTool could have constraints e.g. Task A could only be done by persons with ability X, or person A could not do tasks of TaskArea X and so on.
For example, when I create a new CTask, CPerson or CTool I could imagine a constraint config dialog with dropdowns like:
Class | Operator | Class | Property | Value
CPerson | NOT | CTool | Name | Hammer
What design pattern provides the opportunity to dynamically configure constraints for all the classes, without forcing the classes to know additional information or take additional dependencies on each other?
Can I use an interface for objects to express that they accept constraints being applied somehow, or to discover classes which should be configurable with constraints?
Why not to have contraints_for_xxx property at each object having a constraint for particular xxx property?
When some child property is to be added into a collection, it is first run through constraints collection. If any constraint item returns false... exception is thrown, heaven thunders etc.
Constraints can be filled in object's constructor or later via some setupConstraints() call.
CPerson can look like (PHP example):
class Person
{
protected $constraintsAbc = null;
public function setConstraintsAbc(array $constraints)
{
$this->constraintsAbc = $constraints;
}
public function setABC($value)
{
foreach ($this->constraintsAbc as $constraint) {
if (!$constraint->isValid($value)) {
throw new Exception("Constraint {$constraint->getName()} is not happy with value $value");
}
}
$this->abc = $value;
}
}
class PersonSetup
{
public function setupPerson(Person $person)
{
$constrains[] = new PersonAbcConstraint("Value > 5");
$person->setContraintsABC($constrains);
}
}
This is, of course, fictious example. There is a problem here in some code duplication since you have constraintsAbc, setConstraintsAbc and setAbc as different hard-coded fields. But you can abstract this into some virtual "constraintable" field collection if you like.
this is the solution im ok with:
class CCouldHaveConstraints_Base
{
public virtual GetInstance();
public virtual GetClassName();
public virtual GetPropertyListThatCouldHaveConstraints();
}
class CPerson : CCouldHaveConstraints_Base
{
private String m_PersonName;
private String m_PersonAge;
public String PersonName
{
get {return this.m_PersonName;}
set {this.m_PersonName=value;}
}
public String PersonAge
{
get {return this.m_PersonAge;}
set {this.m_PersonAge=value;}
}
public override GetInstance()
{
return new CPerson;
}
public override GetClassName
{
return "Person";
}
public list<string> GetPropertyListThatCouldHaveConstraints()
{
list <string> ConstraintPropsList = new list<string>;
ConstraintPropsList.Add ("PersonName")
}
}
// class contains a list of all objects that could have constraints
class CConstraint_Lst
{
private list<CConstraint> m_ListOfConstraints;
private list<CCouldHaveConstraints_Base> m_ListOfObjectsThatCouldHaveConstraints;
}
// e.g Person | Person.Name | Tim | NOT | Tool | Tool.Name | "Hammer"
class CConstraint
{
private String m_ClassName_A;
private String m_ClassProperty_A;
private String m_ClassProperty_A_Value;
private String m_Operator;
private String m_ClassName_B;
private String m_ClassProperty_B;
private String m_ClassProperty_B_Value;
}
Is that enough code to figure out how im thinking?
Regards,
Tim
You've already made a great conceptual leap to model the constraints as CConstraint objects. The remaining core of the question seems to be "How do I then organize the execution of the constraints, provide them with the right inputs, and collect their outputs? (the outputs are constraint violations, validation errors, or warnings)"
CConstraints obviously can't be evaluated without any input, but you have some choices on how exactly to provide them with input, which we can explore with questions:
Do they get given a 'global state' which they can explore and look for violations in?
Or do they get given a tuple of objects, or object graph, which they return a success or failure result for?
How do they signal constraint violations? Is it by throwing exceptions, returning results, adding them to a collection of violations, or removing violating objects from the world, or triggering repair rules?
Do they provide an "explanation" output that helpfully explains which object or combination of objects is the offending combination, and what rule it violates?
Compilers might be an interesting place to look for inspiration. We know a good compiler processes some complicated input, and produces one or more easy-to-understand error messages allowing the programmer to fix any problem in their program.
Compilers often have to choose some pattern of organizing the work that they're doing like recursion (recursive descent), or a visitor pattern (visit a tree of objects in some arrangement), or stateful pattern matching on a stream of input approach (syntax token recognition by regex matching, or processing a stream of characters), or a chain-of-responsibility (one processor validates and processes input, passes it to the next processor in the chain). Which is actually a whole family of design patterns you can choose from.
Probably one of the most flexible patterns to look at which is useful for your case is the visitor pattern, because you can extend your domain model with additional classes, all of which know how to do a 'visiting' phase, which is basically what 'validation' often entails - someone visits all the objects in a scenario, and inspects their properties, with an easily extensible set of logics (the validation rules) specific to those types of objects, without needing to worry about the mechanics of the visiting procedure (how you traverse the object graph) in each validation rule.

How do I make a well designed validation for a complex collection model?

As input I have a list of Books. As output I expect a SimilarBookCollection.
A SimilarBookCollection has an author, publishYear and list of Books. The SimilarBookCollection can't be created if the author of the books is different or if the publishYear is different.
The solution so far in PHP:
client.php
----
$arrBook = array(...); // array of books
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
$objSimilarBookCollection = new SimilarBookCollection($arrBook);
echo $objSimilarBookCollection->GetAuthor();
}
else {
echo 'Invalid input';
}
SimilarBookCollection.php
---
class SimilarBookCollection() {
public function SimilarBookCollection(array $arrBook) {
$objValidator = new SimilarBookCollectionValidator($arrBook);
if ($objValidator->IsValid()) {
throw new Exception('Invalid books to create collection');
}
$this->author = $arrBook[0]->GetAuthor();
$this->publishYear = $arrBook[0]->GetPublishYear();
$this->books = $arrBook;
}
public function GetAuthor() {
return $this->author;
}
public function GetPublishYear() {
return $this->publishYear;
}
public function GetBooks() {
return $this->books;
}
}
SimilarBookCollectionValidator.php
---
class SimilarBookCollectionValidator() {
public function IsValid() {
$this->ValidateAtLeastOneBook();
$this->ValidateSameAuthor();
$this->ValidateSameYear();
return $this->blnValid;
}
... //actual validation routines
}
The goal is to have a "special" collection with only books that have the same author and publishYear. The idea is to easily access the repeating information like author or year from the object.
How would you name the SimilarBookCollection? The current name is to
generic. Using a name like SameYearAuthorBookCollection looks a bit
long and strange(if more conditions will be added then name will increase)
Would you use a Validator in SimilarBookCollection constructor using a
defensive programming style?
Would you change the design of the code? If yes how?
It all depends ;)
So if I were to aim for a generic adaptable solution I would do the following:
Validator in constructor
On one hand you are validating twice; that is informative in case of a broken precondition/contract (not giving a valid list), but is double the code to run - for what purpose exactly?
If you want to use this in a system depends on its size, how critical it is, product phase, and likely more criterias.
But then it also is controller logic fitted into a model meaning you are spreading your code around.
I would not put it in the constructor.
Name / Design
I would say keep the BookCollection generic as it is, and have any validation strictly in the controller space, instead of bloating the collection which essentially seems to be an array with the extra field of author.
If you want to differentiate between different collection types use either (multiple) inheritance or some sort of additional field "collectionType"; the former if you expect many derivatives or varying functionality to come (also keeps the logic where different nicely separated).
You could also consider your collection as a set on which you perform queries and for convenience's sake you could maintain some sort of meta data like $AuthorCount = N, $publicationDates = array(...) from which you can quickly derive the collection's nature. This approach would also keep your validator-code minimal (or non-existent), as it'd be implicitly in the collection and you could just do the validation in the controller keeping the effective logic behind it clearly visible.
That would also make it more comfortable for you in the future. But the question really is what you want and need it for, and what changes you expect, because you are supposed to fit your design to your requirements and likely changes.
For your very particular problem the constraints as I understand are as follows:
There is only one collection type class in the system at any given
point in time.
The class's items have several attributes, and for a particular, possibly changing subset of these (called identical attributes), the collection only accepts item lists where the chosen attributes of all items are identical.
The class provides getters for all identical attributes
The class must not be usable in any other way than the intended way.
If not for point 1 I would use a generic base class that is either parametrized (ie you tell it upon instantiation which is the set of identical attributes) or uses multiple inheritance (or in php traits) to compose arbitrary combinations with the needed interfaces. Children might rely on the base class but use a predefined subset of the identical attributes.
The parametrized variant might look something as follows:
class BookCollection {
public function __construct($book_list, $identical_fields=array())
{
if (empty($book_list))
{
throw new EmptyCollectionException("Empty book list");
}
$default = $book_list[0];
$this->ia = array();
foreach($identical_fields as $f)
{
$this->ia[$f] = $default->$f;
}
foreach($book_list as $book)
{
foreach($identical_fields as $f)
{
if ($this->ia[$f] !== $book->$f)
{
throw new NotIdenticalFieldException("Field $f is not identical for all");
}
}
}
$this->book_list = $book_list;
}
public function getIdentical($key)
{
$this->ia[$key];
}
}
final class BC_by_Author extends BookCollection{
public function __construct($book_list)
{
parent::__construct($book_list,array('author'));
}
public function getAuthor(){ $this->ia['author']; }
}
or fooling around with abstract and final types (not sure if it's valid like this)
abstract class BookCollection{
public final function __construct($book_list){...}
abstract public function getIdenticalAttributes();
}
final class BC_by_Author {
public function getIdenticalAttributes(){ return array('author'); }
public function getAuthor(){ return $this->ia['author']; }
}
If you rely on getters that do not necessarily match the field names I would go for multiple inheritance/traits.
The naming then would be something like BC_Field1Field2Field3.
Alternatively or additionally, you could also use exactly the same classname but develop your solutions in different namespaces, which would mean you wouldn't have to change your code when you change the namespace, plus you can keep it short in the controllers.
But because there will only ever be one class, I would name it BookCollection and not unnecessarily discuss it any further.
Because of constraint 4, the white box constraint, the given book list must be validated by the class itself, ie in the constructor.

Do write-only properties have practical applications?

I don't know why I started thinking about this, but now I can't seem to stop.
In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax:
class WeirdClass
{
private void Hello(string name)
{
Console.WriteLine("Hello, {0}!", name);
}
public string Name
{
set { Hello(name); }
}
}
In other words, the property has a setter but no getter, it's write-only.
I guess I can't think of any reason why this should be illegal, but I've never actually seen it in the wild, and I've seen some pretty brilliant/horrifying code in the wild. It seems like a code smell; it seems like the compiler should be giving me a warning:
CS83417: Property 'Name' appears to be completely useless and stupid. Bad programmer! Consider replacing with a method.
But maybe I just haven't been doing this long enough, or have been working in too narrow a field to see any examples of the effective use of such a construct.
Are there real-life examples of write-only properties that either cannot be replaced by straight method calls or would become less intuitive?
My first reaction to this question was: "What about the java.util.Random#setSeed method?"
I think that write-only properties are useful in several scenarios. For example, when you don't want to expose the internal representation (encapsulation), while allowing to change the state of the object. java.util.Random is a very good example of such design.
Code Analysis (aka FxCop) does give you a diagnostic:
CA1044 : Microsoft.Design : Because
property 'WeirdClass.Name' is write-only,
either add a property getter with an
accessibility that is greater than or
equal to its setter or convert this
property into a method.
Write-only properties are actually quite useful, and I use them frequently. It's all about encapsulation -- restricting access to an object's components. You often need to provide one or more components to a class that it needs to use internally, but there's no reason to make them accessible to other classes. Doing so just makes your class more confusing ("do I use this getter or this method?"), and more likely that your class can be tampered with or have its real purpose bypassed.
See "Why getter and setter methods are evil" for an interesting discussion of this. I'm not quite as hardcore about it as the writer of the article, but I think it's a good thing to think about. I typically do use setters but rarely use getters.
I have code similar to the following in an XNA project. As you can see, Scale is write-only, it is useful and (reasonably) intuitive and a read property (get) would not make sense for it. Sure it could be replaced with a method, but I like the syntax.
public class MyGraphicalObject
{
public double ScaleX { get; set; }
public double ScaleY { get; set; }
public double ScaleZ { get; set; }
public double Scale { set { ScaleX = ScaleY = ScaleZ = value; } }
// more...
}
One use for a write-only property is to support setter dependency injection, which is typically used for optional parameters.
Let's say I had a class:
public class WhizbangService {
public WhizbangProvider Provider { set; private get; }
}
The WhizbangProvider is not intended to be accessed by the outside world. I'd never want to interact with service.Provider, it's too complex. I need a class like WhizbangService to act as a facade. Yet with the setter, I can do something like this:
service.Provider = new FireworksShow();
service.Start();
And the service starts a fireworks display. Or maybe you'd rather see a water and light show:
service.Stop();
service.Provider = new FountainDisplay(new StringOfLights(), 20, UnitOfTime.Seconds);
service.Start();
And so on....
This becomes especially useful if the property is defined in a base class. If you chose construction injection for this property, you'd need to write a constructor overload in any derived class.
public abstract class DisplayService {
public WhizbangProvider Provider { set; private get; }
}
public class WhizbangService : DisplayService { }
Here, the alternative with constructor injection is:
public abstract class DisplayService {
public WhizbangProvider Provider;
protected DisplayService(WhizbangProvider provider) {
Provider = provider ?? new DefaultProvider();
}
}
public class WhizbangService : DisplayService {
public WhizbangService(WhizbangProvider provider)
: base(provider)
{ }
}
This approach is messier in my opinion, because you need to some of the internal workings of the class, specifically, that if you pass null to the constructor, you'll get a reasonable default.
In MVP pattern it is common to write a property with a setter on the view (no need for a getter) - whenever the presenter sets it content the property will use that value to update some UI element.
See here for a small demonstration:
public partial class ShowMeTheTime : Page, ICurrentTimeView
{
protected void Page_Load(object sender, EventArgs e)
{
CurrentTimePresenter presenter = new CurrentTimePresenter(this);
presenter.InitView();
}
public DateTime CurrentTime
{
set { lblCurrentTime.Text = value.ToString(); }
}
}
The presenter InitView method simply sets the property's value:
public void InitView()
{
view.CurrentTime = DateTime.Now;
}
Making something write-only is usefulwhenever you're not supposed to read what you write.
For example, when drawing things onto the screen (this is precisely what the Desktop Window Manager does in Windows):
You can certainly draw to a screen, but you should never need to read back the data (let alone expect to get the same design as before).
Now, whether write-only properties are useful (as opposed to methods), I'm not sure how often they're used. I suppose you could imagine a situation with a "BackgroundColor" property, where writing to it sets the background color of the screen, but reading makes no sense (necessarily).
So I'm not sure about that part, but in general I just wanted to point out that there are use cases for situations in which you only write data, and never read it.
Although the .NET design guidelines recommend using a method ("SetMyWriteOnlyParameter") instead of a write-only property, I find write-only properties useful when creating linked objects from a serialised representation (from a database).
Our application represents oil-field production systems. We have the system as a whole (the "Model" object) and various Reservoir, Well, Node, Group etc objects.
The Model is created and read from database first - the other objects need to know which Model they belong to. However, the Model needs to know which lower object represents the Sales total. It makes sense for this information to be stored a Model property. If we do not want to have to do two reads of Model information, we need to be able to read the name of Sales object before its creation. Then, subsequently, we set the "SalesObject" variable to point to the actual object (so that, e.g., any change by the user of the name of this object does not cause problems)
We prefer to use a write-only property - 'SalesObjectName = "TopNode"' - rather than a method - 'SetSalesObjectName("TopNode") - because it seems to us that the latter suggests that the SalesObject exists.
This is a minor point, but enough to make us want to use a Write-Only property.
As far as I'm concerned, they don't. Every time I've used a write-only property as a quick hack I have later come to regret it. Usually I end up with a constructor or a full property.
Of course I'm trying to prove a negative, so maybe there is something I'm missing.
I can't stop thinking about this, either. I have a use case for a "write-only" property. I can't see good way out of it.
I want to construct a C# attribute that derives from AuthorizeAttribute for an ASP.NET MVC app. I have a service (say, IStore) that returns information that helps decide if the current user should be authorized. Constructor Injection won't work, becuase
public AllowedAttribute: AuthorizeAttribute
{
public AllowedAttribute(IStore store) {...}
private IStore Store { get; set; }
...
}
makes store a positional attribute parameter, but IStore is not a valid attribute parameter type, and the compiler won't build code that is annotated with it. I am forced to fall back on Property Setter Injection.
public AllowedAttribute: AuthorizeAttribute
{
[Inject] public IStore Store { private get; set; }
...
}
Along with all the other bad things about Property Setter instead of Constructor Injection, the service is a write-only property. Bad enough that I have to expose the setter to clients that shouldn't need to know about the implementation detail. It wouldn't do anybody any favors to let clients see the getter, too.
I think that the benefit of Dependency Injection trumps the guidelines against write-only properties for this scenario, unless I am missing something.
I just came across that situation when writing a program that reads data from a JSON database (Firebase). It uses Newtonsoft's Json.NET to populate the objects. The data are read-only, i.e., once loaded they won't change. Also, the objects are only deserialized and won't be serialized again. There may be better ways, but this solution just looks reasonable for me.
using Newtonsoft.Json;
// ...
public class SomeDatabaseClass
{
// JSON object contains a date-time field as string
[JsonProperty("expiration")]
public string ExpirationString
{
set
{
// Needs a custom parser to handle special date-time formats
Expiration = Resources.CustomParseDateTime(value);
}
}
// But this is what the program will effectively use.
// DateTime.MaxValue is just a default value
[JsonIgnore]
public DateTime Expiration { get; private set; } = DateTime.MaxValue;
// ...
}
No, I can' imagine any case where they can't be replaced, though there might people who consider them to be more readable.
Hypothetical case:
CommunicationDevice.Response = "Hello, World"
instead of
CommunicationDevice.SendResponse("Hello, World")
The major job would be to perform IO side-effects or validation.
Interestingly, VB .NET even got it's own keyword for this weird kind of property ;)
Public WriteOnly Property Foo() As Integer
Set(value As Integer)
' ... '
End Set
End Property
even though many "write-only" properties from outside actually have a private getter.
I recently worked on an application that handled passwords. (Note that I'm not claiming that the following is a good idea; I'm just describing what I did.)
I had a class, HashingPassword, which contained a password. The constructor took a password as an argument and stored it in a private attribute. Given one of these objects, you could either acquire a salted hash for the password, or check the password against a given salted hash. There was, of course, no way to retrieve the password from a HashingPassword object.
So then I had some other object, I don't remember what it was; let's pretend it was a password-protected banana. The Banana class had a set-only property called Password, which created a HashingPassword from the given value and stored it in a private attribute of Banana. Since the password attribute of HashingPassword was private, there was no way to write a getter for this property.
So why did I have a set-only property called Password instead of a method called SetPassword? Because it made sense. The effect was, in fact, to set the password of the Banana, and if I wanted to set the password of a Banana object, I would expect to do that by setting a property, not by calling a method.
Using a method called SetPassword wouldn't have had any major disadvantages. But I don't see any significant advantages, either.
I know this has been here for a long time, but I came across it and have a valid (imho) use-case:
When you post parameters to a webapi call from ajax, you can simply try to fill out the parameters class' properties and include validation or whatsoever.
public int MyFancyWepapiMethod([FromBody]CallParams p) {
return p.MyIntPropertyForAjax.HasValue ? p.MyIntPropertyForAjax.Value : 42;
}
public class CallParams
{
public int? MyIntPropertyForAjax;
public object TryMyIntPropertyForAjax
{
set
{
try { MyIntPropertyForAjax = Convert.ToInt32(value); }
catch { MyIntPropertyForAjax = null; }
}
}
}
On JavaScript side you can simply fill out the parameters including validation:
var callparameter = {
TryMyIntPropertyForAjax = 23
}
which is safe in this example, but if you handle userinput it might be not sure that you have a valid intvalue or something similar.

Encapsulation within class definitions

For example, do you use accessors and mutators within your method definitions or just access the data directly? Sometimes, all the time or when in Rome?
Always try to use accessors, even inside the class. The only time you would want to access state directly and not through the public interface is if for some reason you needed to bypass the validation or other logic contained in the accessor method.
Now if you find yourself in the situation where you do need to bypass that logic you ought to step back and ask yourself whether or not this need betrays a flaw in your design.
Edit: Read Automatic vs Explicit Properties by Eric Lippert in which he delves into this very issue and explains things very clearly. It is about C# specifically but the OOP theory is universal and solid.
Here is an excerpt:
If the reason that motivated the
change from automatically implemented
property to explicitly implemented
property was to change the semantics
of the property then you should
evaluate whether the desired semantics
when accessing the property from
within the class are identical to or
different from the desired semantics
when accessing the property from
outside the class.
If the result of that investigation is
“from within the class, the desired
semantics of accessing this property
are different from the desired
semantics of accessing the property
from the outside”, then your edit has
introduced a bug. You should fix the
bug. If they are the same, then your
edit has not introduced a bug; keep
the implementation the same.
In general, I prefer accessors/mutators. That way, I can change the internal implementation of a class, while the class functions in the same way to an external user (or preexisting code that I dont want to break).
The accessors are designed so that you can add property specific logic. Such as
int Degrees
{
set
{
_degrees = value % 360;
}
}
So, you would always want to access that field through the getter and setter, and that way you can always be certain that the value will never get greater than 360.
If, as Andrew mentioned, you need to skip the validation, then it's quite possible that there is a flaw in the design of the function, or in the design of the validation.
Accessors and Mutators are designed to ensure consistency of your data, so even within your class you should always strive to make sure that there's no possible way of injecting unvalidated data into those fields.
EDIT
See this question as well:
OO Design: Do you use public properties or private fields internally?
I don't tend to share with the outside world the 'innards' of my classes and so my internal needs for data (the private method stuff) tends to not do the same sort of stuff that my public interface does, typically.
It is pretty uncommon that I'll write an accessor/mutator that a private method will call, but I suspect I'm in the minority here. Maybe I should do more of this, but I don't tend to.
Anyway, that's my [patina covered] two cents.
I will often start with private auto properties, then refactor if necessary. I'll refactor to a property with a backing field, then replace the backing field with the "real" store, for instance Session or ViewState for an ASP.NET application.
From:
private int[] Property { get; set; }
to
private int[] _property;
private int[] Property
{
get { return _property; }
set { _property = value; }
}
to
private int[] _property;
private int[] Property
{
get
{
if (_property == null)
{
_property = new int[8];
}
return _property;
}
set { _property = value; }
}
to
private int[] Property
{
get
{
if (ViewState["PropertyKey"] == null)
{
ViewState["PropertyKey"] = new int[8];
}
return (int[]) ViewState["PropertyKey"];
}
set { ViewState["PropertyKey"] = value; }
}
Of course, I use ReSharper, so this takes less time to do than to post about.