0

For comparisons / evaluations of objects of the same class(and other purposes), is it better to define a static or a non-static (is this called "dynamic" by chance?) function?

Sample code:

class student
{
    internal decimal medianOfMarks()
    {
        int count = 0;
        decimal sum = 0;
        foreach(float mark in reportCard)
        {
            counter++;
            sum += mark;
        }
        return sum / count;
    }

    **OR**

    internal static decimal medianOfMark(student delinquent)
    {
        [same logic]
    }
}

Let's not consider making the function a property, though parameterless, since I'd like an answer applicable to parameterized functions as well.

What are arguments pro / con each approach?
What deciding factors do exist?
I've already thought into this myself, but I don't want to bias the discussion with my opinion.

  • 1
    See here programmers.stackexchange.com/questions/199735/… – blgt Jun 16 '14 at 9:51
  • @blgt that one is more about performance, memory consumption in particular. For me this is more about which one is better style, better comprehensible and good practice. I am by far not concerned about running out of memory. – Mark Jun 16 '14 at 11:30
  • 4
    Do you need access to private members? Yes? Make it a method. No? Make it static. – Doval Jun 16 '14 at 12:18
  • 1
    If you're not concerned about what's under the hood, than @Doval's comment is the alpha and the omega. static == no state, non-static == state. – blgt Jun 16 '14 at 13:18
  • 1
    I always put static members in a separate section of the source code. This makes it clear that they are completely different from non-static members. Microsoft code analysis automatically warns you if a method could be static, but is not. – Frank Hileman Jun 16 '14 at 17:25
1

Subjectively, I like the non-static instance method, it feels more natural. YMMV.

Objectively, the static form requires one additional parameter that feels redundant, i.e.

myStudent.medianOfMark()

vs.

student.medianOfMark(myStudent)

I'm not a C# wizard so excuse any wrong syntax details. Also, as others have commented, there are some other issues with naming, using floats, etc...

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.