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

6

9

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.

Lifelike answered 25/2, 2014 at 13:47 Comment(4)
Stack is a weird thing, you can push and pop stuff out of it, but cant get a specific item. Sometimes you want to know the top item. So peek() is introduced. You could have a property TopItem or such. Its a matter of style like @TomTom saidEtheline
The source is here: referencesource-beta.microsoft.com/#mscorlib/system/collections/…Jeramey
@DaveShaw: The current source, anyway. Future versions might feature a different implementation without changing the interface.Cleaning
apart from being a verb as the answer says, it's more like keeping properties for actual distinct data - peek is a computed value from the collection - the last item - properties are also unwrapped to methods: a get-er and a set-er for example.Agouti
P
12

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.

Poplar answered 25/2, 2014 at 13:54 Comment(2)
I'm fairly certain the question wasn't why is the code object named Peek a method?, but rather why is peeking at the top element of a stack done using a method?.Expulsion
However with a different name it could also be a property. addresses the reason for the implementationReservist
S
6

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.

Sawfish answered 25/2, 2014 at 13:52 Comment(0)
G
2

The documentation doesn't mention exactly what collection is actually used to handle the stack, but basically there is no other, more efficient way to give you access to only the "top" of that collection. We also don't know if the "top" is even the first or last element, it's possible that the stack keeps track of which element is the "top" and doesn't actually delete the popped members (at least not every time they are popped) in order to avoid having to move every other element (again, assuming they are using an array-like rather than linked-list-like structure).

Gyre answered 25/2, 2014 at 13:53 Comment(1)
Not sure if this is relevant. If the Peek() method is able to obtain the 'top' element, a property could use the exact same code to do so as well.Expulsion
I
2

I'd say as the value is not a property of the Stack itself, but a result of evaluating the current content of the stack, in my opinion a method is more suitable than a property.

And as C. Evenhuis mentions in his answer, Peek is a verb, so a method is more logical. And as peek is the common terminology for this operations on stacks it makes more sense to use that then to use a new/different term just to use a property.

Interrogation answered 25/2, 2014 at 13:55 Comment(0)
W
2

I agree, could be a Property as TopItem or something because that makes intitial sense, but would it throw an exception or return null if empty? Properties should not throw exceptions, according to MSDN.

From Stack's source reference, you'll see code involved to throw a specific exception.

    // Returns the top object on the stack without removing it.  If the stack
    // is empty, Peek throws an InvalidOperationException.
    public virtual Object Peek() {
        if (_size==0)
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EmptyStack"));
        Contract.EndContractBlock();
        return _array[_size-1];
    }

This now differs from how the above property concept would be handled. So one vs the other.

edit- added Property documentation. And not the winning answer, but providing further explanation about the logic on why it is not a property.

Weatherford answered 25/2, 2014 at 14:1 Comment(6)
Yes, but property is able to act the exact way as method mentioned.Lifelike
"I agree, could be a Property as TopItem or something, but would it throw an exception or return null if empty?" - Yes, of course it would.Cleaning
@O.R.Mapper Yes is not a valid answer to an either/or question. I would expect properties to not throw exceptions but to return null. Long standing Stack functionality is the exception.Weatherford
@bland: It was a "Yes" as in "Yes, it would do either of those."Cleaning
@O.R.Mapper MSDN states that Properties should avoid throwing exceptions. My point is that as a Property, it changes how functionality is and has been. The two could both exist sure, but they would result in different handling if the stack is empty.Weatherford
@bland: Yes, I'm aware of that list; it lists exceptions thrown from properties as an AVOID, but not as a DO NOT. Sometimes, such exceptions can be appropriate, as e.g. with Nullable<T>.Value, as they simply indicate the programmer is using the property in an incorrect way (e.g. at the wrong time).Cleaning
C
-1

This is encapsulation, it's purpose is to restrict access to an objects components: http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)

Companionship answered 25/2, 2014 at 13:50 Comment(7)
I do know what encapsulation is. I asked why is it implemented as a method instead as a getter-only property.Lifelike
a getter method would expose internal implementation details - the peek method does only provide high level functionality without exposing any internal data structuresJest
@Jest could you please extend that comment? I don't understand what do you mean by esposing internal implementation details.Lifelike
This answer is incorrect. A property does not expose any implementation details that are hidden by a method (if only because a property essentially comprises of one or two (get and set) methods).Cleaning
Also, linking to a Java tutorial (with Java not supporting properties) while this question is about C# (and C# does support properties) seems a bit pointless.Cleaning
@light_303: A property getter method would not expose any internal implementation details that would remain hidden with an ordinary method.Cleaning
After the edit, the answer still has nothing to do with the question. Methods and properties are both means of encapsulation.Cleaning

© 2022 - 2025 — McMap. All rights reserved.