Search code examples
oopdecouplingcoupling

Public static data used throughout program


Code examples are C# but this is a general OO question.

I know according to OO rules, class coupling should be minimised and members should be kept private wherever possible, etc.

Consider this example:

You are writing an esoteric program which has some sort of data set (I'm not talking about System.Data.DataSet) which is used in literally every facet of the program. In fact, the program basically exists just to load, display, manipulate, and save the data set. Furthermore, there can only ever be one data set loaded at any time, and it is loaded when the program opens.

If we follow OO rules strictly, we would have

public void ShowSomeGraphs(IData data)
{
  // do stuff with data which implements IData
}

however we could potentially store a public static Data member in Program, for example.

public void ShowSomeGraphs()
{
  // do stuff with Program.Data
}

On one hand, we have traded a slightly shorter function signature for vastly increased class coupling. On the other hand, we are no longer passing a Data parameter to practically every function, everywhere.

The right answer probably is: Avoid class coupling wherever possible. The local Data variables are just pointers so the memory overhead is negligible, and because the classes are decoupled they can be used elsewhere at a later date.

Though realistically speaking, the structure of the Data class will likely be phenomenally different in a different application, so it's not like you can just pull a class from this program and drop it in somewhere else without any tweaks. The extra time and effort required to write the classes in such a way that they can just be dropped in might be difficult to justify to a stakeholder.

I'm working on this sort of program now, and I have used the OO-canon approach: Data parameters are passed around where needed I have minimised class coupling with an IData interface to generalise the data set for future code re-use. Given the application, I'm almost certain this code won't ever be re-used. Without these extra interfaces and abstraction, the program would have worked exactly the same as far as the end user is concerned, but would have represented significantly less headaches and development time for me.

What do you think about this? Do you think it's justifiable to spend all the extra time to write the interfaces and generalisations to ensure classes are decoupled where possible, especially when you can't see the classes being use elsewhere later?


Solution

  • Don't agonise over it. Seriously.

    Software paradigms/patterns are there to help us and not to be followed dogmatically.

    You make it clear in your question that you consider the loose coupling overkill, and you can justify why. Therefore, don't use it.