Purpose of instantiation of Service classes - ruby

I have repeatedly seen a Ruby pattern of initializing objects of Service classes, i.e. classes that have a singular "call" instance method and nothing else.
For example in the dry-validation gem (https://dry-rb.org/gems/dry-validation/1.8/schemas/) the contract class is initialized, then that instance is used for validation and never used again.
Same with other Service classes, I found multiple tutorials where it is used like ServiceClass.new(stuff).call().
I don't understand why to jump through the additional hoop of object initialization, when you can achieve the same behavior by simply defining a class method that does the job, like ContractClass.call(example: "hi") and ServiceClass.call(stuff) respectively.
Am I missing something here? Repeatedly initializing one-of objects seems completely pointless to me.

Related

Is Spring more suitable for business-logic-focused apps?

After reading the official doc of Spring, I got this impression:
"Spring, specifically its IoC container, suits better for apps that requires only one instance of most classes".
For example we have an online shopping app. Its business logic is divided into
Order process
Payment process
and encapsulating these two parts into classes is for better code organisation rather than for implementing any functionalities, and Spring makes it easier to inject the same instance to whichever object needs it, to avoid frequent and redundant new.
However, in a Mario-like game, we might have a class Coin that requires hundreds of individual instances, and hence Spring can't be applied in this case ('cause I think #qualifier makes more mess than the good part brought by IoC).
Is the above correct?
You're correct in thinking that you wouldn't inject an object that only applies in a narrow scope.
I could see objects with Request scope that are not Singleton. Spring has supported that from the beginning.
Method scope variables should not be under Spring's control. There's nothing wrong with calling new.
You should understand Spring better before you make judgements about its efficacy.

How to disable this error in ES6? error: Can't reference 'this' before calling super in derived class constructors

In object-oriented languages like C++ you don't have to call the base constructor. I don't understand why I need to do it in a psuedo object-oriented language like javascript. My base constructor has virtual elements that need to be setup before I call it. Constructors worked fine in ES5, why ruin them with this restriction. This error is garbage, it should be removed.
In C++ the compiler creates code to call the base constructor for you before your derived class constructor is called. Your C++ derived class definition can specify which base constructor to call and what to pass it (if there is a choice).
That's how the C++ specification is written. See short explanation here.
Javascript ES6 classes do not work the exact same way. You have to insert a place in your code where the base constructor is called with super(...) and you can specify or compute the parameters to pass to the base constructor.
In both C++ and Javascript, you can't access your own instance methods or properties before the base constructor has been called.
FYI, Java is even more restrictive than Javascript. You must put a call to super() or this() as the first statement of your constructor. Javascript at least lets you put logic that doesn't use this before calling the constructor.
In your Javascript, you can't stop this error without rewriting your code to work a different way. It's not an error you can disable.
There are valid OOP reasons (whether you agree with them or not) to not allow references to an object until all base classes have been fully initialized. Or, you can go back to the pre-ES6 way of initializing objects where there are no controls on how you do things and you can do whatever you want.
If you show us your code and explain what you're trying to do, we can likely suggest a different design that solves your problem and does not have this issue.

Is there a usable rendering context in sinatra/padrino?

I am attempting to use the Exhibit pattern in a padrino application but to do so properly I need to access the rendering context. That is, I need to have some object context such that calling something along the lines of context.render('accounts/index') will produce identical output to when render 'accounts/index' is called from inside a controller (assuming that all variables are set the same and that app/views/accounts/index.erb is a template file).
I can't find anything that does this within the padrino public API, so I attempted to dig deeper. The existing render method in the controller wraps sinatra's render method, which is a private instance method. So it's not obviously not defined on the class MyApp (i.e. the Padrino::Application subclass). MyApp.new results in an instance of Rack::Session::Cookie rather than of itself, and none of the padrino methods that I can find return the existing instance of the app, which would be a suitable candidate for the context object if I called its private render method.
Is this something that's just inherently too difficult to bother with given sinatra's and padrino's designs, or is there something that I'm missing here?
I realise that the answer was in the Objects on Rails book if only I'd kept reading. I needed to pass the context explicitly from within the template: exhibit(object, self) inside the template causes the template's rendering context to be passed as the second argument. Of course.
I guess this really wasn't specific to padrino after all and I was looking for something complicated when the answer was very simple.

The Class/Object Paradox confusion

In the book The Well Grounded Rubyist (excerpt), David Black talks about the "Class/Object Chicken-and-Egg Paradox". I'm having a tough time understanding the entire concept.
Can someone explain it in better/easier/analogical/other terms?
Quote (emphasis mine):
The class Class is an instance of itself; that is, it’s a Class
object. And there’s more. Remember the class Object? Well, Object
is a class... but classes are objects. So, Object is an object. And
Class is a class. And Object is a class, and Class is an object.
Which came first? How can the class Class be created unless the
class Object already exists? But how can there be a class Object
(or any other class) until there’s a class Class of which there can
be instances?
The best way to deal with this paradox, at least for now, is to ignore
it. Ruby has to do some of this chicken-or-egg stuff in order to get
the class and object system up and running—and then, the circularity
and paradoxes don’t matter. In the course of programming, you just
need to know that classes are objects, instances of the class called
Class.
(If you want to know in brief how it works, it’s like this: every
object has an internal record of what class it’s an instance of, and
the internal record inside the object Class points back to Class.)
You can see the problem in this diagram:
(source: phrogz.net)
All object instances inherit from Object. All classes are objects, and Class is a class, therefore Class is an object. However, object instances inherit from their class, and Object is an instance of the Class class, therefore Object itself gets methods from Class.
As you can see in the diagram, however, there isn't a circular lookup loop, because there are two different inheritance 'parts' to every class: the instance methods and the 'class' methods. In the end, the lookup path is sane.
N.B.: This diagram reflects Ruby 1.8, and thus does not include the core BasicObject class introduced in Ruby 1.9.
In practical terms, all you need to understand is that Object is the mother of all classes. All classes extend Object. It is this relationship that you will use in programming, understanding inheritance and so forth.
Eg; You can call hash() on any instance of any object at any time? Why? Because that function appears in the Object class, and all classes inherit that function, because all classes extend Object.
As far as the idea of Class goes, this comes up much less frequently. An object of class Class is like a blueprint, it's like having the class in your hands, without creating an instance of it. There's a little more to it, but it's a difficult one to describe without a lengthy example. Rest assured, when (if ever) the time comes to use it, you'll see it's purpose.
All this excerpt is saying is that Object has a class of type Class and Class is an object, so must extend Object. Its cyclic, but it's irrelevant. The answer is buried somewhere in the compiler.
Regarding the which-came-first criterion, there are two kinds of Ruby objects:
Built-in objects. They exist at the start of a Ruby program and can be considered to have zero creation time.
User created objects. They are created after the program starts via object creation methods (new/clone/dup, class-definition, module-definition, literal-constructs, ...). Such objects are linearly ordered by their time of creation. This order happens to inversely correspond to class-inheritance and instance-of relations.
A detailed explanation of the Ruby object model is available at www.atalon.cz.
I know that my answer comes at least 3 years late, but I have learned about Ruby quite recently and I must admit that the literature sometimes presents (in my opinion) misleading explanations, even though one is handling a very simple problem. Moreover, I am (and was) surprised by such appalling phrases as:
"The best way to deal with this paradox, at least for now, is to ignore it."
stated by the author D. Black, and quoted in the question, but this attitude seems to be pervasive. I have experienced this tendency within the physics community but I have not suspected it had also spread through the programming one. I am not stating that nobody understands what is lurking behind, but it seems at least intriguing why not providing the (indeed) very simple and precise answer, as in this case there is one, without invoking any obscure words such as "paradox" within the explanation.
This so-called "paradox" (even though it is definitely NOT such thing) comes from the (at least misleading) belief that "being an instance of (a subclass of)" should be something as "being an element of" (in, say, naive set theory), or in other terms, a class (in Ruby) is the set containing all the objects sharing some common property (for instance, under this naive interpretation the class String includes all the string objects). Even though this naive point of view (which I may call the "membership interpretation") may help understanding isolated (and rather easy) classes such as String or Symbol, it indeed PRODUCES A CLEAR CONTRADICTION with our naive understanding (and also the axiomatic one, for it contradicts Von Neumann's regularity axiom of set theory, if someone knows what I am talking about) of the membership relationship, for an object could not be an element of itself, as the previous interpretation implies when regarding the object Class.
The previously stated problem is easily avoided if one gets rid of such misleading membership interpretation with a very simply minded model as follows.
I would have guess that my following explanation is well-known by the experts, so I claim no originality at all, but perhaps it was not rephrased in the (simple) terms I am going to present it: in some sense I am completely astonished that (apparently) nobody stated in these terms from the very beginning, and my intention is just to highlight what I believe is the basic underlying structure.
Let us consider a set O of (basic) objects, which consists of all the (basic) objects Ruby has, provided with a mapping f from O to O (which is more or less the .class method), satisfying that the image of the composition of f with itself has only one element.
This latter element (or object) is denoted Class (indeed, what you know to be the class Class).
I would be tempted to write this post using LaTeX code but I am not quite sure if it will be parsed and converted into typical math expressions.
The image of the mapping f is (by definition) the set of Ruby classes (e.g. String, Object, Symbol, Class, etc).
Ruby programmers (even though if they do not know it) interpret the previous construction as follows: we say that an object "x is an instance of y" if and only if y = f(x). By the way this tells us you exactly that Class is an instance of Class (i.e. of itself).
Now, we would need much more decorations to this simple model in order to get the full Ruby hierarchy of classes and functionality (imposing the existence of some fixed members on the image of the map f, a partial order on the image of the map f in order to define subclasses to get afterwards inheritance, etc), and in particular to get the nice picture that was interestingly upvoted, but I suppose that everybody can figure this out from the primitive model I gave (I have written some pages explaining this for myself, after having read several Ruby manuals. I may provide a copy if anybody finds it useful).
Which came first: The class Class or the class Object?
Every class is an instance of the class Class. It follows that the class Object is an instance of the class Class. So you need the class Class to create the class Object. Therefore:
The class Class exists before the class Object.
The class Class is a subclass of the class Object. So you need the class Object from which the class Class can be created. Therefore:
The class Object exists before the class Class.
So statement-2 conflicts with statement-1 and so we have our chicken & egg dilemma. Or you can just accept it as a circular definition!
I have done a dig into the source code of Ruby and created this post on how to make sense of it.

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