|
Because a constructor must always return a new instance of the object you might like to look at alternatives.
For example: Use the factory pattern. Specifically: use a factory method.
A factory method is one that creates an object but is not a constructor. You might create one like this:
public class MyObj
{
private MyObj()
{
}
public static CreateMyObj()
{
MyObj result = null;
if (parametersAreOkay)
{
result = new MyObj();
}
return result;
}
}
The rest of the code cannot access the constructor, and must use the CreateMyObj factory method to instantiate the object. The method may return null if the object cannot be created.
Does this help?
|
|
|
|
|
Your factory method technique is valid indeed, however, you hit my question on the mark with the statement:
>>>...a constructor must always return a new instance of the object...
It would be nice if constructors behaved as functions, then "return null" would be clear and clean. Something to think about.
Thank-you
Visualize then Realize
|
|
|
|
|
Giancarlo Trevisan wrote: It would be nice if constructors behaved as functions, then "return null" would be clear and clean. Something to think about.
No it wouldn't. The purpose of a constructor is to construct an object. If it was able to avoid doing that then the semantics of a constructor would be broken.
|
|
|
|
|
Yes, we are talking about semantics and at this point about philosophy. I agree that a constructor should construct, and you probably agree that constructors have a behavior of their own in the sense that they are not functions yet return a handle to an instance: keep in mind that a NULL is also an instance.
My consideration is, why not allow constructors that allow ONLY, if necessary, "return null", the semantics would not be crippled yet acquire "selfawareness".
Visualize then Realize
|
|
|
|
|
Giancarlo Trevisan wrote: keep in mind that a NULL is also an instance
Ummm... No. A null is the absence of a instance.
Giancarlo Trevisan wrote: My consideration is, why not allow constructors that allow ONLY, if necessary, "return null", the semantics would not be crippled yet acquire "selfawareness".
Returning null from a constructor would cripple the semantics of a constructor. The purpose, and I feel I'm repeating myself here, of a constructor is to construct an object. To do anything otherwise would be to "cripple" the semantics of a constructor.
If you don't want it to actually construct an object there is an existing solution and that is to throw an exception. And in fact that isn't really a solution because the instance will already exist at the point the exception is thrown. It just means that, so long as the exception is thrown out of the constructor, nothing will ever reference the instance.
|
|
|
|
|
Ok
Visualize then Realize
|
|
|
|
|
Giancarlo Trevisan wrote: My consideration is, why not allow constructors that allow ONLY, if necessary, "return null", the semantics would not be crippled yet acquire "selfawareness".
If you did allow the constructor to kill the object that is constructed, it would mean that you get an additional way of returning error status, that you have to handle everywhere.
The semantics would actually be crippled, as you could no longer trust that creating an object actually did create an object. You would have to check the reference after each object you create.
In practice this would mean that everyone would just write code to check the reference and throw an exception, to get the behaviour that we already have (but with less information about what caused the error):
StringBuilder sb = new StringBuilder();<br />
if (sb == null) throw new ApplicationException("Object creation failed.");
The power of a programming language is not only what you can do, but also what you can't do.
---
b { font-weight: normal; }
|
|
|
|
|
I began the post with a postscriptum and the possibility to raise a System.Exception() (preceeded possibly by a Me.Dispose?): an ApplicationException would be more appropriate. I agree that raising an exception is the correct approach, who better than a class knows if the conditions are right to instantiate an object: I call this encapsulation.
Guffa wrote: In practice this would mean that everyone would just write code to check the reference and throw an exception, to get the behaviour that we already have (but with less information about what caused the error):
Let's go to an extreme, there is not enough memory to create an object, proper code would still require a reference check. In my view NOT ENOUGH MEMORY is a condition that does not allow object instantiation, I'm just generalizing. Give you an example, class MythicalFooCreature can't be instantiated if the temperature is below 32F, in my view the constructor should raise an exception and return a null reference.
Guffa wrote: The power of a programming language is not only what you can do, but also what you can't do.
Very profound, I add, evolution is applicable even to programming languages and is a consequence of trial and error or, better for humans, a questioning to gain deeper knowledge (my knowledge is probably superficial). I am alluding at a fundamental behavior that in my view would not be crippling but evidently this is not a general consensus.
Visualize then Realize
|
|
|
|
|
Giancarlo Trevisan wrote: I call this encapsulation.
Not accurate at all. Your "implementation" doesn't encapsulate anything. Your actually trying to give a class the option of not creating itself based on conditions OUTSIDE the class. So, you're not encapsulating anything, but are forcing a class to look outside of its own scope. It must know certain things about the environment its running in. That's quite the opposite of encapsulation.
A properly designed class shouldn't care about ANYTHING outside of its own scope. All it should need is proper parameters to construct itself. If it needed to look outside of itself, that would destroy its ability to be reused in non-similar situations.
The factory pattern in the best way to go to maintain that encapsulation. There's nothing that says you can't write multiple factories, each dealing with a specific set of requirements, to create the same class.
Dave Kreskowiak
Microsoft MVP - Visual Basic
-- modified at 8:38 Monday 24th July, 2006
|
|
|
|
|
Dave Kreskowiak wrote: A properly designed class shouldn't care about ANYTHING outside of its own scope. All it should need is proper parameters to construct itself. If it needed to look outside of itself, that would destroy its ability to be reused in non-similar situations.
Did it cross your mind that the temperature is a constructor parameter? And that instead of temperature I could pass the class constructor a nice reference of the Environment? Are you alluding that the Environemnt should know better than MythicalFooCreature if it can grow? It's a point of view, your classes are isolated, I tend to see mine as living in a commmunity. I encapsulate within the constructor the birth/death behavior: this is what I call selfawareness.
And I do agree that Factoring is the best solution.
Visualize then Realize
-- modified at 9:06 Monday 24th July, 2006
|
|
|
|
|
Giancarlo Trevisan wrote: Did it cross your mind that the temperature is a constructor parameter?
Yes, it did!
Giancarlo Trevisan wrote: And that instead of temperature I could pass the class constructor a nice reference of the Environment?
Beyond the constructor, does the Environment have ANYTHING to do with what's inside the class?? Nope. So why should it care?
Example - Your class, written under the .NET Framework on Windows XP, needs certain things to exist before it can construct itself. Great! You pass in your Environment and your class constructs itself. Wonderful!! Now, use the exact some code under Mono on a Linux box. But, the Environment class under Mono doesn't expose the same information that it does under Windows. Your class constructor now fails because it can't get what it expects, even though the code would run perfectly! Now what???
That's what the factory pattern is for! The factory is responsible for checking to see if it is OK to construct the class. Is it wise to put an entire automotive assembly plant in every car so it can build itself?
The class code should care NOTHING about what's going on outside of it. The class is, literally, it's own little world.
Dave Kreskowiak
Microsoft MVP - Visual Basic
|
|
|
|
|
Dave,
as class builders we model the problem at hand, I consider modelling a wonderful art.
Dave Kreskowiak wrote: Beyond the constructor, does the Environment have ANYTHING to do with what's inside the class?? Nope. So why should it care?
I can reply very simply: the Environment conditions the MythicalFooCreature during its life.
Dave Kreskowiak wrote: Your class constructor now fails because it can't get what it expects, even though the code would run perfectly! Now what???
You are right! You can try to instantiate a MythicalFooCreature in a hostile Environment, it would probably not live, and the constructor would be the first to know. (Mind you, I don't mean to undermine Mono nor Linux)
Dave Kreskowiak wrote: The class code should care NOTHING about what's going on outside of it. The class is, literally, it's own little world.
Hm, this is a rather strong assertion, we could really debate about this.
At any rate, I do not like to reinvent wheels, and if I do I'll use inheritance. My post questioned: why not have a Constructor that in some cases DOES NOT do its job, construct, but simply does nothing? What are the implications? However we model this necessity at the end the instance should not be there. So there, we create then destroy, that's when my minimalist nature came in, and I wrote the post, why not simply "cut short" from within the constructor?
I'm investigating the effect of Dispose as implied in the pseudocode below, this would solve the need at hand:
Class MythicalFooCreature<br />
Public Sub New(temp)<br />
If temp < 32 Then<br />
Me.Dispose()<br />
Throw System.Exception("Too cold")<br />
End If<br />
End Sub<br />
End Class
Maybe the dispose is not necessary since throwing an exception within a constructor does it automatically.
-- modified at 1:19 Tuesday 25th July, 2006
|
|
|
|
|
Giancarlo Trevisan wrote: Let's go to an extreme, there is not enough memory to create an object, proper code would still require a reference check
No, proper coding would require that the out of memory exception is handled.
Giancarlo Trevisan wrote: Give you an example, class MythicalFooCreature can't be instantiated if the temperature is below 32F, in my view the constructor should raise an exception and return a null reference.
You can't do both. Either raise the exception in the constructor, or use a Factory Pattern.
If an exception is thrown to something outside the constructor it no longer matters what the constructor would have returned because the garbage collector will get it before anything else can get a reference to it.
Giancarlo Trevisan wrote: I am alluding at a fundamental behavior that in my view would not be crippling but evidently this is not a general consensus.
It wouldn't be crippling per se, but it would change the semantics. There already exists a semantic equivalent for what you want to do over the responsibility of a basic constructor that you can use (i.e. The Factory Pattern) so why reinvent the wheel.
|
|
|
|
|
Colin Angus Mackay wrote: It wouldn't be crippling per se, but it would change the semantics. There already exists a semantic equivalent for what you want to do over the responsibility of a basic constructor that you can use (i.e. The Factory Pattern) so why reinvent the wheel.
Now, this is an answer!
Visualize then Realize
|
|
|
|
|
Hi,
Is there a way to provide a MS-Word type interface in a C# .NET
application?
Does the Microsoft Office 11.0 object let us do this? Or, is there any
third-party library that can be used for such a feature? Please let me know.
Thank you.
Ravi
|
|
|
|
|
DevExpress have a ribbon bar component if that's any help.
As of how to accomplish this I wouldn't have a clue at the moment and I'm too lazy to google it
|
|
|
|
|
Thanks for the citation Ed. I'll check out the component.
-Ravi
|
|
|
|
|
Hi,
Maybe, because of extremally hot sommer my searching skills are reduced
to zero, but i couldnt find any detailed description of windows
services, i would be greatful if You could give me some link... well
i'll describe my problem anyway:
I have to write windows service, which on timer event calls function
from unmanaged dll library to comunicate with some device over tcp
protocol and send informations to database. (This dll loads proxy
server (from another dll) to listen for informations from this device)
All code works fine in console/windows c# application
In Windows service it accidently started to work but under quite
unacceptable circumstances...
Server works correct only when i use in timer event function
MessageBoxA imported from user32.dll (i tried this for debugging
purposes)... Also "allow service to interact with desktop" must be
'ON'. (well, i can always see server in netstat, but service cant get data fom
it)
I have tried to use another function from user32.dll (just to load this dll into memory) but with no results...
Thats what i have observed. Im sorry if i dont know something which i
should, im new in c# .net, and now im in a point in which i dont know
which tutorial should i read next...
I would be thankful for ANY help...
|
|
|
|
|
try anthoer method for period waken,
when timer event handler completed it execution, what's next ?
|
|
|
|
|
Timer event is used for polling. It just checkes if there is data pedning, read it if yes, end ends.
Anyway i have tried another simpler aproach. I thought that mayby its not working because of creating multiple threads. So i have created single worker thred which does all work in infinite loop. Although there is the same problem... It looks like this:
private void WorkerFunction()
{
//I tried this but it changes nothing:
// MyDll.LoadLibrary("user32.dll");
//If i am correct the same is done by pinvoke:
// IntPtr dll = MyDll.LoadLibrary("my.dll");
m_nAppId = MyDll.OpenApp(0);
string Id = "123";
m_nLnkId = MyDll.OpenLink(m_nAppId, encoding.GetBytes(Id), 0);
AddTransaction("OnStart " + m_nAppId.ToString() + ":" + m_nLnkId.ToString());
// start an endless loop; loop will abort only when
// "serviceStarted" flag = false
while (serviceStarted)
{
tick++;
AddTransaction(tick);
StringBuilder buffer = new StringBuilder(256);
int res = MyDll.AutoGetPollData(m_nAppId, m_nLnkId, buffer, 256);
if (res != 0)
{
AddTransaction(buffer.ToString());
MyDll.AutoReleasePollData(m_nAppId, m_nLnkId);
}
if (serviceStarted)
{
Thread.Sleep(new TimeSpan(0, 0, pollingBreak));
}
//and now MessageBox. I can put it enywhere within
//loop and it works...
MyDll.MessageBoxA(0, "asd", "Myservice", 0);
}
AddTransaction() sends data to db. "ticks" are always sent properly but not proper data. I appreciate any suggestions, i have no idea whats going on...
|
|
|
|
|
Does anybody know of any API or SDK which I can use to programatically generate visual studio project files and solution files?
Also is there a way to programatically generate a strongly typed dataset or xml schema by passing in a database name, and table name to some API, SDK or .exe?
thanks
|
|
|
|
|
danielk_ wrote: xml schema by passing in a database name, and table name
If you export the table as an xml file you can then use the SDK tool XSD.exe to generate a schema for it and then it can be used again to generate a dataset from it. I think , based on running xsd.exe in a prompt without any args (displays the help).
danielk_ wrote: programatically generate visual studio project files and solution files?
They're just text files, depends on what your input is but it shouldn't be too difficult to build your own utility for this. If you're really stuck take a look at the Solution Import Wizard (or something with a similar name) in SharpDevelop [^]for some pointers.
The Welsh will always support two teams: The Welsh, and anyone playing England
|
|
|
|
|
Hi all,
I am developing the Pocket pc application & i want to synchronize database between PC and Pocket PC. How can i do that? I don't have any idea about that.
I am using Sql server ce as pocket pc database and want to synchronize when Active Sync run. and tell me how to write the conduit for pocket pc bcoz my PC database is not sql server.
Help me plz.
shalabh
-- modified at 7:41 Saturday 22nd July, 2006
|
|
|
|
|
Hi all
I have an Task on Combobox and its style is DropDown
ie
When i move the cursor over combobox,
it should be dropdown and show its contents.
after lot work,i didn,t get up to the mark
plz suggest me.
thanks in advance
Nagraj
|
|
|
|
|
Handle the MouseMove event, when it's fired set the DroppedDown property to true.
May I ask why this is required since, for me it would seriously annoy me
The Welsh will always support two teams: The Welsh, and anyone playing England
|
|
|
|
|