As in the title. Why does the Stack class need a method to return a reference of the top object? I've always been told, that methods suggest there's some computing involved and that simple objects should be returned with properties instead. Peek()
method has no parameters and on a code level it's (I think) a simple operation.
The question is: is there a speciffic reason for that? Any hidden behaviour that impacts performance?
EDIT: I don't know the class implementation, but f.e. if the method uses enumerator beneath, then iterating to the last element many times would be unwise. On the other hand if it's a single IList
, then it should not have any bigger impact on the performance.
stack. peek() is used to get the reference of the element at the stack's top. It does not remove that element from the stack.
A stack implementation typically contains three methods, which as push, pop, and peek. Push will allow the user to put a single item onto the stack. Peek allows the user to see what value is on top of the stack, and pop allows the user to remove the top value from the stack.
peek() – Return the top item in the stack. If the stack is empty, raise an exception. push(value) – Push a value into the head of the stack. pop() – Remove and return a value in the head of the stack.
Queue peek() method in Java The method does not throws an exception when the Queue is empty, it returns null instead.
Peek is a verb, so in my book Peek()
should be a method. However with a different name it could also be a property.
Remember that any property has associated get and/or set methods, so you'd end up with a method either way.
I understand the question as "Why is it a method, not a property".
One reason can be consistency - all access methods are actually methods. It totally is a matter of styl, because I see no reason to not have it as a property, from a pure code perspective.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With