What conclusion should we draw from this example?

I can’t understand what’s going on here? Who knows what needs to be done here?

Follow the instructions that are given…

Use the class keyword to create a Thermostat class. The constructor accepts a Fahrenheit temperature.

class Thermostat {
  constructor (fahrenheit) {
     this._fahrenheit = fahrenheit;
  }
}

In the class, create a getter to obtain the temperature in Celsius and a setter that accepts a temperature in Celsius.
Remember that C = 5/9 * (F - 32) and F = C * 9.0 / 5 + 32, where F is the value of temperature in Fahrenheit, and C is the value of the same temperature in Celsius.

class Thermostat {
  constructor (fahrenheit) {
     this._fahrenheit = fahrenheit;
  }
  get temperature() {
    return 5/9 * (this._fahrenheit - 32);
  }
  set temperature(updatedtemp) {
    this._fahrenheit = updatedtemp * 9/5 + 32;
  }
}

This is admittedly a little awkward because while this is a training exercise, logically, it’s a bad example. The initial constructor takes a temperature in Fahrenheit but then all the other interactions are Celcius.

In this instance, I wouldn’t have built a constructor like this, and I would have two getters and two setters, one for each temperature scale, but that’s just me.

2 Likes

I look at this code, it is very complex and incomprehensible, I think it would be clearer to describe it in a regular function than to write some class with an incomprehensible constructor with incomprehensible getas and sets, since it all looks very complicated, I think

It’s complex because it’s a different approach - OOP instead of functional. They are two completely different approaches, and each have their merits.

OOP deals with objects and all the things that can be done to the objects. Functional deals with doing stuff, full stop.

Functional is great when you need to do simple things to simple groups of things. What a button does when it’s pressed, that kind of thing…

OOP is a completely different way of thinking. It looks at things from an object focus. How can that object be described (properties)? What kinds of things would want to be done to or known about an object (methods)? An example would be a user for a website. A user has a username, password, email address and maybe a timezone they live in. Those are properties that can be described about a user. A method that could be added to a user object would be to decide how to greet them each time they logged in. If I would access the site, it might say good morning, but for Paul who lives in Europe, it might say good afternoon or even good evening because of the timezones. So it’s using something that describes a user to do something else. Those are methods.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.