Question

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?

Was it helpful?

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.

OTHER TIPS

First, copy() is not a function. It is an intrinsic.

Second it is job is to copy, while in the case of delete() modifying the current string is an option, it is delete, not copyanddelete.

That difference is important because Delphi doesn't suffer from immutable strings like Java and C#.

Before ansistring, returning functions always added at least one copy, which was noticable on the computers of the day. The ansistring case afaik is only better when inlined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top