Prevent direct call to New()

BlitzMax Forums/BlitzMax Beginners Area/Prevent direct call to New()

SculptureOfSoul(Posted 2006) [#1]
Is there any easy and elegant way to prevent a direct call to new() for a given type?

The only way I can think of is to do something like this




Dreamora(Posted 2006) [#2]
That does actually not prevent the call of new.
it only blocks the default setup of it.

What you could do is add a "setup variable" that will prevent any usage of the object if it is not set and that is only set through the creation function.

But actually I don't see the reason for trying to block the call of new. if a user does that he will just need to be aware that the default setup is not as it needs to be and thus it can potentially break the app.


SculptureOfSoul(Posted 2006) [#3]
Well, I guess I didn't mean that I need to actually prevent new() from being called - just that I want the call to fail if called directly.

As to the reasoning behind it? Eh, just curious if it's possible to emulate a private constructor.


Koriolis(Posted 2006) [#4]
There is only one solution I can think of using the current state of BlitzMax, and it will only prevent the call from outside the current module :
Type TestType Abstract
	...
	Function Create:TestType()
		Local t:TestType = New TestTypeImpl
		...                
		Return t
	EndFunction
EndType
Private
Type TestTypeImpl Extends TestType
	Method New()
		...
	EndMethod    
End Type



Dreamora(Posted 2006) [#5]
Sculpture: new will never fail. The new command, before the method is even called, already has created the object and knows the reference. All new does is fill the object with default data.

So currently there are two ways:

Do creation functions that actually create the object basing on some input.

Do it as some others do it, the "interesting way" which evolves out of the fact that new has the highest precedence:

Strict

Type TTest
   Field _value:Int

   Method Create:TTest(value:Int)
      _value = value
      Return Self
   End Method
End Type

Local test:TTest = New TTest.Create(10)

Print test._value

End



FlameDuck(Posted 2006) [#6]
As to the reasoning behind it? Eh, just curious if it's possible to emulate a private constructor.
Not really. Best solution I could come up with is throwing an exce[tion in the New() Method, which is caught in the create function.

It doesn't really work tho'.