Ruby - Relationship of Class/Objects/Methods - ruby

Pertaining to Ruby, can someone state the relationship between Class, Objects, and Methods in layman's terms? And maybe even give an analogy?
New to OOP and trying to grasp the concept.

note: OOP is independent of Ruby.
Classes are like recipes.
Objects are the actual food you prepare from a recipe.
Methods are ... don't really fit in this metaphor. But they are the behaviors an object can perform. Some might say methods are the messages an object will respond to.

A friend gave me this analogy:
"It's like a watch. The Class is the watch casing, it encompasses the inner workings of the watch (Objects and Methods). The hands are the Objects, they perform the function of the watch based on the movement of the gears (Methods). The gears and springs underneath the face are the Methods; they are the heart of the watch that make up the function of the hands (Objects). Without the gears (Methods) the hands (Objects) have no function. Without either of those, there's no need for the watch casing (Class) to exist."

Classes are your blueprints
Methods are your tools (to build, to modify, to adjust)
Objects are your buildings
Remember that your objects are your nouns (e.g. a building) ... methods are you verbs (e.g. is built)!!

Related

Is there a common convension to put new methods(on top or on bottom)?

If we omit visibility modifiers(let's say all methods are public), is there any common convension to put new methods in class? I mean if I put them on bottom it's logically correct, because methods are sorted by date. If I put them on top, it's easy to see and compare what methods are added if the class is very long.
Just depends on what you and your team are comfortable with. I usually have method at the top of my class followed by fields. If there are many method that do different thing you are better off organizing them in a new class. Now without seeing any code I'm simply guessing.
No, I don't think there is.
As Kalagen said it's up to you and your team to decide it.
I would keep any methods that share similar functionality together and keep the class definition short.
The short answer in my opinion is no. Coding style might vary depending on the language you are using and the team you are working with. In addition you might have your own preference as well. I tend to add new methods close to methods that are related to it (e.g. if method1 calls method2 then method1 is above method2). Then it is relatively easy to find the method that's being called. On the other hand, most IDEs can find the method with a mouse click.
If you're using version control, you can easily see what methods were added and in which order, so sorting by date is not needed.
And as others have mentioned, keep the class small. Take a look at the Single responsibility principle. If the methods you are adding are not related to the responsibility of the class, extract them and create a new class.

Organizing classes in Ruby script

I'm writing a small game. I have:
class MyGame
...
class_methods
a bit of game logic
end
# after my_game unwrapped code
putss
get.chomps
methods, loops (to be DRY)
interaction with user, returning values
Is there a correct approach to wrap code together? Is it correct to not wrap code after my_game class in any class or module, or should I always put my code in classes/modules?
I would wrap functionality in modules and classes, as there are some benefits to it:
a) you can easily write tests for code in classes (and for modules by including them in classes as mixins and testing the classes)
b) you have control over the visibility of functions/methods and you can actually create an interface in case you have a consumer of the game that needs to access something more than just the game class
c) it's easier to extend the functionality of parts of the game by creating new implementors of parts of the game's functionality
That said, there is no dogma on writing only in an Object Oriented way. In some cases (perhaps for scripts that will be used as command line scripts), just having some functions and code executing those functions might be enough (especially if the script is simple and short in general).
My advice regarding the structure of the little game you're building is to look for the interactions, the "verbs" that need to take place (ie the messages sent between objects) and then you'll come up with the classes that will send those messages (methods) and designing and structuring the game will get much easier I believe.
By the way, a good book that could help in the direction of designing software is the following:
http://www.amazon.com/Practical-Object-Oriented-Design-Ruby-Addison-Wesley/dp/0321721330
Hope the above help.

DDD Events and abstract base classes

I am currently working on implementing multiple events which share common properties and are basically the same: Templates. Our event provider applies several events like SomeTemplateAddedEvent and SomeOtherTemplateAddedEvent. There could possibly come more variations later, so I was thinking about implementing a base class for each TemplateAddedEvent since they all share common properties. But I am doubtful if this is the right way to go, since some people prefer events to be simple classes containing every property instead of having to dig deeper to find out what the event can provide.
I hope someone can shed some light on this subject.
Inheritance is normally used for two orthogonal reasons - to reuse functionality and to declare an "is-a" relationship between classes. It seems that you're using it for the first reason. This reason is a weaker argument because reuse can also be attained with composition. The question to ask then is whether there exists an "is-a" relationship between the events. Sometimes inheritance among events is desirable, such as when it makes sense to provide a handler for all events deriving from the base class.
Overall, I'd caution against inheritance if it is only applied to attain code reuse. If it is an appropriate statement about the domain, then it can make sense.

MVC - which methods should be in Model class except set/get members?

Should methods that manipulate the Model class members be implemented in the Model or in the Controller? Does it depend on how "heavy" this manipulation is ?
By "manipulation" I mean:
get a class member
make a long calculation based upon this class member
return another value which relates to this class
For example, a Board class which hold a cell matrix member.
Now I want to implement a method which returns all the surrounding cells according to specific cell location.
Is the model or view responsible to for implementing the above ?
If this question belongs to another Stack Exchange QA site I will welcome the recommendation to move my post to that site.
Keep your controllers thin, don't let them do much, this aligns with the Single Responsibility Principle in SOLID for Object Oriented Design. If you have fat controllers, they become hard to test and maintain.
As for the models, I used to have dumb models before that did nothing but to map to database tables and that was inspired by most of the sample applications that you see on the web, but now I don't do that.
I (try to) follow the principles from Domain Driven Design, where models (entities in DDD terms) are at the center of the application, they are expected to encapsulate behaviour related to the entity, they are smart models (so yes, the logic related to an object will live with it in that case). DDD is a much bigger topic and it is not related directly to MVC, but the principles behind it helps you better design your applications, there is a lot of materials and sample apps available if you google DDD.
Additionally, Ruby On Rails community - which seems to inspire most of MVC frameworks - also seems to have a hype around having Fat Models and Skinny Controllers.
On top of that, you can add View Models to your mix which I find helpful. In this case, you can have a ViewModel to represent a dumb subset of your model(s) just to use for generating the view, it makes your life easier and further separate your Views from your Models so that they don't affect your design decisions unnecessarily.
What you call "model" is are actually domain objects. The actual model in MVC is just a layer, not concrete thing.
In your particular example, the Board should have a method that returns this list. I assume, that you are actually acquiring it because you then need to do further interaction with those cells.
This is where the services within the model layer comes in to play. If you use them, they are the outer part of model layer and contain the application logic - interaction between different domain objects and the interaction between the persistence (usually either data mappers or units of work) and domain objects.
Let's say you are making a game, and you and player performs and AoE attack. Controller takes a hold of service, which is responsible for this functionality and sends a command: this player aimed AoE in this direction, perform it.
Service instantiates Board and asks for surrounding cells of the target location. Then it performs "damage" on every cell in the collection that it acquired. After the logic is done, it tell the Unit of Work instance to commit all the changes, that happened on the Board.
Controller does not care about the details of what service does. And it should not receive any feedback. When execution gets to the view, it request from model layer the latest changes and modifies the UI. As the added benefit - services let you stop the business logic from leaking in the presentation layer (mostly made up from views an controllers).
The domain object should contain only methods, that deal with their state.
I think this has little to do with MVC, and a lot more to do with regular software engineering.
I personally wouldn't hesitate to stick trivial calculations in a model, but would be extremely wary of fat models.
Now, the fact that MVC stands for Model View Controller doesn't necessarily mean that everything should be either a view, a model or a controller. If you feel the need to move responsibilities to a separate class that doesn't really qualify as an M, a V or a C, I don't see why you shouldn't do it.
The way you implement it is up to you. You could either use this separate class as a "top level" (for lack of a better term) object, or make a method of the model delegate to it, so as to hide the fact that you're using it. I would probably go for the latter.
Everything is debatable, though. Everybody and their sister seem to have a different opinion on how to do MVC right.
Me, I just consider it a guideline. Sure, it's a great idea because it leads you to a better separation of concern, but in the end—as it always happens—there's no one-size-fits-all way to apply it, and you should not be overly constrained by it, to the point where everything has to be either a view, a model or a controller.
As per best practice we should use properties for Calculated fields with get access only. example public double TotalCost {
get
{
return this.Role.Cost * TotalHour;
}
}

Is it normal to have a long list of arguments in the constructor of a Presenter class?

Warning acronym overload approaching!!! I'm doing TDD and DDD with an MVP passive view pattern and DI. I'm finding myself adding dependency after dependency to the constructor of my presenter class as I write each new test. Most are domain objects. I'm using factories for dependency injection though I will likely be moving to an IoC container eventually.
When using constructor injection (as apposed to property injection) its easy to see where your dependencies are. A large number of dependencies is usually an indicator that a class has too much responsibility but in the case of a presenter, I fail to see how to avoid this.
I've thought of wrapping all the domain objects into a single "Domain" class which would act as a middle man but I have this gut feeling that I'd only be moving the problem instead of fixing it.
Am I missing something or is this unavoidable?
Often a large number of arguments to a method (constructor, function, etc) is a code smell. It can be hard to understand what all the arguments are. This is especially the case if you have large numbers of arguments of the same type. It is very easy for them to get confused which can introduce subtle bugs.
The refactoring is called "Introduce Parameter Object". Whether that's really a domain object or not, it is basically a data transfer object that minimizes the number of parameters passed to a method and gives them a bit more context.
I only use DI on the Constructor if I need something to be there from the start. Otherwise I use properties and have lazy loading for the other items. For TDD/DI as long as you can inject the item when you need it you don't need to add it to your constructor.
I recommend always following the Law of Demeter and not following the DI myth of everything needs to be in the constructor. Misko Hevery (Agile Coach at Google) describes it well on his blog http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/
Having a Layer Supertype might not be a bad idea, but I think your code smell might be indicating something else. Geofflane mentioned the refactor pattern, Introduce Parameter Object. While it's a good pattern for this sort of problem, I'm not entirely sure it's the way to go for this situation.
Question: Why are you passing in Domain Model objects to the constructor?
There is such a thing as having too much abstraction. If there's one solid layer of code you should be able to trust, it's your Domain Model. You don't need to reference 3 IEntity objects when you're dealing with Customer, Vendor, and Product classes if those are part of your basic Domain Model and you don't necessarily need polymorphism.
My advice: Pass in application and domain services. Trust your Domain Model.
EDIT:
Re-reading the problem when it's not horribly late at night, I realize your "Domain class" is already the Introduce Parameter Object refactoring and not, in fact, a Layer Supertype, as I thought at 3AM.
I also realize that perhaps you need to reference the Model objects in the application code, outside the Presenter. Perhaps you're doing some initial setup of your Model objects before passing them in to the Presenter. If this is the case, your "Domain class" idea might be best. If there is some initial setup, when moving to an IoC, you'll want to look at something like Factory Support in Castle Windsor. (Other IoC containers have similar concepts.)

Resources