Defining Lisp classes in packages

In Lisp, when you define classes in packages, you have to remember that you have to explicitly export the accessors too. For example, you define the following package with a class inside.

(defpackage :mhn-foo
  (:use :common-lisp)
  (:export #:fooclass))
(in-package :mhn-foo)
(defclass fooclass ()
  ((fooatt
    :accessor fooattribute)))

However, while you can instantiate the class, you get an error message when you try to access the attribute of the class.

CL-USER> (defparameter *fooparameter* (make-instance 'mhn-foo:fooclass))
*FOOPARAMETER*
CL-USER> (setf (mhn-foo:fooattribute *fooparameter*) "foo")
; Evaluation aborted on #<SB-INT:SIMPLE-READER-PACKAGE-ERROR "The symbol ~S is not external in the ~A package." {1005FDFC03}>.

To be able to access the attribute of the class, you have to export it.

(defpackage :mhn-foo
  (:use :common-lisp)
  (:export #:fooclass #:fooattribute))

Now you can work with the attribute of the class without problems.

CL-USER> (defparameter *fooparameter* (make-instance 'mhn-foo:fooclass))
*FOOPARAMETER*
CL-USER> (setf (mhn-foo:fooattribute *fooparameter*) "foo")
"foo"
CL-USER> (mhn-foo:fooattribute *fooparameter*)
"foo"

This is not very different in other programming languages. For example, in Java and C#, you define visibility not only for the class, but for the class members too. If you forget to set visibility for class members, you might have problems accessing them.

Comment