Search code examples
classooplispcommon-lispclos

Common Lisp alternative to using Classes


I'm wondering how to store a single variable and to have specific functions on that variable. I'm wondering if there are alternatives to creating a class.

Specifically, I am creating an application where I store a value for time that represents the number of seconds elapsed from a base time (e.g., Jan 1, 2000, 00:00:00). I want to perform operations on this value such as convert it from seconds from to a specific time or date, or from a date to the specific seconds.

I have done this using a class, however it seems wasteful. Specifically, every time I access the stored value for seconds elapsed it would look similar to (time-time time) where time-time is the accessor for the time instance time.

Is there a better way to design this, perhaps without classes?


Solution

  • If you have a class which is just wrapping a single object, and that object has a known type, then you can always just write methods for the class of that object instead:

    (defmethod time-as-unix-time ((tm integer))
      (- tm (load-time-value (encode-universal-time 0 0 0 1 1 1970 0))))
    

    For instance.

    Of course object-oriented zealots will throw you into a pit full of spikes if they catch you doing this sort of thing: it no doubt violates encapsulation or some other rule of the cult.