Search code examples
delphilanguage-designpascallibrary-design

Why do some string routines give a result and some change the original in Delphi?


Something that has been boggling my mind is that I don't understand why some (most) string routines are functions that give a result and some string routines are procedures which change the original string.

S2 := Copy(S1,3,2);

Copies into S2 from S1 the 2 characters starting from the 3rd position.

Delete(S,3,2);

Deletes from S the 2 characters starting from the 3rd position.

I would have thought it more consistent to have Delete (and a few others) behave like most other string routines, so you could write:

S2 := Delete(S1,3,2);

Why isn't that the case?


Solution

  • The reason is in the name.

    Copy is a function because it is supposed to create a copy. A procedure version of Copy would need an additional parameter, because when there is already a source, where would the target go?

    Delete is a procedure because it is supposed to delete characters from a string. For a function version of Delete which returns the outcome of the delete operation, what should become of the source? You're calling a delete operation on it: it cannot remain unaltered.

    As analogy; compare it with the procedure TRect.Offset and the function TRect.CenterPoint. Offset performs an operation on the entity, where CenterPoint reads a attribute of the entity.