Swift readonly external, readwrite internal property - objective-c

In Swift, what is the conventional way to define the common pattern where a property is to be externally readonly, but modifiable internally by the class (and subclasses) that own it.
In Objective-C, there are the following options:
Declare the property as readonly in the interface and use a class extension to access the property internally. This is message-based access, hence it works nicely with KVO, atomicity, etc.
Declare the property as readonly in the interface, but access the backing ivar internally. As the default access for an ivar is protected, this works nicely in a class hierarchy, where subclasses will also be able to modify the value, but the field is otherwise readonly.
In Java the convention is:
Declare a protected field, and implement a public, read-only getter (method).
What is the idiom for Swift?

Given a class property, you can specify a different access level by prefixing the property declaration with the access modifier followed by get or set between parenthesis. For example, a class property with a public getter and a private setter will be declared as:
private(set) public var readonlyProperty: Int
Suggested reading: Getters and Setters
Martin's considerations about accessibility level are still valid - i.e. there's no protected modifier, internal restricts access to the module only, private to the current file only, and public with no restrictions.
Swift 3 notes
2 new access modifiers, fileprivate and open have been added to the language, while private and public have been slightly modified:
open applies to class and class members only: it's used to allow a class to be subclassed or a member to be overridden outside of the module where they are defined. public instead makes the class or the member publicly accessible, but not inheritable or overridable
private now makes a member visible and accessible from the enclosing declaration only, whereas fileprivate to the entire file where it is contained
More details here.

As per #Antonio, we can use a single property to access as the readOnly property value publicly and readWrite privately. Below is my illustration:
class MyClass {
private(set) public var publicReadOnly: Int = 10
//as below, we can modify the value within same class which is private access
func increment() {
publicReadOnly += 1
}
func decrement() {
publicReadOnly -= 1
}
}
let object = MyClass()
print("Initial valule: \(object.publicReadOnly)")
//For below line we get the compile error saying : "Left side of mutating operator isn't mutable: 'publicReadOnly' setter is inaccessible"
//object.publicReadOnly += 1
object.increment()
print("After increment method call: \(object.publicReadOnly)")
object.decrement()
print("After decrement method call: \(object.publicReadOnly)")
And here is the output:
Initial valule: 10
After increment method call: 11
After decrement method call: 10

Related

Kotlin protected property can not be accessed in other module

Just when I thought I understood it, I got the following issue.
I have a base class in another module (called base here)
It looks like that:
open class BaseTest {
companion object {
lateinit var baseTest: BaseTest
}
protected open var someProperty: String? = "base"
}
I want to set that property and made it protected so my extended class in another module could access it.
class Extended: BaseTest() {
fun extendedCall() {
BaseTest().someProperty = "extended"
baseTest.someProperty = "extended"
}
}
However, neither the static one, not the direct property is accessable stating the following error:
Cannot access 'someProperty': it is protected in 'BaseTest'
But shouldn't that be accessable since Extended inherents from BaseTest()? I mean the definition of protected is "Declarations are only visible in its class and in its subclassess" so what have I missed? It even doesn't work in the same module so that's not the cause.
What am I missing?
BaseTest().someProperty = "extended"
Here you make a new BaseTest object by calling the constructor BaseTest() and you are not allowed to access protected properties of other BaseTest objects.
baseTest.someProperty = "extended"
the static BaseTest object is also another object and not the Extended object itself.
Being protected merely makes it possible to do
someProperty = "extended"
or the equivalent
this.someProperty = "extended"
That is, access the property of this object.
I believe the protected modifier doesn't work like that in Kotlin.
The documentation says:
The protected modifier is not available for top-level declarations.
But I agree it's quite confusing as written. It appears the documentation focuses more on the Outter/Inner class relationship via the this keyword.

In ASPNetCore 2.2, Startup.cs, the Configure property only has {get}, yet it is assigned a reference. Why is this? [duplicate]

I created an automated property:
public int Foo { get; }
This is getter only.
But when I build a constructor, I can change the value:
public MyClass(string name)
{
Foo = 5;
}
Why is it possible, even though this is get-only?
This is a new C# 6 feature, "Getter-only auto-properties", also known as "Auto-Property Initializers for Read-Only Properties" as discussed in this MSDN magazine article 'C# : The New and Improved C# 6.0' by Mark Michaelis and in the C# 6.0 draft Language Specification.
The read-only field's setter is only accessible in the constructor, in all other scenarios the field is still read only and behaves as before.
This is a convenience syntax to reduce the amount of code you need to type and to remove the need to explicitly declare a private module level variable to hold the value.
This feature was seen as important as, since the introduction of Auto-Implemented Properties in C#3, mutable properties (those with a getter and setter) had become quicker to write than immutable ones (those with only a getter), meaning people were being tempted to use mutable properties to avoid having to type the code for a backing field usually required for read-only properties. There is more discussion of Auto-Implemented properties in the relevant section of the Microsoft C# Programming Guide.
This blog post, '#1,207 – C# 6.0 – Auto-Property Initializers for Read-Only Properties' by Sean Sexton Has a good explanation and example as follows:
Prior to C# 6.0, if you wanted a read-only (immutable) property, you’d
typically use a read-only backing field that is initialized in the
constructor, as shown below.
public class Dog
{
public string Name { get; set; }
// DogCreationTime is immutable
private readonly DateTime creTime;
public DateTime DogCreationTime
{
get { return creTime; }
}
public Dog(string name)
{
Name = name;
creTime = DateTime.Now;
}
}
In C# 6.0, you can use auto-implemented properties to implement a
read-only property. You do this by using an auto-property
initializer. The result is much cleaner than the above example, where
we had to explicitly declare a backing field.
public class Dog
{
public string Name { get; set; }
// DogCreationTime is immutable
public DateTime DogCreationTime { get; } = DateTime.Now;
public Dog(string name)
{
Name = name;
}
}
More details can also be found in the dotnet Roslyn repo on GitHub:
Auto-properties can now be declared without a setter.
The backing field of a getter-only auto-property is implicitly
declared as readonly (though this matters only for reflection
purposes). It can be initialized through an initializer on the
property as in the example above. Also, a getter-only property can be
assigned to in the declaring type’s constructor body, which causes the
value to be assigned directly to the underlying field:
This is about expressing types more concisely, but note that it also
removes an important difference in the language between mutable and
immutable types: auto-properties were a shorthand available only if
you were willing to make your class mutable, and so the temptation to
default to that was great. Now, with getter-only auto-properties, the
playing field has been leveled between mutable and immutable.
and in the C# 6.0 draft Language Specification (NB: The language specification is final as far as Microsoft are concerned, but it is yet to be approved as a EMCA/ISO standard, hence the 'draft'):
Automatically implemented properties
An automatically implemented property (or auto-property for short), is
a non-abstract non-extern property with semicolon-only accessor
bodies. Auto-properties must have a get accessor and can optionally
have a set accessor.
When a property is specified as an automatically implemented property,
a hidden backing field is automatically available for the property,
and the accessors are implemented to read from and write to that
backing field. If the auto-property has no set accessor, the backing
field is considered readonly (Readonly fields). Just like a readonly
field, a getter-only auto-property can also be assigned to in the body
of a constructor of the enclosing class. Such an assignment assigns
directly to the readonly backing field of the property.
An auto-property may optionally have a property_initializer, which is
applied directly to the backing field as a variable_initializer
(Variable initializers).
This is a new feature in C#6 that allows you to create read-only properties and initialize their values from the constructor (or inline when you declare them).
If you try to change the value of this property outside the constructor, it would give you a compile error.
It is read-only in the sense that once you initialize its value (inline or inside the constructor), you cannot change its value.
If it were not possible to initialize the read-only property from the constructor (or an auto-property initializer), then it would be useless, since it would always return the default value for its type (0 for numerics, null for reference types). The same semantics applied to readonly fields in all C# versions.
To define a true getter-only property (that cannot be initialized from the constructor), you need to specify what it returns as part of the definition:
public int Foo { get { return 5; } }
Or, more concisely in C# 6:
public int Foo => 5;
“readonly automatically implemented properties”
First of all I want to clarify that the property like
public string FirstName { get; }
Is known as “readonly automatically implemented properties”
To verify this you can run & check the above code with Visual Studio. If you change the language version from C#6.0 to C#5.0 then compiler will throw the following exception
Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater.
to change C# language version visit here
Now I am coming to your second question
“This is getter only. But when I build a constructor, I can change the value”
Microsoft introduces the “readonly automatically implemented properties” on the logic of read only. As we know that the keyword “readonly” is available from C#1.0. we use “readonly” keyword as modifier on a field and that field can be assigned in 2 ways either at the time of declaration or in a constructor in the same class.
In the same way value of “readonly automatically implemented properties” can be assigned in 2 ways
Way1 (at the time of declaration):
public string FirstName { get; } = "Banketeshvar";
Way2 (in a constructor in the same class)
Person()
{
FirstName = "Banketeshvar";
}
Purely ReadOnly Property
If you are looking for purely Readonly property then go for this
public string FullName => "Manish Sharma";
now you cannot assign value of “FullName” propery from constructor.
If you try to do that it will throw the following exceptions
“Property or indexer 'Person.FullName' cannot be assigned to -- it is read only”
Auto property feature was added to the language during C# 3.0 release. It allows you to define a property without any backing field, however you still need to use constructor to initialize these auto properties to non-default value. C# 6.0 introduces a new feature called auto property initializer which allows you to initialize these properties without a constructor like Below:
Previously, a constructor is required if you want to create objects
using an auto-property and initialize an auto-property to a
non-default value like below:
public class MyClass
{
public int Foo { get; }
public Foo(int foo)
{
Foo = foo;
}
}
Now in C# 6.0, the ability to use an initializer with the auto-property
means no explicit constructor code is required.
public string Foo { get; } = "SomeString";
public List<string> Genres { get; } = new List<string> { "Comedy", "Drama" };
You can find more information on this here
A variable declared readonly can be written within a constructor, but in languages which honor the attribute, cannot be modified after the constructor returns. That qualifier was provided as a language feature because it is often necessary for fields whose values will vary based upon constructor parameters (meaning they can't be initialized before the constructor starts) but won't have to change after constructors return, but it was only usable for variables exposed as fields. The semantics of readonly-qualified fields would in many cases have been perfect for public members except that it's often better for classes to expose members--even immutable ones--as properties rather than fields.
Just as read-write auto-properties exist to allow classes to expose mutable properties as easily as ordinary fields, read-only auto-properties exist to allow classes to expose immutable properties as easily as readonly-qualified fields. Just as readonly-qualified fields can be written in a constructor, so too with get-only properties.

Overriding the property and renewing the property?

On my sub class if I override the property, we call it property XYZ is overriding the property from the base class. What do you call if property is getting renewed by using new keyword? Renewed?
This using of the new keyword as modifier is called member hiding.
From MSDN Documentation:
When used as a declaration modifier, the new keyword explicitly hides a member that is inherited from a base class. When you hide an inherited member, the derived version of the member replaces the base class version. Although you can hide members without using the new modifier, you get a compiler warning. If you use new to explicitly hide a member, it suppresses this warning.
To hide an inherited member, declare it in the derived class by using the same member name, and modify it with the new keyword.
public class BaseC
{
public int x;
public void Invoke() { }
}
public class DerivedC : BaseC
{
new public void Invoke() { }
}
For more information when to use override and when to use new keyword modifier you can read in MSDN too.

If an interface defines a ReadOnly Property, how can an implementer provide the Setter to this property?

Is there a way for implementers of an interface where a ReadOnly property is defined to make it a complete Read/Write Property ?
Imagine I define an interface to provide a ReadOnly Property (i.e., just a getter for a given value) :
Interface SomeInterface
'the interface only say that implementers must provide a value for reading
ReadOnly Property PublicProperty As String
End Interface
This means implementers must commit to providing a value. But I would like a given implementer to also allow setting that value. In my head, this would mean providing the Property's setter as part of the implementation, doing something like this :
Public Property PublicProperty As String Implements SomeInterface.PublicProperty
Get
Return _myProperty
End Get
Set(ByVal value As String)
_myProperty = value
End Set
End Property
but this will not compile as, for the VB compiler, the implementer no longer implements the interface (because it is no longer ReadOnly).
Conceptually, this should work, because, in the end, it just means Implement the getter from the Interface, and add a setter method. For "normal methods", this would be no problem.
Is there some way of doing it, without resorting to "interface hiding" or "home-made" SetProperty() method, and style having the Property behave like a Read/Write property in the implementations ?
Thanks !
--UPDATE--
(I have moved this question to a separate Question)
My question is really : "why can't this be done in VB.NET", when the following is valid in C#.NET?" :
interface IPublicProperty
{
string PublicProperty { get; }
}
with implementation :
public class Implementer:IPublicProperty
{
private string _publicProperty;
public string PublicProperty
{
get
{
return _publicProperty;
}
set
{
_publicProperty = value;
}
}
}
Now supported in Visual Studio 2015.
What's New for Visual Basic
Readonly Interface Properties
You can implement readonly interface properties using a readwrite property. The interface guarantees minimum functionality, and it does not stop an implementing class from allowing the property to be set.
In the end, I ended up with a solution that matches my goal :
users that access via the Interface see at least a getter
users that access the implementation can Read and Write.
I did this "shadowing" the implemented property like this :
'users who access through interface see only the Read accessor
Public ReadOnly Property PublicProperty_SomeInterface As String Implements SomeInterface.PublicProperty
Get
Return _myProperty
End Get
End Property
'users who work with the implementation have Read/Write access
Public Property PublicProperty_SomeInterface As String
Get
Return _myProperty
End Get
Set(ByVal value As String)
_myProperty = value
End Set
End Property
Then, depending on how you use it, you can do :
Dim implementorAsInterface As SomeInterface = New InterfaceImplementor()
logger.Log(implementor.PublicProperty) 'read access is always ok
implementor.PublicProperty = "toto" 'compile error : readOnly access
Dim implementor As InterfaceImplementor = New InterfaceImplementor()
implementor.PublicProperty = "toto" 'write access
There is nothing at a CLI level which prevents this type of implementation and as you've demonstrated it's already supported by C#. The VB.Net language just doesn't support this style of implementation.
Knowing why though is a bit tough since the decision is almost 10 years removed at this point. Very likely it was just an over site at the time interface implementation was designed.
You can't do it as the interface requires that you implement a ReadOnly Property.
Properties don't allow overloading so there is no way to implement a non-ReadOnly and also a ReadOnly.
I would suggest you either implement a Custom Setter or drop the ReadOnly from the Interface.
Without details of why you want to do this it is hard to suggest the best solution
In Visual Basic, when you implement a method or property from an interface, you can change its name and its visibility. You can leverage that capability to handle the case you are asking about. Prior to Visual Studio 2015, I often did this:
Interface:
Public Interface SomeInterface
ReadOnly Property SomeProperty As String
End Interface
Implementing Class:
Public Class SomeClass
Implements SomeInterface
Public Property SomeProperty As String
Private ReadOnly Property SomeProperty_ReadOnly As String Implements SomeInterface.SomeProperty
Get
Return Me.SomeProperty
End Get
End Property
End Class
The result is that SomeProperty is read-only when accessed through SomeInterface, but read-write when accessed through SomeClass:
Dim c As New SomeClass
c.SomeProperty = "hello" 'Write via class OK
Dim s1 = c.SomeProperty 'Read via class OK
Dim i As SomeInterface = c
Dim s2 = i.SomeProperty 'Read via interface OK
i.SomeProperty = "greetings" 'Syntax Error, interface property is read-only

What is the use of making constructor private in a class?

Why should we make the constructor private in class? As we always need the constructor to be public.
Some reasons where you may need private constructor:
The constructor can only be accessed from static factory method inside the class itself. Singleton can also belong to this category.
A utility class, that only contains static methods.
By providing a private constructor you prevent class instances from being created in any place other than this very class. There are several use cases for providing such constructor.
A. Your class instances are created in a static method. The static method is then declared as public.
class MyClass()
{
private:
MyClass() { }
public:
static MyClass * CreateInstance() { return new MyClass(); }
};
B. Your class is a singleton. This means, not more than one instance of your class exists in the program.
class MyClass()
{
private:
MyClass() { }
public:
MyClass & Instance()
{
static MyClass * aGlobalInst = new MyClass();
return *aGlobalInst;
}
};
C. (Only applies to the upcoming C++0x standard) You have several constructors. Some of them are declared public, others private. For reducing code size, public constructors 'call' private constructors which in turn do all the work. Your public constructors are thus called delegating constructors:
class MyClass
{
public:
MyClass() : MyClass(2010, 1, 1) { }
private:
MyClass(int theYear, int theMonth, int theDay) { /* do real work */ }
};
D. You want to limit object copying (for example, because of using a shared resource):
class MyClass
{
SharedResource * myResource;
private:
MyClass(const MyClass & theOriginal) { }
};
E. Your class is a utility class. That means, it only contains static members. In this case, no object instance must ever be created in the program.
To leave a "back door" that allows another friend class/function to construct an object in a way forbidden to the user. An example that comes to mind would be a container constructing an iterator (C++):
Iterator Container::begin() { return Iterator(this->beginPtr_); }
// Iterator(pointer_type p) constructor is private,
// and Container is a friend of Iterator.
Everyone is stuck on the Singleton thing, wow.
Other things:
Stop people from creating your class on the stack; make private constructors and only hand back pointers via a factory method.
Preventing creating copys of the class (private copy constructor)
This can be very useful for a constructor that contains common code; private constructors can be called by other constructors, using the 'this(...);' notation. By making the common initialization code in a private (or protected) constructor, you are also making explicitly clear that it is called only during construction, which is not so if it were simply a method:
public class Point {
public Point() {
this(0,0); // call common constructor
}
private Point(int x,int y) {
m_x = x; m_y = y;
}
};
There are some instances where you might not want to use a public constructor; for example if you want a singleton class.
If you are writing an assembly used by 3rd parties there could be a number of internal classes that you only want created by your assembly and not to be instantiated by users of your assembly.
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).
We can also have private constructor,
to enfore the object's creation by a specific class
only(For security reasons).
One way to do it is through having a friend class.
C++ example:
class ClientClass;
class SecureClass
{
private:
SecureClass(); // Constructor is private.
friend class ClientClass; // All methods in
//ClientClass have access to private
// & protected methods of SecureClass.
};
class ClientClass
{
public:
ClientClass();
SecureClass* CreateSecureClass()
{
return (new SecureClass()); // we can access
// constructor of
// SecureClass as
// ClientClass is friend
// of SecureClass.
}
};
Note: Note: Only ClientClass (since it is friend of SecureClass)
can call SecureClass's Constructor.
You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.
Edit: I'm standing by that, no matter how many downvotes you throw at this.
You're cutting off the potential for future development on the code. If other users or programmers are really determined to extend the class, then they'll just change the constructor to protected in source or bytecode. You will have accomplished nothing besides to make their life a little harder. Include a warning in your constructor's comments, and leave it at that.
If it's a utility class, the simpler, more correct, and more elegant solution is to mark the whole class "static final" to prevent extension. It doesn't do any good to just mark the constructor private; a really determined user may always use reflection to obtain the constructor.
Valid uses:
One good use of a protected
constructor is to force use of static
factory methods, which allow you to
limit instantiation or pool & reuse
expensive resources (DB connections,
native resources).
Singletons (usually not good practice, but sometimes necessary)
when you do not want users to create instances of this class or create class that inherits this class, like the java.lang.math, all the function in this package is static, all the functions can be called without creating an instance of math, so the constructor is announce as static.
If it's private, then you can't call it ==> you can't instantiate the class. Useful in some cases, like a singleton.
There's a discussion and some more examples here.
I saw a question from you addressing the same issue.
Simply if you don't want to allow the others to create instances, then keep the constuctor within a limited scope. The practical application (An example) is the singleton pattern.
Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class.
For instance in singleton implementation we have to make the constructor private
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i==0)
{
instance =new singletonClass;
i=1;
}
return instance;
}
void test()
{
cout<<"successfully created instance";
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//////return instance!!!
temp->test();
}
Again if you want to limit the object creation upto 10 then use the following
#include<iostream>
using namespace std;
class singletonClass
{
static int i;
static singletonClass* instance;
public:
static singletonClass* createInstance()
{
if(i<10)
{
instance =new singletonClass;
i++;
cout<<"created";
}
return instance;
}
};
int singletonClass::i=0;
singletonClass* singletonClass::instance=NULL;
int main()
{
singletonClass *temp=singletonClass::createInstance();//return an instance
singletonClass *temp1=singletonClass::createInstance();///return another instance
}
Thanks
You can have more than one constructor. C++ provides a default constructor and a default copy constructor if you don't provide one explicitly. Suppose you have a class that can only be constructed using some parameterized constructor. Maybe it initialized variables. If a user then uses this class without that constructor, they can cause no end of problems. A good general rule: If the default implementation is not valid, make both the default and copy constructor private and don't provide an implementation:
class C
{
public:
C(int x);
private:
C();
C(const C &);
};
Use the compiler to prevent users from using the object with the default constructors that are not valid.
Quoting from Effective Java, you can have a class with private constructor to have a utility class that defines constants (as static final fields).
(EDIT: As per the comment this is something which might be applicable only with Java, I'm unaware if this construct is applicable/needed in other OO languages (say C++))
An example as below:
public class Constants {
private Contants():
public static final int ADDRESS_UNIT = 32;
...
}
EDIT_1:
Again, below explanation is applicable in Java : (and referring from the book, Effective Java)
An instantiation of utility class like the one below ,though not harmful, doesn't serve
any purpose since they are not designed to be instantiated.
For example, say there is no private Constructor for class Constants.
A code chunk like below is valid but doesn't better convey intention of
the user of Constants class
unit = (this.length)/new Constants().ADDRESS_UNIT;
in contrast with code like
unit = (this.length)/Constants.ADDRESS_UNIT;
Also I think a private constructor conveys the intention of the designer of the Constants
(say) class better.
Java provides a default parameterless public constructor if no constructor
is provided, and if your intention is to prevent instantiation then a private constructor is
needed.
One cannot mark a top level class static and even a final class can be instantiated.
Utility classes could have private constructors. Users of the classes should not be able to instantiate these classes:
public final class UtilityClass {
private UtilityClass() {}
public static utilityMethod1() {
...
}
}
You may want to prevent a class to be instantiated freely. See the singleton design pattern as an example. In order to guarantee the uniqueness, you can't let anyone create an instance of it :-)
One of the important use is in SingleTon class
class Person
{
private Person()
{
//Its private, Hense cannot be Instantiated
}
public static Person GetInstance()
{
//return new instance of Person
// In here I will be able to access private constructor
}
};
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
It's really one obvious reason: you want to build an object, but it's not practical to do it (in term of interface) within the constructor.
The Factory example is quite obvious, let me demonstrate the Named Constructor idiom.
Say I have a class Complex which can represent a complex number.
class Complex { public: Complex(double,double); .... };
The question is: does the constructor expects the real and imaginary parts, or does it expects the norm and angle (polar coordinates) ?
I can change the interface to make it easier:
class Complex
{
public:
static Complex Regular(double, double = 0.0f);
static Complex Polar(double, double = 0.0f);
private:
Complex(double, double);
}; // class Complex
This is called the Named Constructor idiom: the class can only be built from scratch by explicitly stating which constructor we wish to use.
It's a special case of many construction methods. The Design Patterns provide a good number of ways to build object: Builder, Factory, Abstract Factory, ... and a private constructor will ensure that the user is properly constrained.
In addition to the better-known uses…
To implement the Method Object pattern, which I’d summarize as:
“Private constructor, public static method”
“Object for implementation, function for interface”
If you want to implement a function using an object, and the object is not useful outside of doing a one-off computation (by a method call), then you have a Throwaway Object. You can encapsulate the object creation and method call in a static method, preventing this common anti-pattern:
z = new A(x,y).call();
…replacing it with a (namespaced) function call:
z = A.f(x,y);
The caller never needs to know or care that you’re using an object internally, yielding a cleaner interface, and preventing garbage from the object hanging around or incorrect use of the object.
For example, if you want to break up a computation across methods foo, bar, and zork, for example to share state without having to pass many values in and out of functions, you could implement it as follows:
class A {
public static Z f(x, y) {
A a = new A(x, y);
a.foo();
a.bar();
return a.zork();
}
private A(X x, Y y) { /* ... */ };
}
This Method Object pattern is given in Smalltalk Best Practice Patterns, Kent Beck, pages 34–37, where it is the last step of a refactoring pattern, ending:
Replace the original method with one that creates an instance of the new class, constructed with the parameters and receiver of the original method, and invokes “compute”.
This differs significantly from the other examples here: the class is instantiable (unlike a utility class), but the instances are private (unlike factory methods, including singletons etc.), and can live on the stack, since they never escape.
This pattern is very useful in bottoms-up OOP, where objects are used to simplify low-level implementation, but are not necessarily exposed externally, and contrasts with the top-down OOP that is often presented and begins with high-level interfaces.
Sometimes is useful if you want to control how and when (and how many) instances of an object are created.
Among others, used in patterns:
Singleton pattern
Builder pattern
On use of private constructors could also be to increase readability/maintainability in the face of domain-driven design.
From "Microsoft .NET - Architecing Applications for the Enterprise, 2nd Edition":
var request = new OrderRequest(1234);
Quote, "There are two problems here. First, when looking at the code, one can hardly guess what’s going
on. An instance of OrderRequest is being created, but why and using which data? What’s 1234? This
leads to the second problem: you are violating the ubiquitous language of the bounded context. The
language probably says something like this: a customer can issue an order request and is allowed to
specify a purchase ID. If that’s the case, here’s a better way to get a new OrderRequest instance:"
var request = OrderRequest.CreateForCustomer(1234);
where
private OrderRequest() { ... }
public OrderRequest CreateForCustomer (int customerId)
{
var request = new OrderRequest();
...
return request;
}
I'm not advocating this for every single class, but for the above DDD scenario I think it makes perfect sense to prevent a direct creation of a new object.
If you create a private constructor you need to create the object inside the class
enter code here#include<iostream>
//factory method
using namespace std;
class Test
{
private:
Test(){
cout<<"Object created"<<endl;
}
public:
static Test* m1(){
Test *t = new Test();
return t;
}
void m2(){
cout<<"m2-Test"<<endl;
}
};
int main(){
Test *t = Test::m1();
t->m2();
return 0;
}