Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Stack.Peek() a method? [closed]

Tags:

stack

c#

peek

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.

like image 409
Tarec Avatar asked Feb 25 '14 13:02

Tarec


People also ask

What does stack peek () do?

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.

What is the difference between the stack pop and peek operations?

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.

How do you peek a stack in Python?

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.

What is the type of exception thrown by peek method in Java?

Queue peek() method in Java The method does not throws an exception when the Queue is empty, it returns null instead.


2 Answers

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.

like image 175
C.Evenhuis Avatar answered Sep 21 '22 22:09

C.Evenhuis


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.

like image 20
TomTom Avatar answered Sep 22 '22 22:09

TomTom