Advertising (This ad goes away for registered users. You can Login or Register)

Are constructors and destructors Evil?

Discuss about your favorite (gaming...or not) devices here. The most popular ones will end up getting their own categories
Programming discussions for your favorite Device
Forum rules
Forum rule Nº 15 is strictly enforced in this subforum.

Are constructors and Destructors Evil?

Yes
0
No votes
No
4
100%
 
Total votes: 4

User avatar
Infinite Chalupas
Posts: 92
Joined: Thu Feb 20, 2014 9:00 pm

Are constructors and destructors Evil?

Post by Infinite Chalupas » Tue Mar 11, 2014 3:38 pm

So I was working on an HTML5 port of my game engine today and while I was writing the File "class" I had an epiphany. It was something so controversial to me, that I wanted other programmer's opinions. Please read the details fully before making a decision.


One of the most common features of object-oriented programming is the use of constructors and destructors, but most people don't put a lot of thought into how it affects the structure of a language. The first issue is, not all object-oriented languages support them. For example, the most common one is Javascript, and the desire to have them actually contributed greatly to it being mangled. Java also doesn't having destructors.

The second issue is that the context in which objects are created and disposed is not always apparent. In C#, an object is not guaranteed to be destroyed when it goes out of scope. In fact, it tends to linger in the garbage collector for some time, so you have to manually dispose or finalize the object, thus defeating the purpose of a destructor altogether.

The third issue is name mangling. The languages that do use constructors and destructors have a somewhat ridiculous naming scheme that uses the name of the class itself. You may not think of this as an issue, but consider in C++ that the tilde (~) is not a valid character for identifiers. The constructor can also cause issues if you're working with both C and C++ code. For example, in an older version of my engine, I had a C struct called Matrix and a function to create it:

Code: Select all

typedef struct Matrix Matrix;
struct Matrix
{
  float cell[4][4];
}

void Matrix_Matrix(Matrix *_this, const float *value);
and I had a C++ class that was supposed to act as a wrapper:

Code: Select all

class Matrix
{
  public: Matrix(const float *value);
};
When I tried to build the application, I got name mangling errors. Not because there is a struct Matrix and a class Matrix (it had no problem telling those apart), but because the function Matrix_Matrix and Matrix.Matrix ended up having the same name in the assembly. Again, I do not expect many of you to consider this a big concern, but I do think it would've been more appropriate to at least dedicate specific keywords to identify constructors and destructors or to treat them as operators.

The fourth issue is error handling. Because constructors can't return a value, the only way to handle errors in a constructor is to wrap the object in a try/catch statement, which leads to a secondary headache; freeing resources after an error, which pushed some languages to evolve to having "with", "using", and "finally" statements.

The fifth issue is by far the biggest...multithreading and asynchronous operations. When dealing with multiple threads or asynchronous operations, the user may need to provide several event handlers and setup additional properties or things like semaphores. Just too much to be passed to a constructor. Additionally, they don't consider that fact that the object could be disposed in one of several threads. If thread 1 disposes of the object while thread 2 is using it, you could get a crash. Or an even worse example, if thread 1 disposes of the object while thread 2 has a semaphore locked and thread 3 is waiting for permission, you've could have yourself a nasty deadlock.
I did come up with simple solution to this though. I'm not sure if it's ever been done before, but I've personally never seen it done. It's to create an agent that manages events, properties, and semaphores for an object. It's kinda similar to how .NET does events for it's controls, but bundled together. For example:

Code: Select all

Agent agent = new Agent();
agent.eventHandler.Add(FileOpenEventHandler, MyFileOpenHandler);
agent.eventHandler.Add(FileCloseEventHandler, MyFileCloseHandler);
agent.eventHandler.Add(FileReadEventHandler, MyFileReadHandler);
agent.eventHandler.Add(FileErrorEventHandler, MyFileErrorHandler);

File file = new File(filePath, FileMode.Read, agent);



void MyFileOpenHandler(Agent agent, FileOpenEventArgs e)
{
  Debug.Log("File was opened");
}

void MyFileCloseHandler(Agent agent, FileCloseEventArgs e)
{
  agent.eventHandler.Clear();
}

void MyFileReadHandler(Agent agent, FileReadEventArgs e)
{
  Debug.Log(e.progress.ToString());
}

void MyFileErrorHandler(Agent agent, FileErrorEventArgs e)
{
  Debug.Error(e.ToString());
}
Using agents would make asynchronous and multi-threaded programming much easier. Additionally, you could expand off of agents to remove the need for semaphores and mutexes altogether by sending signals to the agent that place operations on a queue, which the agent itself performs, thus simplifying cross-thread communication.


-----------------------------

So in summary, are constructors and destructors 100% evil? No... But they do have quirks and issues surrounding them, and as we progress towards a multi-tasking world, we may have to address them more seriously in future; perhaps in "the next big language".

Please take this with a grain of salt. The major purpose of this poll is to help myself come to a conclusion about the path I'm wanting to take with one of the libraries I'm working on. If you have anything else to add, some comments to make, some insults to throw (I'm sure there will be), please share your opinion.
Advertising

User avatar
codestation
Big Beholder
Posts: 1660
Joined: Wed Jan 19, 2011 3:45 pm
Location: /dev/negi

Re: Are constructors and destructors Evil?

Post by codestation » Tue Mar 11, 2014 5:04 pm

I don't see constructors/destructors as evil things, they are just another programming concept that can be useful if used properly.

I really don't see a problem with C# objects being destroyed at an indeterminate time, just be careful to don't introduce dependencies in the constructor that can be tracked to external resources. For example it will be stupid to open a database connection from a constrained remote server in a constructor because it will be posibly be blocking another objects who try to access that resource when the original object goes out of scope but the destructor ins't called yet. BTW, the delayed destructor call can be applied too to languages without a GC like C++: for example Qt offers delayed object deletion for objects derived from QObject via deleteLater().

I cannot give you an opinion about the name mangling problem because i haven't see that problem myself (yet).

The error handling issue depends on the language, personally i wouldn't be using any code in the constructor that could generate an *expected* exception (like opening a file that couldn't exist).

Sorry to leave my post half done, have to do some things at work. Will be back finish it (and yes, my post is biased toward constructors/destructors == good, and the problems comes by a bad implementation of them by the programmer).
some insults to throw (I'm sure there will be)
No programming thread is complete without some flamming, lets see who is the first one to start it :twisted:
Advertising
Plugin list
Working on: QPSNProxy, QCMA - Open source content manager for the PS Vita
Playing: Error: ENOTIME
Repositories: github, google code
Just feel the code..

User avatar
Infinite Chalupas
Posts: 92
Joined: Thu Feb 20, 2014 9:00 pm

Re: Are constructors and destructors Evil?

Post by Infinite Chalupas » Tue Mar 11, 2014 7:27 pm

codestation wrote:I don't see constructors/destructors as evil things, they are just another programming concept that can be useful if used properly.
Agreed. One of the things I tried to point out most in this was how many different bad constructor/destructor practices people use every day without even thinking, and how people tend have way too many overloads or arguments in their constructors. They aren't 'evil' per se, but they tend to influence it a lot.
codestation wrote:I really don't see a problem with C# objects being destroyed at an indeterminate time, just be careful to don't introduce dependencies in the constructor that can be tracked to external resources. For example it will be stupid to open a database connection from a constrained remote server in a constructor because it will be posibly be blocking another objects who try to access that resource when the original object goes out of scope but the destructor ins't called yet. BTW, the delayed destructor call can be applied too to languages without a GC like C++: for example Qt offers delayed object deletion for objects derived from QObject via deleteLater().
There are some cases where you need the object to be disposed immediately though. For example, in the PS Vita Tool program I'm working on, if the user attempts to delete a vita game backup or savedata, the windows explorer won't let you because the images (icon0.png, pic1.png) are being used by the application, even if I set the images to null because the handles are still opened in the objects that are floating around in the garbage collector. So I have to force a dispose so the user can actually delete files.



I'm pretty much neutral about this because they're such a common part of object oriented programming despite having so many quirks.

User avatar
hgoel0974
Retired Mod
Posts: 2154
Joined: Mon Jul 23, 2012 11:42 pm
Location: Maia, Pleiades Nebula

Re: Are constructors and destructors Evil?

Post by hgoel0974 » Tue Mar 11, 2014 8:31 pm

Assuming you're using a CLR language I don't think you should have that issue with images if you simply call dispose when you're done. If that doesn't work, you can always tell the GC to collect garbage.
"If the truth is a cruel mistress, then a lie must be a nice girl"

User avatar
Acid_Snake
Retired Mod
Posts: 3099
Joined: Tue May 01, 2012 11:32 am
Location: Behind you!

Re: Are constructors and destructors Evil?

Post by Acid_Snake » Tue Mar 11, 2014 9:14 pm

or you can be a man and use either python or C

User avatar
codestation
Big Beholder
Posts: 1660
Joined: Wed Jan 19, 2011 3:45 pm
Location: /dev/negi

Re: Are constructors and destructors Evil?

Post by codestation » Tue Mar 11, 2014 9:16 pm

Well, calling Close() on the opened files actually calls Dispose(), so closing/disposing the files after using them is the correct way to do it (as opossed to just removing the reference by assigning null).
Acid_Snake wrote:or you can be a man and use either python or C
SHOTS FIRED!
Plugin list
Working on: QPSNProxy, QCMA - Open source content manager for the PS Vita
Playing: Error: ENOTIME
Repositories: github, google code
Just feel the code..

User avatar
Infinite Chalupas
Posts: 92
Joined: Thu Feb 20, 2014 9:00 pm

Re: Are constructors and destructors Evil?

Post by Infinite Chalupas » Tue Mar 11, 2014 9:33 pm

Acid_Snake wrote:or you can be a man and use either python or C
A majority of my programs are. I normally only use C++ if I need a lot of structure or C# if I need to design a GUI application fairly quickly.
codestation wrote:Well, calling Close() on the opened files actually calls Dispose(), so closing/disposing the files after using them is the correct way to do it (as opossed to just removing the reference by assigning null).
That doesn't with with the Image.FromFile functions, and I'm talking about assigning null to the .Image property of picture boxes

User avatar
Acid_Snake
Retired Mod
Posts: 3099
Joined: Tue May 01, 2012 11:32 am
Location: Behind you!

Re: Are constructors and destructors Evil?

Post by Acid_Snake » Tue Mar 11, 2014 9:43 pm

Infinite Chalupas wrote:A majority of my programs are. I normally only use C++ if I need a lot of structure or C# if I need to design a GUI application fairly quickly.
no goddamnit, that is not how you do flame wars in the programming section. It goes something like this:
- either m0skit0 or me start a flame war
- other users continue the flame war
- either m0skit0 or me call the other users dumb and closes the thread to end the flamewar
go it? it ain't that hard, let me try again:
C# sucks

User avatar
codestation
Big Beholder
Posts: 1660
Joined: Wed Jan 19, 2011 3:45 pm
Location: /dev/negi

Re: Are constructors and destructors Evil?

Post by codestation » Tue Mar 11, 2014 9:46 pm

Infinite Chalupas wrote: That doesn't with with the Image.FromFile functions, and I'm talking about assigning null to the .Image property of picture boxes
Read this and was like "wtf, the file should be closed after the image is returned", then i found that you were right. IMHO keeping the file handle opened on a image that is already mapped to memory is a horrible implementation. In your case using a Image.FromStream seems better (according to that example). BTW, you should try Qt for quick GUI applications, QtCreator is getting better with each release.
Plugin list
Working on: QPSNProxy, QCMA - Open source content manager for the PS Vita
Playing: Error: ENOTIME
Repositories: github, google code
Just feel the code..

User avatar
Infinite Chalupas
Posts: 92
Joined: Thu Feb 20, 2014 9:00 pm

Re: Are constructors and destructors Evil?

Post by Infinite Chalupas » Tue Mar 11, 2014 10:14 pm

codestation wrote:
Infinite Chalupas wrote: That doesn't with with the Image.FromFile functions, and I'm talking about assigning null to the .Image property of picture boxes
Read this and was like "wtf, the file should be closed after the image is returned", then i found that you were right. IMHO keeping the file handle opened on a image that is already mapped to memory is a horrible implementation. In your case using a Image.FromStream seems better (according to that example). BTW, you should try Qt for quick GUI applications, QtCreator is getting better with each release.
Yeah...it is... Btw, I've tried Qt before and I tend to have a lot of problems with it. Sometimes the installer freezes the entire pc, sometimes the toolchain doesn't work and applications won't build, sometimes the glade library screws up linking. Those 3 things aside, the placement of objects in the form designer is also a bit goofy. Of course, the last time I tried it was at least a year ago, so it's probably gotten better since then.

Post Reply

Return to “Programming and Security”