3 ms·
The problem with getters and setters is that the code for them is nearly identical, yet they have to be written in nearly every single class: // Sorry if the
by malisper 12y ago
The problem with getters and setters is that the code for them is nearly identical, yet they have to be written in nearly every single class:
// Sorry if there are any mistakes, I have not
// written any Java code for quite some time.
public class Point
{
private int x;
private int y;
.
.
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int newX)
{
x = newX;
}
public void setY(int newY)
{
y = newY;
}
}
Look at how long the class definition is for something so basic!
In Common Lisp there are two ways to define classes/structures, defstruct and defclass. Defstruct[0] automatically automatically defines everything for you:
(defstruct point x y)
will define the procedures make-point, point-x, point-y, (setf point-x), and (setf point-y). The cool thing is that they are all procedures. It easily change the class definition without changing the code that uses it. There are also some additional options for defstruct to specify default values, how to print the structure, as well as what prefix to use (the default is the name of the structure, 'point' in this case).
Defclass[1], while much more verbose than defstruct, is much more powerful:
(defclass point ()
(x :writer set-x :initarg :x)
(y :reader get-y :initarg :y)
(z :accessor z))
will define procedures, set-x, get-y, z, and (setf z). Set-x and (setf z) are the setters, while get-x and z are the getters. To construct a point that is defined this way, one has to use the procedure make-instance which will take keyword parameters[2] :x and :y, for x and y respectively.
[0] http://www.lispworks.com/documentation/lw445/CLHS/Body/m_defstr.htm
[1] http://clhs.lisp.se/Body/m_defcla.htm
[2] http://www.gigamonkeys.com/book/functions.html