Michael Johnson
Michael Johnson

Reputation: 33

Private class data design pattern is silly?

I'm reading this page

I am confused as to what is wrong with the first example. Why cannot he just add readonly to the declaration of the private fields?

Upvotes: 3

Views: 1373

Answers (2)

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

The keyword readonly (or its equivalent) is provided in some languages (for example, C# and VB.NET) but not others.

C++ is an example of an object-oriented language that does not have a keyword stipulating "This can be set at any part of a constructor function, but nowhere else".

Object oriented design patterns are meant to be language neutral: applying to all object-oriented languages. It follows from this that some languages might have extra features which make a particular pattern obsolete.

In this instance, the presentation of the pattern appears extra silly because the pattern is introduced, then the example is provided in C# which doesn't need it.

Upvotes: 9

cdhowie
cdhowie

Reputation: 169018

He very well could use readonly. It sounds like he doesn't understand what readonly does. From MSDN:

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

You can set readonly fields in a constructor. In fact, you would have to -- how else are those fields going to have any meaningful value?

Upvotes: 0

Related Questions