0

So I have a header file, which looks like this:

class Crc16 
{
public:
   Crc16();

   static long calculateCrc(const BYTE* ptr, long length);
   long getCrc();
private:
   long m_crc;
};

where BYTE is an unsigned char. This implementation takes the data and returns the CRC for that particulate data. The polynomial used is a fixed one, i.e. hard coded within the static function. However, I would like to extend this implementation by letting someone define his own polynomial and carrying out the calculation. I have thought of creating a new constructor which takes the new polynomial and assigns it to a member, but it will be not possible to use it in the static function. Another possibility is to create a new function which is not static, which will take a polynommial as an argument. But the code in the static and non-static version will almost be identical. I do not want change the interface of the static function I have, since it is used in many places. What would the best solution be, from an architechural point of view?

Wballer3
  • 141
  • 1
  • 9
  • The static function and the class seem almost orthogonal. When would you currently instantiate an object of this class? Why not just use calculateCrc directly? I have trouble figuring out your use - cases. – ravnsgaard May 31 '18 at 19:05

2 Answers2

1

I would add another parameter to the function for the polynomial and give it a default value. This allows you to not have to change any of the call sites that you want to use the default but allows you to give the function your own polynomial when you want to.

static long calculateCrc(const BYTE* ptr, long length);

becomes

static long calculateCrc(const BYTE* ptr, long length, polynomial_type poly = some_default_value);
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

Why would you change to change the function to non-static if you add the polynomial as an argument?

You can have both of them implemented :

static long calculateCrc(const BYTE* ptr, long length);
static long calculateCrc(const BYTE* ptr, const PolyType poly, long length);

See : http://www.cplusplus.com/doc/tutorial/functions2/

Olivier Samson
  • 609
  • 4
  • 13
  • Thanks, I guess that is an alternative solution to NathanOliver's one. I guess both of the solve the problem in a good way, thank you once again! – Wballer3 May 31 '18 at 19:11
  • However, your solution causes duplication of a lot of code in the source file. – Wballer3 May 31 '18 at 19:16
  • 1
    @Wballer3 not necessarily, you'd just call the second from the first: `static long calculateCrc(const BYTE* ptr, long length) { return calculateCrc(ptr, default_poly_value, length); }` – Ryan Haining May 31 '18 at 20:32