openframeworks / openFrameworks

openFrameworks is a community-developed cross platform toolkit for creative coding in C++.
http://openframeworks.cc
Other
9.9k stars 2.55k forks source link

Constructors in openFrameworks #1562

Open kylemcdonald opened 12 years ago

kylemcdonald commented 12 years ago

We need a standardized approach to constructors.

The hardline answer is that there are only two types of constructors:

This means that ofBuffer(const string) shouldn't exist, only ofBuffer::load(const string). That's kind of reasonable.

But it also means that ofRectangle(x,y,w,h) shouldn't exist, and that's unreasonable.

I think a good guideline is that if anything would be called load, init or setup, then it should be in a method, not a constructor. If something would be called set (simple data container) then it's ok to have a constructor.

What does everyone think? Should ofFile(string filename) exist? How about ofFile(string filename, bool binary)? How about ofImage(string filename)?

Code is cheap, but having more alternatives can make things harder to explain and more difficult to maintain, even when they're simple wrappers.

arturoc commented 12 years ago

have answered this in other place, but here's it also :)

i think we should add custom constructors to every class that has a load, setup or allocate method, it's not the most usual in OF but is a pretty used pattern in c++, if you create a class inside a function only to be used in that function it's shorter and useful. it also allows for one of the most characteristic patterns in c++: http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

artificiel commented 1 year ago

felt for a little necrobump...

so to follow-up with https://forum.openframeworks.cc/t/use-setup-vs-constructor/41106, how about a bit of dogma?

classes:

  1. must never require constructors arguments;
  2. should have sensible defaults and be as functional as possible without being setup();
  3. that can be instantiated with constructor arguments (without complexity or side-effects) should do so;
  4. that have custom constructors should consistently follow the setup() syntax;
  5. that can’t behave correctly without a setup() call should post an ofLogError when used; (looking sharply at you, ofxPanel)