I have a simple question, is it a good practise to implement getters and setters in the header file, like this ?
class WebsocketSession : public boost::enable_shared_from_this<WebsocketSession>{
public:
WebsocketSession(boost::asio::io_service& io_service, WebsocketServer& server);
tcp::socket& getSocket() { return socket_; } // <--- This
private:
tcp::socket socket_;
WebsocketServer& server_;
};
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
Having getters and setters does not in itself break encapsulation. What does break encapsulation is having a getter and a setter for every data member (every field, in java lingo). That is one step away from making all data members public.
You should not call getters and setters from the constructor. A constructor constructs the specific class in which it is defined. It is its job to initialise the fields because - well - nothing else will. The only way to guarantee initialising the fields is to assign them.
The Java coding convention states that methods (getters and setters are methods) should be after constructors declarations. It just a convention and it exists to make code easier to read in general.
Advantage
The getters and setters will be inlined so they will have no function overhead.
Disadvantage
You will be unable to make any changes to your getter and setter without having to recompile all code using your class. This is especially bad when the implementation of your class lies in a different DLL or .so file.
I personally do not like placing getters and setters in the header files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With