1

How can I refactor the code below as OOP?

I don't expect you to give me a full re-write here, rather I am seeking advice on how to approach and convert my code into OOP.

This is something new to me. If you can just show the thought process behind and perhaps just add an initial code refactor, I'll start studying and implementing it further. Insights on best practices are welcome as well.

$(function() {
$.ajax({
    type: "GET",
    url: "/data",
    success: res => {
        console.log(res);
        let data = res;
        //console.log(data.guests[0].firstName);

        let Greeting = () => {

            let getFirstName = data.guests.map(name => name.firstName);
            let getHotelName = data.hotels.map(name => name.company);
            let getRoomNumber = data.guests.map(number => number.reservation.roomNumber);

            let handleSubmit = () => {
                $("#form").submit(function(e) {
                    e.preventDefault();
                    let room = $('#selectRoom').val();
                    let name = $('#selectName').val();
                    let hotel = $('#selectHotel').val();
                    let greetGuest = `${time} ${name} and welcome to ${hotel} your ${room} is now ready for you. Enjoy your stay, let us know if you need anything.`;
                    console.log(greetGuest);
                    //append to Dom
                    $('#message').append(greetGuest);
                });
            };
            handleSubmit()

        };
        Greeting();
    }, //success ends
    error: err => console.log(err)
});
});
14
  • 2
    This is more of a code review question than a Stack Overflow question. Commented Oct 1, 2017 at 14:03
  • 1
    Personally I don't recommend OOP for javascript. It can be useful in some cases, but in general it just leads to extra boilerplate and a Functional Programming style is more suitable. Commented Oct 1, 2017 at 14:27
  • 2
    Where do you think do you can you apply OOP here, and why do you think you need it? The code already uses objects all over the place, where they are suitable. Commented Oct 1, 2017 at 14:47
  • 2
    @DuncanThacker You cannot really avoid objects in JS. You can (and should) avoid the "put everything into a class" mentality of Java, but there's nothing wrong with functional OOP in general. Commented Oct 1, 2017 at 14:49
  • 1
    I'd suggest you study the basic concepts of object oriented programming. Reading the equivalent of a few chapters of a book in online resources should familiarize yourself with the basic concepts. OOP is about recognizing situations that lend themselves to OOP, not about forcing a given problem into an OOP design. We can't really teach you OOP here, nor is your particular code snippet particularly appropriate for a new and OOP design. If this is working code here, then you can post at codereview.stackexchange.com to see if people have suggestions for how to improve it. Commented Oct 1, 2017 at 16:23

1 Answer 1

4

The whole point of OOP is to encapsulate functionality into objects, such that each object has a specific set of properties and behavior attached to it. The provided snippet can be modified to have a Greeting class that has a handleSubmit method with the properties described inside the arrow function of the AJAX callback. However, based on the layout, you'd probably only have an instance, essentially making OOP useless here.

You perform an AJAX request which fetches all the data for each greeting. You then map the data into separate arrays that each have specific per-guest data. If you really want to use classes, this can be refactored into something like:

class HotelGuest {
  constructor(a, b, c) {
    this.firstName = a;
    this.hotelName = b;
    this.roomNum = c;
  }

  // Add ${time} as necessary, because I only see it once and do not know its purpose
  get greeting(){
    return this.firstName + " and welcome to " + this.hotelName +
      " your " + this.roomNum + " is now ready for you. Enjoy your stay, let us know if you need anything.";
  }
}

var guestsInfo = [];

$(function(){
  $.ajax({
    type: "GET",
    url: "/data",

    success: data => {
      data.guests.forEach((guest, i) => guestsInfo.push(new HotelGuest(guest.firstName, data.hotels[i].company, guest.reservation.roomNumber)));
    },

    error: err => console.log(err)
  });
});

All of the guests and important info can be found into guestsInfo. Each element follows the layout of the HotelGuest class. To get a guest's greeting, just access the .greeting property. It'll change based on the guest's data.

For more information on classes and their syntax in ES6, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.