Question
I’m currently working a on an assignment for school. The assignment is to create a puzzle/calculator program in which you learn how to work with different datastructures (such as Stacks). We have generate infix math strings suchs as “1 + 2 * 3 – 4” and then turn them in to postfix math strings such as “1 2 + 3 * 4 -“.
In my book the author creates a special class for converting the infix notation to postfix. I was planning on using this but whilst I was about to implement it I was wondering if the following is what you would call “high coupling”. I have read something about this (nothing that is taught in the book or anything) and was wondering about the aspect (since I still have to grasp it).
Problem
I have created a PuzzleGenerator class which generates the infix notation of the puzzle (or math string, whatever you want to call it) when it’s instantiated. I was going to make a method getAnswer() in which I would instantiate the InToPost class (the class from the book) to convert the infix to postfox notation and then calculate the answer. But whilst doing this I thought: “Is using the InToPost class inside this method a form a high coupling, and would it be better to place this in a different method?” (such as a “convertPostfixToInfix” method, inside the PuzzleGenerator class)
Thanks in advance.
No, it would not be high coupling — no more than to use any library class within another class.
It is coupling, of course, because it’s a dependency. High coupling occurs when there are too many direct dependencies between classes and you lose the ability to recycle your code. For example, if you have a LogWriter
class which has only one method: Log( String )
, you may use a specific class for outputting a log, such as a file writing class.
The above would be high coupling because you can’t reuse the LogWriter
class in other output modes. The job of the LogWriter
class is to create log line and output them, not specifically log to the file system.
In that case it would be better to inject the dependency in the constructor, by passing it: you would have a LogWriter( OutputStream )
constructor which stores and reuses the stream to output the log.
Another possible way is to read a configuration file and compose the class from it using reflection.
4