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.

Tarec
  • 3,268
  • 4
  • 30
  • 47
  • 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 said – lordkain Feb 25 '14 at 13:52
  • 1
    The source is here: http://referencesource-beta.microsoft.com/#mscorlib/system/collections/stack.cs#6acda10c5f8b128e – DaveShaw Feb 25 '14 at 13:58
  • @DaveShaw: The *current* source, anyway. Future versions might feature a different implementation without changing the interface. – O. R. Mapper Feb 25 '14 at 14:01
  • 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. – Demetris Leptos Jan 03 '17 at 21:24

6 Answers6

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.

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • 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?`. – decPL Feb 25 '14 at 14:02
  • 1
    `However with a different name it could also be a property.` addresses the reason for the implementation – Jonesopolis Feb 25 '14 at 14:03
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.

TomTom
  • 61,059
  • 10
  • 88
  • 148
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).

IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
  • 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. – decPL Feb 25 '14 at 13:55
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.

Community
  • 1
  • 1
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
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.

bland
  • 1,968
  • 1
  • 15
  • 22
  • 1
    Yes, but property is able to act the exact way as method mentioned. – Tarec Feb 25 '14 at 14:05
  • "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. – O. R. Mapper Feb 25 '14 at 14:05
  • @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. – bland Feb 25 '14 at 14:52
  • @bland: It was a "Yes" as in "Yes, it would do either of those." – O. R. Mapper Feb 25 '14 at 15:05
  • 1
    @O.R.Mapper [MSDN](http://msdn.microsoft.com/en-us/library/ms229006.aspx) 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. – bland Feb 26 '14 at 15:40
  • @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.Value`](http://msdn.microsoft.com/en-us/library/ydkbatt6%28v=vs.110%29.aspx), as they simply indicate the programmer is using the property in an incorrect way (e.g. at the wrong time). – O. R. Mapper Feb 26 '14 at 15:58
-1

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

Eamonn McEvoy
  • 8,876
  • 14
  • 53
  • 83
  • 1
    I do know what encapsulation is. I asked why is it implemented as a method instead as a getter-only property. – Tarec Feb 25 '14 at 13:51
  • 1
    a getter method would expose internal implementation details - the peek method does only provide high level functionality without exposing any internal data structures – light_303 Feb 25 '14 at 13:55
  • 1
    @light_303 could you please extend that comment? I don't understand what do you mean by esposing internal implementation details. – Tarec Feb 25 '14 at 13:57
  • 1
    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). – O. R. Mapper Feb 25 '14 at 13:59
  • 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. – O. R. Mapper Feb 25 '14 at 14:00
  • @light_303: A property getter method would *not* expose any internal implementation details that would remain hidden with an ordinary method. – O. R. Mapper Feb 25 '14 at 14:08
  • 1
    After the edit, the answer still has nothing to do with the question. Methods and properties are both means of encapsulation. – O. R. Mapper Feb 25 '14 at 14:09