PDA

View Full Version : public objects / good coding form



tooth
23rd November 2010, 18:27
I'm just getting started again with c++/Qt working on a project.
I have a class the just lays out a widget with a button and a line edit field.
I'll be creating an instance of this object in another class (mainwindow), and will need to make some connections with the buttons. Is it bad form to make these buttons public? The below works great, solves my problem, but I would rather do it the right way. Or should I just go about creating signals and slots for these objects and make them private? Thanks for advice :)




class CustomWidget : public QWidget
{
Q_OBJECT
public:
explicit CustomWidget(QWidget *parent = 0);

QPushButton *pushButton;
QLineEdit *lineEdit;
private:
QVBoxLayout *vLayout;
QHBoxLayout *hLayout1;
QHBoxLayout *hLayout2;

// QLineEdit *lineEdit;
// QPushButton *pushButton;

};

tbscope
23rd November 2010, 18:34
The idea that some people have is that a widget, like CustomWidget, should hide the implementation details from the user.
This means that you should use CustomWidget as a single widget without anyone knowing it actually has a push button or a label etc...

This in turn means that there's a bit of work to do to create useful get/set functions, signals, slots, etc...

Always let the members of an object be managed by the parent and not by outsiders.
Take for example the case where you accidentally destroy the pushButton pointer. If you hide those pointers so that nobody can access them, you'll have established a useful protection.

tooth
23rd November 2010, 18:44
thank you for the answer and explanation. makes sense, exactly what i was looking for :)

couldn't think of a downside to making them public, thanks for providing one

franz
23rd November 2010, 19:54
As a general rule the world outside a class should not know whether certain values are calculated or cached. This means that any access you need should be done through a function. This helps you hide implementation more effectively.

Timoteo
23rd November 2010, 23:22
This topic, interface design, is a deceptively complex subject. The only rule that you can rely on with certainty is that you must keep the interface as minimal as possible. Once something is public, it is public forever. That is, the public interface of a class is viral.


As a general rule the world outside a class should not know whether certain values are calculated or cached. This means that any access you need should be done through a function. This helps you hide implementation more effectively.

Also, lazy initialization is not possible with public access to data members. Pretty much the same type of behavior but wanted to add that anyway. Having Qt class pointers (either directly or by method) in the public interface of the class also really hurts your porting efforts if you ever have to evacuate the Qt framework:eek: but that is a topic for another time.:eek: