lundi 25 novembre 2019

How best to design configurable overloaded operators?

I have a class called BitArray which provides a convenient interface for working with variables as if they were hardware registers. So, for example, if x0 represents a 64-bit GPR, then if I say x0[15:8], then I want the second-to-least-significant byte.

In addition to a value, every object possesses a width property which specifies the number of bits the object holds.

I have overloaded most of the operator methods to provide functionality for bit-shifting, bit-wise operations, arithmetic, and so on. This was all pretty straight-forward, but the tricky part comes in when dealing with the width. For example, what is the right behavior if I bit-wise or two BitArray objects together that have different widths? If I use the left-shift operator, should I left bits disappear off the end, or should I expand the width of the object? And so on.

I could simply pick answers to these questions, but I think that maybe different behavior might be desirable in different contexts and I would like the users of this class to be able to have some way of configuring the behavior. For example, I expect that when an object represents an actual register, the user will want the register to stay fixed at a specific width, but when the object represents a literal value that is being used in an expression, then the width should be dynamic.

My question is: what is the best way to go about doing this? Here are some of my ideas:

  1. Instead of using the operators, I could use explicit method names with additional parameters that tell the methods how to behave.
  2. I could add some static members to the class which tell the methods how to have.
  3. I could make non-static members so that it is configurable per-object.
  4. I could make separate subclasses, one which has dynamic width and the other with fixed-width.

I'm not crazy about option 1 because I really want the use of the class to be convenient, and that means being able to use all the builtin operators.

But I'm worried that if I do option 2 or 3 that it will be confusing from the users perspective what is happening at any given line of code because the behavior will depend on any other line of that might have changed the configuration fields.

Are there other good options I haven't thought of?

Aucun commentaire:

Enregistrer un commentaire