tags:

views:

52

answers:

3

Hello guys,

I have a class with two related functions (methods):

public class class1
{
    public void SubscribeToListOfEvents()
    {
        // ....
    }

    public void UnSubscribeFromListOfEvents()
    {
        // ....
    }
}

What's the best practice to use related functions in one class ?

Do you know of any implementations of related functions as one function ? Are they good ? In what situations are they good ? If so, can hyou give me an example?

Any available options of code above will be appreciated.

+2  A: 

If the functions belong to the class, logically, then they are fine that way.

A class should be cohesive and methods that do an operation normally should have the mirror operation defined as well (Subscribe/Unsubscribe, Add/Remove etc...).

You have named them well, as they are very descriptive of what they do - how would you name a merged one? It is better to leave them separate, as this way they are self documenting and will not confuse users of the class.

Oded
A: 

With the example you provided, they are related - but only because they may work with the same set of data or objects.

Personally i would NEVER merge these into a single function. While it may be more typing, it is easier both to read and to maintain to keep them separate. When either of those two functions are being called it is obvious what is going to happen - if you were to merge them then it becomes not so obvious. This is a simple example though - if you were to merge two functions that were more complicated then things could get very murky, and you could end up having unintended side effects from calling the merged function.

Remember KISS - Keep It Simple, Stupid :) For every function, try and follow SRP - Single Responsibility Principle. While Wikipedia talks about SRP at the class/object level, there is no reason to not also apply it at the function level where practicable.

slugster
A: 

dont merge them, make an interface that will force you implement both methods

 interface ISubscriber
 {
        void Subscribe();
        void Unsubscribe();
 }
Kikaimaru
Why are you recommending an interface? Can you elaborate on the relevance of an interface to the question?
Oded