When to use Seaside components, and when to use simple render objects? - smalltalk

I have been developing a web application in Seaside+Squeak recently, and have found it to be a wonderful experience. Seaside really is head and shoulders above every other framework out there, and I feel as though I am working at a higher level of abstraction (above the HTTP request/response cycle and HTML templating that other frameworks make you deal with).
That said, I'm a little confused about Seaside components. I recently had to display a list of objects on a component (similar to the stackoverflow front page). At first I made each object a component (a subclass of WAComponent), but this proved to be really wasteful, and I had to set #children dynamically in the parent component for it to work at all. I then tried making them render objects (objects that aren't subclasses of WAComponent, and render using renderOn: instead of renderContentOn:, like components do). This worked, but now they could no longer access global state in the session object as components can (using #session). Then I discovered "WACurrentSession value", which gives any object access to the current Seaside session object. I was now able to make them render objects. In addition, I discovered that I could rewrite a lot of my other, more minor components as render objects, too.
Besides needing call/answer or backtracking state, what other reasons are there for using components over render objects?

This is a frequent point of confusion for new Seaside users. We have tried hard to make this clearer in Seaside 2.9, which is currently in Alpha, but I will try to focus on 2.8 here since it sounds like that is what you are using.
First of all, you are correct that you do not need to use a Component in order to access the Session. Seaside 2.9 moves #session up to a new class WAObject which makes it accessible to almost all Seaside objects (including Components) but you can definitely refer to WACurrentSession yourself for now in 2.8.
Components provide roughly the following functionality in 2.8:
#renderContentOn: is called with an instance of whatever renderer class you specify in #rendererClass (instead of whatever renderer is in use when your object is asked to render itself)
A hook (#updateUrl:) to allow updating the URL used by the renderer to generate links
Hooks (#updateRoot:, #style, #script) to allow updating the HEAD section of the HTML document
The ability to be the root of an Application
Hooks (#updateStates:, #states) to make state backtracking easier
A hook (#initialRequest:) to allow initialization based on the request that caused the Session to be created
A facility (#children) to make sure all components below you will also have the above hooks called on them
The ability to add Decorations
The ability to show/answer/call (uses Decorations)
Some convenience methods (#inform:, #isolate:, etc)
If you don't need any of the above, you don't need a Component. If you need any of the above, you pretty much do need a Component unless you want to implement the equivalent functionality on your own class.
The simplest metric is probably: if you intend to keep the object around between HTTP requests it should be a Component; if you intend to throw the object away and create it on each rendering pass it probably doesn't need to be. If you imagine an application that was displaying blog pages, you'd probably have Components for a menu, a blog roll, the blog body, each comment, and so on. You might want to factor out the reading of the blog's markup and generation of its HTML so that you could support different markups or different renderers and so that the comment Components could support the same markup. This could be done with a non-Component class that implements #renderOn: and could be created and used by other Components as needed.
Seaside 2.9 currently splits up the above functionality by making WAPresenter concrete and introducing WAPainter as its superclass. 1-3 above are implemented on WAPainter and 4-7 on WAPresenter so you have your choice of what to subclass depending on your needs. It also removes a lot of methods from WAPresenter and WAComponent in an effort to make them easier for end users to understand.
Hope that helps.

Related

What is a good pattern to access other components' states?

I encounter a situation where component A needs to know about the state of component B when A is asked to perform certain actions (for example, if edit menu is toggled, the save action on the save button should not be performed). My application is structured like a tree with nested components.
I have tried passing all the components I need into the constructor of other components. I find this quite tedious whenever I add more component to the application, I have to pass them all the way down. Furthermore, some components are instantiated under the same constructor, but they need to know about each other. I cannot pass say component A and B into each other since I need to instantiate them in order.
I have also tried using event system to signal between components. (Observer pattern ?) It seems to be more of an overkill and not intended to be used like this.
3rd thing I try is to use singleton through dependency injection. Components register themselves on init to the provider and the provider can be injected to provide access to other components.
The 3rd approach is the most effortless and it is working for me. But I google that Singleton is not a recommended approach since it is just global variable and it entangles the code. But Unity game engine seems to have the same thing ( FindComponentByTag ). What is the general practice for this ?
The standard pattern for handling things like this is MVC (Model View Controller) which usually makes use of the Observer pattern. Components (I guess that you are having GUI components in mind) should not directly access the state of other components. Instead, state should be handled by the model. The components that need to know about the state are registered as observers of the model.

where does a library like Fractal belong?

I was looking into Fractal (tldr : data object/collection to json formatting library) today and saw some benefits to using it. However it's functionality seems to span across multiple layers of the app I'm working on. Hence a question appeared -- where does a code utilising Fractal belong to? Model, service, controller, some other place? The examples given in the documentation at the project docs seem to favour putting it in the controller or right in a route callback (more complex examples seem to be coming from Laravel app and the author mentioned it in his book on API).
My concern is coupling -- if I put it in the controller, as most of the usage examples show, then I'm pretty much bound to it in the future. My first instinct is to abstract it a little, make that abstraction bound to a contract and then put it to use. Might sound over engineered, but the API I'm working on "is aspiring" to be JSON-API compliant, so exchanging such a "json formatter" for something else sounds less crazy. Besides I still need to format error messages and Fractal seems no to touch that at all.
I'd like to take advantage of support for Eloquent's paginator and embedded resources, because that's always a pain. Only doing that makes it awkward (to say the least) at presentation/control layer. Even in the Fractal docs they resort to adding some extra methods to the controller class to prep Fractal objects. It seems a bit weird to me, but maybe it's just me. That's why take it here.
I'm aware that it might be a matter of preference, but I'm counting on somebody to have a reasonably sounding one :). Or perhaps a better solution altogether, keeping in mind that automation and json-api compliance are key reasons.
I did this once with an API class for a proprietary system with which my application needed to interface. The API returned objects that looked a lot like models, so I implemented a number of classes for the objects I needed and implemented a library to make the API calls and return the objects. Luckily, I only needed read access to the API, so my library implements only a small subset of the actions available.
Maybe you could abstract all the functionality you need (both Fractal and any Eloquent features) into a library class for which you have defined an interface. That way all the Fractal code is in one place and if you ever need to replace it, you just rewrite your custom library class (which might be a lot of work, but probably better than hunting down references to Fractal sprinkled throughout your code).

What are Smalltalk pragmas conceptually?

I have used pragmas in Pharo Smalltalk and have an idea about how they work and have seen examples for what they are used in Pharo.
My questions are:
what are pragmas conceptually,
to what construct do they compare in other languages,
when should i introduce a pragma?
I already found an interesting article about their history: The history of VW Pragmas.
You must think of it as Annotations attached to a CompiledMethod, or if you want as additionnal properties.
Then, thanks to reflection, some tools can walk other compiled methods, collect those with certain annotations (properties) and apply some special handling, like constructing a menu, a list of preferences, or other UI, invoking every class methods marked as #initializer, or some mechanism could be walking the stack back until a method is marked as an #exceptionHandler ...
There are many possibilities, up to you to invent your own meta-property...
EDIT
For the second point, I don't know, it must be a language that can enumerate the methods, and can attach properties to them.
The third point is also hard to answer. In practice, I would say you would use some already existing annotations, but very rarely create a new one, unless you're trying to create a new framework for exception handling, or a new framework for GUI (you want to register some known events or some handlers...). The main usage I would see is for extending, composing an application with unrelated parts, like a main menu. It seems like a relatively un-intrusive way to introduce DECLARATIVE hooks - compared to the very intrusive way to override a well known method TheWorld>>mainMenu. It's also a bit lighter than registering/un-registering IMPERATIVELY via traditional message send at class initialization/unoading. On the other hand, the magic is a bit more hidden.

Communication in component-based game engine

For a 2D game I'm making (for Android) I'm using a component-based system where a GameObject holds several GameComponent objects. GameComponents can be things such as input components, rendering components, bullet emitting components, and so on. Currently, GameComponents have a reference to the object that owns them and can modify it, but the GameObject itself just has a list of components and it doesn't care what the components are as long as they can be updated when the object is updated.
Sometimes a component has some information which the GameObject needs to know. For example, for collision detection a GameObject registers itself with the collision detection subsystem to be notified when it collides with another object. The collision detection subsystem needs to know the object's bounding box. I store x and y in the object directly (because it is used by several components), but width and height are only known to the rendering component which holds the object's bitmap. I would like to have a method getBoundingBox or getWidth in the GameObject that gets that information. Or in general, I want to send some information from a component to the object. However, in my current design the GameObject doesn't know what specific components it has in the list.
I can think of several ways to solve this problem:
Instead of having a completely generic list of components, I can let the GameObject have specific field for some of the important components. For example, it can have a member variable called renderingComponent; whenever I need to get the width of the object I just use renderingComponent.getWidth(). This solution still allows for generic list of components but it treats some of them differently, and I'm afraid I'll end up having several exceptional fields as more components need to be queried. Some objects don't even have rendering components.
Have the required information as members of the GameObject but allow the components to update it. So an object has a width and a height which are 0 or -1 by default, but a rendering component can set them to the correct values in its update loop. This feels like a hack and I might end up pushing many things to the GameObject class for convenience even if not all objects need them.
Have components implement an interface that indicates what type of information they can be queried for. For example, a rendering component would implement the HasSize interface which includes methods such as getWidth and getHeight. When the GameObject needs the width, it loops over its components checking if they implement the HasSize interface (using the instanceof keyword in Java, or is in C#). This seems like a more generic solution, one disadvantage is that searching for the component might take some time (but then, most objects have 3 or 4 components only).
This question isn't about a specific problem. It comes up often in my design and I was wondering what's the best way to handle it. Performance is somewhat important since this is a game, but the number of components per object is generally small (the maximum is 8).
The short version
In a component based system for a game, what is the best way to pass information from the components to the object while keeping the design generic?
We get variations on this question three or four times a week on GameDev.net (where the gameobject is typically called an 'entity') and so far there's no consensus on the best approach. Several different approaches have been shown to be workable however so I wouldn't worry about it too much.
However, usually the problems regard communicating between components. Rarely do people worry about getting information from a component to the entity - if an entity knows what information it needs, then presumably it knows exactly what type of component it needs to access and which property or method it needs to call on that component to get the data. if you need to be reactive rather than active, then register callbacks or have an observer pattern set up with the components to let the entity know when something in the component has changed, and read the value at that point.
Completely generic components are largely useless: they need to provide some sort of known interface otherwise there's little point them existing. Otherwise you may as well just have a large associative array of untyped values and be done with it. In Java, Python, C#, and other slightly-higher-level languages than C++ you can use reflection to give you a more generic way of using specific subclasses without having to encode type and interface information into the components themselves.
As for communication:
Some people are making assumptions that an entity will always contain a known set of component types (where each instance is one of several possible subclasses) and therefore can just grab a direct reference to the other component and read/write via its public interface.
Some people are using publish/subscribe, signals/slots, etc., to create arbitrary connections between components. This seems a bit more flexible but ultimately you still need something with knowledge of these implicit dependencies. (And if this is known at compile time, why not just use the previous approach?)
Or, you can put all shared data in the entity itself and use that as a shared communication area (tenuously related to the blackboard system in AI) that each of the components can read and write to. This usually requires some robustness in the face of certain properties not existing when you expected them to. It also doesn't lend itself to parallelism, although I doubt that's a massive concern on a small embedded system...?
Finally, some people have systems where the entity doesn't exist at all. The components live within their subsystems and the only notion of an entity is an ID value in certain components - if a Rendering component (within the Rendering system) and a Player component (within the Players system) have the same ID, then you can assume the former handles the drawing of the latter. But there isn't any single object that aggregates either of those components.
Like others have said, there's no always right answer here. Different games will lend themselves towards different solutions. If you're building a big complex game with lots of different kinds of entities, a more decoupled generic architecture with some kind of abstract messaging between components may be worth the effort for the maintainability you get. For a simpler game with similar entities, it may make the most sense to just push all of that state up into GameObject.
For your specific scenario where you need to store the bounding box somewhere and only the collision component cares about it, I would:
Store it in the collision component itself.
Make the collision detection code work with the components directly.
So, instead of having the collision engine iterate through a collection of GameObjects to resolve the interaction, have it iterate directly through a collection of CollisionComponents. Once a collision has occurred, it will be up to the component to push that up to its parent GameObject.
This gives you a couple of benefits:
Leaves collision-specific state out of GameObject.
Spares you from iterating over GameObjects that don't have collision components. (If you have a lot of non-interactive objects like visual effects and decoration, this can save a decent number of cycles.)
Spares you from burning cycles walking between the object and its component. If you iterate through the objects then do getCollisionComponent() on each one, that pointer-following can cause a cache miss. Doing that for every frame for every object can burn a lot of CPU.
If you're interested I have more on this pattern here, although it looks like you already understand most of what's in that chapter.
Use an "event bus". (note that you probably can't use the code as is but it should give you the basic idea).
Basically, create a central resource where every object can register itself as a listener and say "If X happens, I want to know". When something happens in the game, the responsible object can simply send an event X to the event bus and all interesting parties will notice.
[EDIT] For a more detailed discussion, see message passing (thanks to snk_kid for pointing this out).
One approach is to initialize a container of components. Each component can provide a service and may also require services from other components. Depending on your programming language and environment you have to come up with a method for providing this information.
In its simplest form you have one-to-one connections between components, but you will also need one-to-many connections. E.g. the CollectionDetector will have a list of components implementing IBoundingBox.
During initialization the container will wire up connections between components, and during run-time there will be no additional cost.
This is close to you solution 3), expect the connections between components are wired only once and are not checked at every iteration of the game loop.
The Managed Extensibility Framework for .NET is a nice solution to this problem. I realize that you intend to develop on Android, but you may still get some inspiration from this framework.

Are tag (or "marker") interfaces obsolete?

I'm trying to help a coworker come to terms with OO, and I'm finding that for some cases, it's hard to find solid real-world examples for the concept of a tag (or marker) interface. (An interface that contains no methods; it is used as a tag or marker or label only). While it really shouldn't matter for the sakes of our discussions, we're using PHP as the platform behind the discussions (because it's a common language between us). I'm probably not the best person to teach OO since most of my background is highly theoretical and about 15 years old, but I'm what he's got.
In any case, the dearth of discussions I've found regarding tag interfaces leads me to believe it's not even being used enough to warrant discussion. Am I wrong here?
Tag interfaces are used in Java (Serializable being the obvious example). C# and even Java seem to be moving away from this though in favor of attributes, which can accomplish the same thing but also do much more.
I still think there's a place for them in other languages that don't have the attribute concept that .NET and Java have.
ETA:
You would typically use this when you have an interface that implies an implementation, but you don't want the class that implements the interface to actually have to provide that implementation.
Some real world examples:
Serializable is a good example - it implies that there is an implementation (somewhere) that can serialize the object data, but since a generic implementation for that is available, there is no need to actually have the object implement that functionality itself.
Another example might be a web page caching system. Say you have a "Page" object and a "RequestHandler" object. The RequestHandler takes a request for a page, locates/creates the corresponding Page object, calls a Render() method on the Page object, and sends the results to the browser.
Now, say you wanted to implement caching for rendered pages. But the hitch is that some pages are dynamic, so they can't be cached. One way to implement this would be to have the cacheable Page objects implement an ICacheable "tag" interface (Or vice-versa, you could have an INotCacheable interface). The RequestHandler would then check if the Page implemented ICacheable, and if it did, it would cache the results after calling Render() and serve up those cached results on subsequent requests for that page.
In .Net Tag interfaces can be great for use with reflection and extension methods. Tag interfaces are typically interfaces without any methods. They allow you to see if an object is of a certain type without having the penatilty of reflecting over your objects.
An examples in the .Net Framework INamingContainer is part of ASP.Net
I'd call myself an OO programmer, and I've never heard of a tag interface.
I think tag interfaces are worth discussing, because they're an interesting corner case of the concept of an interface. Their infrequent use is also worth noting, though!
I've used tag interfaces a couple of times in an object model representing a SQL database. In these instances, it's a subtype of the root interface for particular types of objects. It's easier to check for a tag interface than an attribute ('obj is IInterface' rather than using reflection)
The .NET Style guide says to use Attributes rather than tag/marker interfaces.
alt text http://www.freeimagehosting.net/uploads/th.4528577db5.jpg
Click for Full image
source: http://www.informit.com/articles/article.aspx?p=423349&seqNum=6
or any number of other exposure points of Cwalina's recommendations, like the book.
I've used a tag interface twice in the past month. They can cut through some nasty problems when refactoring to make a function more generic.
That said, another thing I just discovered is using a tag interface as a parent class to a bunch of related interfaces with methods. The object can be passed around, and various preprocessors can check to see if they need to deal with a particular object. A way of keeping the processing in a separate object where it belongs, but the implementation details of processed objects in their definitions where they belong.