Skip to content

Instantly share code, notes, and snippets.

@metasansana
Created July 2, 2013 22:00
Show Gist options
  • Save metasansana/5913619 to your computer and use it in GitHub Desktop.
Save metasansana/5913619 to your computer and use it in GitHub Desktop.
No setters please (unless necessary).
//One of the popular concepts in OOP style programming is the concept of loose coupling.
//Your objects should have everything they need to carry out their duties from the time you instansiate them (new Object).
//Failing that, you should be able to inject any missing dependecies into your classes whenever necessary.
//This does not mean you go and create a whole bunch of setters.
//Wrong!
dog = new Animal();
dog.setColor('blue');
dog.setMood('Angry');
dog.setHeight('tall');
//This obviously leads to tedious and longer source code files, which nobody likes.
//Instead let's try this, think about the design of this class. What does it do? Can you explain that in one sentance without using and? How will this class be used?
//Well, we can say in this case that Animal class represents an Animal in a pet shop. Animals in petshops have ceartin attributes about them that
//we keep track of (color, mood, height etc).
//Ok well let's try this:
dog = new Animal(new AngryMood, new Color('#fff000'), new Dimenson(12,24)); //When we instansiate the animal class we give it what it needs early.
//While this is not the best design possible it eliminates the need for setters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment