Interface behavior is dfferent in VB.Net - vb.net

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class

The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.

From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...

There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.

When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.

The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

Related

Translating C# functions into vb.net

I need help converting some of this code. Mainly:
private static void SetProvider(ServiceCollection collection)
=> _service = collection.BuildServiceProvider();
and the line below it. This is being used for a discord bot using Discord.Net with the music library Victoria. Can someone also tell me what this actually is? Just a side question. this uses static classes and there's not anything called static on VB.Net so what would be the best call here? I've seen some other posts from here debating whether to use NonInheritable Class or a Module. What are the differences and when it is better to use either one?
It depends on what you want exactly. VB.NET does not provide static classes. Instead, it offers modules, but those are not completely equal to static classes.
The module version would be:
Public Module ServiceManager
Private _service As IServiceProvider
Public Sub SetProvider(collection As ServiceCollection)
_service = collection.BuildServiceProvider()
End Sub
Public Function GetService(Of T As New)() As T
Return _service.GetRequiredService(Of T)()
End Function
End Module
The class version would be:
Public NotInheritable Class ServiceManager
Private Sub New()
End Sub
Private Shared _service As IServiceProvider
Public Shared Sub SetProvider(collection As ServiceCollection)
_service = collection.BuildServiceProvider()
End Sub
Public Shared Function GetService(Of T As New)() As T
Return _service.GetRequiredService(Of T)()
End Function
End Class
When using the class implementation, you have to be careful to mark all members as Shared. Additionally, you can consider the following:
Declare the class as NotInheritable, since neither VB.NET modules nor C# static classes can be inherited from. (The corresponding C# keyword is sealed, by the way, but it will never be used in this context, since C# does support static classes.)
Create one private (default) constructor for the class. That will make sure that you cannot instantiate the class. VB.NET modules nor C# static classes cannot be instantiated either.
Using VB.NET modules is somewhat more straightforward, but keep in mind that VB.NET modules have a little quirk. When accessing a member of a module, you are typically not required to prefix it with the module name. Suppose you have some kind of service class called MyService and you have implemented your ServiceManager as a module. Then you do not need to call it like:
Dim svc As MyService = ServiceManager.GetService(Of MyService)()
Instead, you could just call it like:
Dim svc As MyService = GetService(Of MyService)()`.
When using the former method, Visual Studio actually suggests to simplify the name and change it to the latter method. But when you afterwards add another imported namespace that also happens to contain a module that has a GetService(Of T)() method, you will get an error indicating that GetService is ambiguous, in which case you would be forced to prefix it with the module name (like in the former method).
I personally find this checking behavior in Visual Studio regarding VB.NET module member usage to be rather annoying and confusing. I prefer prefixing calls with the module name (for the sake of writing self-documenting code and avoiding ambiguity as mentioned), but I do not want to disable the "simplify name" hint/suggestion in Visual Studio. So I personally prefer a class implementation instead of a module implementation when implementing something in VB.NET that mimics a C# static class.
Or even better: I would avoid a static class design and switch to a "regular" class design when possible. Using class instances has several advantages, like using composition (which is also an important technique used in many popular behavioral design patterns), simplified mocking/unittesting, and less side effects in general.
The equivalent VB.NET is:
Private Shared Sub SetProvider(collection As ServiceCollection)
_service = collection.BuildServiceProvider()
End Sub
C# expression bodies are just a single expression body method, MS Docs e.g. the following are equivalent:
void Greet()
{
Console.WriteLine("Hello World");
}
// Same as above
void Greet() => Console.WriteLine("Hello World");

VB.NET access level of interface declaration not matching access level of implementation [duplicate]

Interface behaves differently in Vb.Net. Below is a sample code snippet where IStudent interface has a method SayHello which is implemented by a class Student. The Access modifier for SayHello should be Public by default. By changing Access modifier to Private is not breaking the existing code and still i can access this private method using below code
Dim stdnt As IStudent = New Student
stdnt.SayHello()
Access modifier determines the scope of the members in a class, more over private members are accessible only from the class which exists. But here the theory of Access Modifier, Encapsulation are broken.
Why .net has designed in this way?
Is the concept of Access modifier and encapsulation are really broken?
How .net framework internally handle this situation?
Thanks in advance
Module Module1
Sub Main()
Dim stdnt As IStudent = New Student
stdnt.Name = "vimal"
stdnt.SayHello()
End Sub
End Module
Public Interface IStudent
Property Name As String
Sub SayHello()
End Interface
Public Class Student
Implements IStudent
Private Property Name As String Implements IStudent.Name
Private Sub SayHello() Implements IStudent.SayHello
Console.WriteLine("Say Hello!")
End Sub
End Class
The original poster submitted this question to me via TheBugGuys#Coverity.com; my answer is here:
https://communities.coverity.com/blogs/development-testing-blog/2013/10/09/oct-9-posting-interface-behaves-differently-in-visual-basic
To briefly summarize:
Why was .NET designed in this way?
That question is impossibly vague.
Is encapsulation broken by explicit implementation in C# and VB?
No. The privacy of the method restricts the accessibility domain of the methods name, not who can call the method. If the author of the class chooses to make a private method callable by some mechanism other than looking it up by name, that is their choice. A third party cannot make the choice for them except via techniques such as private reflection, which do break encapsulation.
How is this feature implemented in .NET?
There is a special metadata table for explicit interface implementations. The CLR consults it first when attempting to figure out which class (or struct) method is associated with which interface method.
From MSDN:
You can use a private member to implement an interface member. When a private member implements a member of an interface, that member becomes available by way of the interface even though it is not available directly on object variables for the class.
In C#, this behaviour is achieved by implementing the interface explicitly, like this:
public interface IStudent {
string Name { get; set; }
void SayHello();
}
public class Student : IStudent {
string IStudent.Name { get; set; }
void IStudent.SayHello() {
Console.WriteLine("Say Hello!");
}
}
So, if you were to omit the IStudent. in front of the method names, it would break. I see that in the VB syntax the interface name is included. I don't know whether this has any implications altough. But interface members aren't private, since the interface isn't. They're kinda public...
There is no fundamental difference between C# and VB.NET, they just chose different ways to solve ambiguity. Best demonstrated with a C# snippet:
interface ICowboy {
void Draw();
}
interface IPainter {
void Draw();
}
class CowboyPainter : ICowboy, IPainter {
void ICowboy.Draw() { useGun(); }
void IPainter.Draw() { useBrush(); }
// etc...
}
VB.NET just chose consistent interface implementation syntax so the programmer doesn't have to weigh the differences between implicit and explicit implementation syntax. Simply always explicit in VB.NET.
Only the accessibility of the interface method matters. Always public.
When your variable stdnt is declared as IStudent, the interface methods and properties are then made Public, so the derived class' (Student) implementation is executed. If, on the other hand, if stdnt was declared as Student, the private members (Name and SayHello) would not be implemented, and an error would be thrown.
I'm guessing that the Interface members stubs (Name & SayHello) are by default Public, and the access modifier definitions of the derived class' implementation are ignored.
IMHO.
The exact equivalent in C# is the following - the method available to objects of the interface type and the private method available otherwise:
void IStudent.SayHello()
{
this.SayHello();
}
private void SayHello()
{
Console.WriteLine("Say Hello!");
}

In Object oriented programming when do we need abstraction?

I read many posts about the "Interface" and "Abstract Class"
Basically, we use "Abstract Class" when we talking about the characteristic of the Object.
And we use "Interface" when we taling about what the object capable can do.
But it still confuse so I make up an example for myself to practice.
so now I thinking of a Object 'Cargo;
public abstract class cargo {
protected int id;
public abstract int getWidth(int width);
public abstract int setWidth(int width);
public abstract int setHeight(int h);
public abstract int getHeight(int h);
public abstract int setDepth(int d);
public abstract int getDepth(int d);
public abstract int volume(int w,int h,int d);
public int getId(){
return this.id;
}
public abstract int setId();
public abstract void setBrand();
public abstract void getBrand( );
.....so on , still have a lot of characteristic of a cargo
}
//in the other class
public class usaCargo extends cargo{
....
private
}
So here is few Question about my design.
1.So in the real programming project world, are we actually doing like above? for me i think it's ok design, we meet the basic characteristic of cargo.
if we setup "private id" , then we actually can't use "id" this variable in any subclass because it's private, so is that mean every variable we defined in abstract class must be either public/ protected?
can someone give some suitable example so my cargo can implement some interface?
public interface registration{
public void lastWarrantyCheck();
}
But seems not suitable here...
we dont usually define variable inside interface, do we ??
I try to gain more sense on OOP . Forgive my long questions.
You would define variables in the Abstract class so that methods defined in the abstract class have variables to use. The scope of those variables depend on how you want concrete classes to access those variables:
private should be used when you want to force a concrete class to go through a getter or setter defined in the abstract class.
protected should be used when you want to give the concrete class direct access to the variable.
public should be used when you want the variable to be accessible by any class.
A reasonable interface that a Cargo object might implement could be Shippable as in how to move the cargo from a source to a destination. Some cargo may be shipped via freight train, some might be shippable by airplane, etc. It is up to the concrete class to implement Shippable and define just how that type of cargo would be shipped.
public interface Shippable {
public void ship();
}
Lastly a variable defined in an interface must be public static and final meaning it would be a constant variable.
Hope this clears it up for you!
Abstract classes can contain implementation, so they can have private variables and methods. Interfaces on the other hand cannot.
You can find some examples on how to implement interfaces here. However, I included how you would implement your registration example below.
public class Cargo implements Registration{
public void lastWarrantyCheck(){
System.out.println("Last warranty check");
}
}
Interface variables are possible, but they should only include constant declarations (variable declarations that are declared to be both static and final). More information about this can be found here.
Variables in an abstract class may be declared as protected, and they will only be available within it and any extending classes. Private variables are never accessible inside extending classes.
Interfaces provide a list of functions that are required by the classes that implement them. For example, you might use an interface hasWarranty to define all the functions that an object would need to handle warranty-related activities.
public interface hasWarranty {
public void lastWarrantyCheck();
public void checkWarranty();
}
Then, any objects that need to perform warranty-related activities should implement that interface:
// Disclaimer: been away from Java for a long time, so please interpret as pseudo-code.
// Will compile
public class Car implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
public void checkWarranty() {
... need to have this exact function or program won't compile ...
}
}
// Missing one of the required functions defined in hasWarranty
public class Bus implements hasWarranty {
public void lastWarrantyCheck() {
... need to have this exact function or program won't compile ...
}
}
Only constants, really, as variables declared in an interface are immutable and are shared by all objects that implement that interface. They are implicitly "static final".

Why in interface why not in abstract class

I know that the access specifier visibility of the overridden method/property must be the same or above as that of the base method/property and I also know that the visibility of members of interfaces is public by default. So how and why can the visibility of the members be private when we implement the interface explicitly in a class though those private methods can be accessed by casting the class object to the implemented interface?
public interface IRocker
{
string RockOff(string str);
}
public abstract class AmAbstract
{
public abstract string SomeMethod(string str);
}
class Program : AmAbstract, IRocker
{
static void Main(string[] args)
{
new Hello().RockU();
Console.ReadKey();
}
string IRocker.RockOff(string str)
{
return str;
}
public override string SomeMethod(string str)
{
return str;
}
}
public class Hello
{
public void RockU()
{
Console.WriteLine(((IRocker)(new Program())).RockOff("Damn"));
Console.WriteLine(((AmAbstract)(new Program())).SomeMethod("lalalalala"));
}
}
'Console.WriteLine(((IRocker)(new Program())).RockOff("Damn"));' statement shows us ultimately accessing a private method of the class 'Program'. My question is why we can't hide the visibility of an abstract method as we can with an interface method? And why we are able to access private method through interface? Any help will be highly appreciated.
You are using explicit interface implementation when implementing IRocker.RockOff(). There are separate rules for those in C#, and in fact these are kind of private and public at the same time.
A quote from paragraph 13.4.1 of the C# 4.0 specification:
Explicit interface member implementations have different accessibility characteristics than other members. Because explicit interface member implementations are never accessible through their fully qualified name in a method invocation or a property access, they are in a sense private. However, since they can be accessed through an interface instance, they are in a sense also public.
Explicit interface member implementations serve two primary purposes:
Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.
Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.
There are no such exceptions for abstract classes, so just the regular modifier rules apply.

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;
}