Daily Chat Thread - December 18, 2018

I recently gave an onsite interview for a fresh grad position. One of the questions was a question about optimizing code of a badly written app.

Because I am a fresh grad with little to no experience when it comes to actual software development I was hoping someone who is more experienced could please clear a doubt for me.

The question was as follows:

  • I had 2 classes.
  • Class 1 was a singleton for the database connection and got 2 items - X, Y from a database. Both these items had getters and setters.
  • Class 2 is a regular class that gets instance of class 1. It uses the instance to get the items X, Y
  • Class 2 performed certain operations based on the X, Y values (if X and Y are not null, do something; if X is null but Y is not null do something else and so on)
  • How can I refactor the code to make it better and how would I test the code?

I think I did the general optimization of the code properly (making sure it was thread safe etc). However I am not sure about optimizing the code for unit testing.

My answer was that I would create an interface and class 1 implements the interface. I also created a mock class which mimics class 1 that implemented the same interface (but this was not a singleton and it only had 2 values publicly exposed so no db connection) and I then used this mock class to write and implement unit tests.

Is my approach correct? If not can you please tell me how you would solve it? I am sorry I cannot go into specifics about the question or about the company that interviewed me because of ethical reasons.

/r/cscareerquestions Thread