Name your compare method diff

In this article, I will talk about naming the comparison method “diff”, what constitute a good return value for the diff method, and how I emulate exception handling in SystemVerilog, a language which does not have formal exception handling.

First, we name the comparison method diff rather than compare. Why? Because is it easier. Consider this code

if (packet1.compare(packet2)) begin
  // what does compare return exactly?
end

Chances are that you have to look up the compare method to see what it returns before you write your code, each time. Now read this code:

if (packet1.diff(packet2)) begin
  // it reads like english
  // so packet1 must be different than packet2
  $display("Packets are different);
end

Much easier. And I bet you don’t have to look up the diff method.

Now onto the concept of what constitute good return values. Let’s continue with the diff example. When you run the Unix diff command, it return 0 when there is no differences between two files, or 1 if there is a difference. This makes conditional statements easy to write, both in Unix and in your code. Let’s write a diff method that returns the number of differences:

// Return the number of differences
function int a_class::diff(a_class other);
  diff = 0;
  if (this.a != other.a)
    diff++;
  if (this.b != other.b)
    diff++;
endfunction

Nice, but we can do better. We can enhance the diff method to return messages about the differences:

function int a_class::diff(a_class other, ref string msg[$]);
begin
  diff = 0;
  if (this.a != other.a)
  begin
    msg.push_back($psprintf("This a (%0d) is different than the other a (%0d)",this.a,other.a));
    diff++;
  end
  if (this.b != other.b)
  begin
    msg.push_back($psprintf("This b (%0d) is different than the other b (%0d)",this.b,other.b));
    diff++;
  end
end
endfunction

And now we can print the diff messages in the context where the comparison was made:

  if (foo.diff(bar,msg))
  begin
    foreach(msg[idx]) $display("%s",msg[idx]);
    // This was fatal, so end here
    `vmm_fatal(log,"Unrecoverable error");
  end

Since VMM supports the printing of line and file number, we get a clear picture of where the error was detected. This is better than aborting from inside the comparison method. Until SystemVerilog gets exception handling, this is an acceptable compromise.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: