The validated-class
metaclass provides a :validators
slot parameter. :validators
takes a list of one or more predicates which are run on object creation and slot updates. Failed valiadtors singnal the validation-error
condition.
(defun less-than-5? (value)
(< (length value) 5))
(defclass test-class ()
((foo :initarg :foo
:accessor foo
:validators (stringp less-than-5?)))
(:metaclass validated-class))
;; CL-USER> (make-instance 'test-class :foo 123)
;; STRINGP failed when setting FOO to 123
;; [Condition of type VALIDATION-ERROR]
;;
;; CL-USER> (make-instance 'test-class :foo "12345")
;; LESS-THAN-5? failed when setting FOO to 12345
;; [Condition of type VALIDATION-ERROR]
;;
;; CL-USER> (make-instance 'test-class :foo "1234")
;; #<TEST-CLASS {7007E09133}>