Intro to Classes

Our journey towards object oriented design took another step forward this week with a dive into classes. Up until now we've used methods to solve challenges so our solutions have been somewhat procedural. Classes open up a new world of possibilities!

Let's start with some basics. Classes are blueprints to create objects. Those objects will have state and behavior. Classes are going to define state through instance variables and behavior through instance methods. Let's try to emulate a real world scenario and create objects that will make us some coffee.

Our Brew class is initialized with two arguments - grounds and brew_type. For this example, I used keyword arguments to add some clarity within the method call. We are passing an instance variable brew_type to define the coffee brewing technique (e.g. Drip, French Press, V60) in order to make our class somewhat extensible. When we call Brew.new this created an instance of the Brew class so we've given our object state. Let's create a brew method to give some behavior.

Within our Brew class we created an instance method brew which uses the instance variable brew_type to call our V60 class. We pass the instance variable grounds to V60 and call that instance method make_coffee. There's more work needed to fully build this out but you can start seeing how classes can work together while keeping responsibilities separate.

Last but not least, attr_reader is a ruby shortcut for creating wrapper methods for instance variables. Instance variables start with an '@' sign which allows them to be accessed from anywhere within the class. By using attr_reader in our Brew class, the brew method was able to access the instance variable grounds without using the @ sign. When the brew method calls grounds it's actually calling the grounds method because attr_reader automatically created: