Using getter and setter methods in Haxe

One of the fundamental concepts in object oriented programming is Encapsulation. This means that all properties are private and can only accessed by public methods. These methods are interfaces to the outside of the class.

How it will look like

class ExampleClass {
		
	private var _width:Float;
	public var width(get, set):Float;
		
	public function new():Void{
		
		// Some code
	}
	
	private function get_width():Float{
		return _width;
	}
	
	private function set_width(value:Float):Float{
		_width = value;
		return _width;
	}
}

The variable _width is private, so we will make sure that this property of the class can not be accessed from the outside. In the next line we define a public varibale width and inside of the
braces you can define if this varibal is read and/ore writeable. Let me explain this in a example:

// Sets the read and write state to accessable.
// The varibale is read- and writeable from outside.
// You have to define a get_variablename method
// and a set_variablename method.
public var width(get, set):Float;

// Sets the read state to accessable. 
// The varibale is read- but not be writeable from outside.
// You have to define a get_variablename method
public var width(get, null):Float;
	
// Sets the write state to accessable. 
// The varibale is write- but not be readable from outside.
// You have to define a set_variablename method
public var width(null, set):Float;

The getter and setter methods are private. They will return always the private variable in the end.

Where are the benefits?

The main benefits of using getter and setter methods are:

  • It will allow you add additional functionality more easily.
  • Because you created an interface to the outside (get/set), you can make internal changes without breaking some classes outside.
  • You can make readonly properties.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>