Domanda

In practical terms it means using an custom (immutable) class over a string or some other primitive type.

Examples:

  1. Publishing: International Standard Book Number.
  2. Finance: International Securities Identification Number.

Advantages:

  1. Can ensure the format of an identifier.
  2. Becomes a first-class member of the model.

Disadvantages:

  1. Adds persistence friction (e.g. Entity Framework).
  2. More code.
È stato utile?

Soluzione

If you can give the class enough useful functionality to justify the added complexity of not being a string, then do it. For identifiers like ISBN and ISIN, I suspect this is not the case.

For an identifier class to be useful, I'd expect it to look something like this:

class ISIN {
    fromCUSIP()
    fromRawISINString()
    toString(ISIN::FormatType)
    getExchange()
    getCountryCode()
    getLastFourDigits()
    getWhateverCode()
    ...
}

If instead it looks more like this:

class ISIN {
    getString()
    setString()
}

Then I'd ditch the class entirely, use regular strings everywhere, and make sure I consistently use "isin" in all the relevant variable names.

Note that in some languages, adding a new type has almost no "added complexity" in typical programs, in which case you'd be encouraged to create the new type even if it had no functionality at all. But this is not the case for most traditional OOP languages like C++.

Altri suggerimenti

I would say go for it. I would argue that the advantages outweigh the disadvantages in this case. The extra code is likely to be pretty minimal and the persistence issue can be solved pretty easily be providing some sort of converter between your new Class and the type the database expects (I've never used Entity Framework but I know this is relatively painless in Hibernate).

One of the advantages you can get by defining your own class is that the compiler can ensure that any methods which want an ISBN or an ISIN will know at compile time if you try and pass in the wrong value. It will also be much harder to accidentally overwrite that field in your entity. We can avoid common errors like this entirely:

book.setAuthor(otherBook.getAuthorName());
book.setIsbn(otherBook.getAuthorName());
book.setPrice(otherBook.getPrice())

If ISBN is a class rather than a primitive type then the above code won't even compile, saving a lot of debugging time later.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
scroll top