Is it bad practice to pass viewmodels to child composables in jetpack compose? - state

Example:
I have a #Composable func WorkoutScreen(...) which injects a dedicated ViewModel (e.g. with hilt). It displays some different child composables like #Composable func ProgressView(...) and some others. ProgressView is the only composable in the whole screen, which observes/needs a specific State property x from the injected ViewModel. Would it be bad practice to pass the ViewModel from WorkoutScreen as parameter down to ProgressView? Or should I just pass the States value only?
Let's think this further and say I pass only the State. Also let's say, not ProgressView is the one needing the State, but just another child of ProgressView. If the State changes now, the whole ProgressView might be recompositioned since "its input changes" (instead of just the child), if I understood correctly. Wouldn't this lead to unnecessary recomps?

The entire Composable shouldn't recompose, since Compose is efficient enough to recompose only the Composable which are explicitly reading a state.
Don't worry about efficiency, it won't get affected. For the principles part, no, you shouldn't pass the model around. That is because of the separation-of-concerns principle. All the parts of the program should have access to only as much information as they need to function - no more, no less.
If you pass the entire viewmodel around, firstly every part of the app will have access to everything inside the viewmodel, and may modify properties leading to conflicts. It also makes the viewmodel tightly coupled with a lot of Composable code, whereas passing only the state, limits the coupling to only the part of the viewmodel that is actually required by the Composable. Finally y, if you pass the viewmodel around, it would be practically impossible to test your apps, since you'll need to generate a whole new "fake" viewmodel, with fake values for testi, which will become problematic as the model grows more and complex.
Use state-hoisting. Read here: https://developer.android.com/codelabs/jetpack-compose-state#8, or another stack overflow answer

Passing a ViewModel to a child composable is not very good practice. Only Screen-Level Composables (Main UI Page) should access ViewModel business logic.
There are two main benefits of this approach:
Your child's composable will become reusable.
There is no concrete implementation, So you can easily update the
business logic.

Related

Different functions or single assignable property with side effects?

I'm designing/writing a small UI toolkit (for self-betterment purposes, what else?) and I am unsure what kind of API would be better in the following senses:
lowest WTF? level.
most flexible.
most succinct, yet descriptive
best fit with Standard C++.
Some elements that are important:
The window class represents well, a window, and can be shown, hidden, minimized, maximized, full screen maximized, and closed.
I have a proxy_property class which can be assigned arbitrary get and set functions that can e.g. reflect a current value that ought to be fetched or set through some external API call.
I also have a property class that can be connected to (i.e. observed), and when it is assigned a new/different value, will signal this new value to its observers.
I am unsure what the best way to handle the window state:
Private member variable, only accessible through hide(), isVisible() etc. member functions, Qt style.
read-only property (will need some extra implementation as I don't currently have this worked out) that is backed by hide(), show(), etc. getters and updated accordingly.
A proxy_property that can be assigned a new state, resulting in a call to hide(), show(), etc. or a combination thereof when assigned a new value.
At first glance, I'd prefer number 3 for reason 3, but in light of the other conditions I'm unsure how well this design will hold up. Suffice to say I haven't seen my number 3 used anywhere, and I'm afraid to lean too much on my proxy_property concept as it might incur more overhead than it's worth (on the other hand, this is UI code we're talking about, so overhead will be there nonetheless).
For clarity:
enum class window_state { windowed, hidden, minimized, maximized, fullscreen_maximized };
class window
{
public:
proxy_property<window_state> state;
//....
};
So one can do
some_window.state = window_state::minimized;
To actually do something more traditionally done by e.g.
some_window.minimize();
The end result would be functionally identical of course. It's just the API that is completely different.
I think you should be careful to distinguish between the properties you can set (e.g., say, visibility from the properties you can observe (e.g. isVisible), because in many cases the observable properties depend on more than just the setting.
A control, for example isVisible if it has visibility == true AND it's container isVisible.
There is no reason to make a control's visibility setting observable, and it fact it would probably lead to mistakes.
For this reason, I would prefer setters and getters for visibility, and a listenable property for isVisible.

Notifying a class of another class' changes

Having the classes Container, Item and Property, the container shall be notified whenever a property in an item changes.
The container is the owner of the items and needs the information to properly manage them according to their properties.
I've thought of 2 options yet:
Observer pattern.
Proxy object.
The observer pattern seems to be too heavy for that task in my opinion. A proxy object could work out well, however in that case I'd violate the DRY principle, because I have to forward calls from the proxy to the actual object.
A requirement is that the details are hidden from the user. It's required that it's not needed to call some update_item() function or similar, i.e. giving the responsibility of informing the container to the user, which might lead to usage problems.
In such simple case I don't see a reason of using Observer. Since an Item can be only in one container at once I would just go with giving the Item a reference or pointer to the container it is placed in.
When some Property of the Item changes it as able to notify it's Container via that pointer
Observer pattern is useful in case you need to notify many objects.
EDIT
Making every simple thing using Interfaces and extremely clean design may also harm you. I think the quote from zen of Python explains good what i mean:
Special cases aren't special enough to break the rules. //make Interfaces
Although practicality beats purity. //but not everywhere
So you should a have balance between purity and practicality
You should use the pattern that is easiest to understand and maintain, and requires the least invention of specialized components. In the environment I work in (objective-C), the observer pattern is about as uncomplicated as it gets. It also offers flexibility when your notification requiements change.
Andrew's answer is event simpler - direct communication between objects does not requie the invention of a proxy or the overhead of notification handling. But it has less flexibility, should you need it in the future.
I'm not sure what "too heavy" means. Perhaps you can explain that.
As has been mentioned before, an Observer is pretty much overkill here, but the solution is pretty simple. You just need to "bubble up" the event.
When a property is changed, it notifies it's parent item.
When an item is changed (a side-affect from either a property changing, or something more integral to the item), it notifies it's container/parent).
When a container is notified, well, you're done. If containers can be nested then I guess it can raise an event to it's parent container if necessary.

Child/Parent structure with different classes in C++

I've decided to make my next game using my own simple engine. I've already written some code for object rendering, physics etc. and now I'm thinking about how to easily connect them together.
I want to make hierarchic structure with one master object, lets call it Scene which will have parent as Sprites or InteractiveObjects and every Sprite or InteractiveObject could have its own child which would have its own child.. I think you already got my point here :)
Let's assume, that every object type will inherit from some base object, let's call it Node for example. I'm not sure yet, if Node will be "real" object which will have its size, position etc. or only abstract wrapper for every object in game (I tend to option two actually).
And finally. My goal is, to have object of actual Scene, call something like Scene->Move(x,y) and it will move every child of Scene (or Sprite, InteractiveObject etc.). Or Scene->Render() and it will render every (renderable) child. If I create Sprite, I want to add child like Sprite->addChild() and child could be another Sprite, InteractiveObject or just simple Node.
And now my question. What's the best way to implement it with C++? Or am I totally wrong and this structure is stupid? :)
I should think that whether or not the structure is sensible depends somewhat on what you really want to achieve -- the system sounds very flexible, but usually there's a trade-off between flexibility and performance. Depending on the genre of the game, performance may be hard enough to come by.
Also, if all things derive from some BaseNode, they all need (although possibly empty) methods for all kinds of things whether or not they actually can be rendered, moved etc. Or you'd end up with lots of dynamic_casts, which isn't very nice either. It might therefore be better to have slightly less flexibility and differentiate between game entities and graphical entities, with the latter being part of the former (you might want to allow a game entity to be made up from multiple graphical entities, or sub-entities, though).
If you do go with your current architecture, I should think that each BaseObject has something like a vector and when you call, say, render() on a master object, it goes through all it's children and calls render on them. They do the same and do any render code that is appropriate to them.
Another question is, though, whether an object could feasibly be attached to several other objects (if there is a difference between rendering and physics, for example). If so, it can get hairy to know when to delete an object, unless you don't use plain BaseObject*, but some form of auto_ptr or shared_ptr.
I hope that this answer does help you a little, though I realise it's not a simple "this is they way!" one.

The Registry pattern: to use or not to use

I am considering using the Registry pattern in my application to store weak pointers to some of app's windows and panes. The general structure of the application is shown below.
The application has one MainFrame top level window with few child panes within it. There can be many of TabPane type based tabs. I need to reference the ParamsPane panel from all of my TabPane tabs, so I need a pointer to the ParamsPane object to be stored somewhere. There can be a plenty of options, but the most obvious ones are (1) to store the pointer within the Application singleton object or (2) to create a simple registry class. Something like:
class Registry {
public:
static MainApp* application;
static MainWindow* mainWindow;
};
Is this a good practice? What are the benefits and caveats of such an approach?
It depends on why you want to reference ParamsPane. I can think of two reasons and two different solutions.
You want to update data in ParamsPane because data in TabPane changed.
If this data is completely separatable from the view, what you should probably do is separate it. This means following the Model-View-Controller pattern. Both ParamsPane and TabPane instances can access the model separatly. So there is no direct reference between the two.
There is some strong link between the two, irrelevant of data.
If the previous mentioned point isn't relevant, and there is a really strong link between the two panels you could consider writing a specific TabPane class which stores a reference to a ParamsPane class.
I feel both these solutions are better than a Singleton or 'Registry' approach. Beware that I haven't heard of this pattern before, but I believe I understand its intent. More info on why global state objects (more specifically singletons) are a bad practice can be found here.
In terms of testability, it may not be a good idea to use the Registry Pattern. To repost from this article:
Unit testing is predicated on the assumption that you are testing small, discrete units of code that do not have dependencies. This requires that developers do everything they can to either remove dependencies or mock them in such a way that the dependencies are neutralized as contributors to the failure of the unit being tested. In PHP 5, objects are not copied when assigned; instead, their address in a hash table is copied. This means that if you retrieve an object from the registry, and then modify it, every subsequent retrieval from the registry will reflect that modification.
The reason this creates a significant issue is that it prevents you from testing a discrete unit of code. Now, instead of one thing being the variable in a test failure, there are two: the unit of code being tested and the object it retrieved from the registry. Any time there is more than one possibility for failure, the effectiveness of the unit testing is diminished.
Your Registry class and Singleton are OO-ways of global variables. Prefer to make the Params Pane in the MainFrame and to pass it as reference to the tab-panes.

Worth using getters and setters in DTOs? (C++)

I have to write a bunch of DTOs (Data Transfer Objects) - their sole purpose is to transfer data between client app(s) and the server app, so they have a bunch of properties, a serialize function and a deserialize function.
When I've seen DTOs they often have getters and setters, but is their any point for these types of class? I did wonder if I'd ever put validation or do calculations in the methods, but I'm thinking probably not as that seems to go beyond the scope of their purpose.
At the server end, the business layer deals with logic, and in the client the DTOs will just be used in view models (and to send data to the server).
Assuming I'm going about all of this correctly, what do people think?
Thanks!
EDIT: AND if so, would their be any issue with putting the get / set implementation in the class definition? Saves repeating everything in the cpp file...
If you have a class whose explicit purpose is just to store it's member variables in one place, you may as well just make them all public.
The object would likely not require destructor (you only need a destructor if you need to cleanup resources, e.g. pointers, but if you're serializing a pointer, you're just asking for trouble). It's probably nice to have some syntax sugars constructors, but nothing really necessary.
If the data is just a Plain Old Data (POD) object for carrying data, then it's a candidate for being a struct (fully public class).
However, depending on your design, you might want to consider adding some behavior, e.g. an .action() method, that knows how to integrate the data it is carrying to your actual Model object; as opposed to having the actual Model integrating those changes itself. In effect, the DTO can be considered part of the Controller (input) instead of part of Model (data).
In any case, in any language, a getter/setter is a sign of poor encapsulation. It is not OOP to have a getter/setter for each instance fields. Objects should be Rich, not Anemic. If you really want an Anemic Object, then skip the getter/setter and go directly to POD full-public struct; there is almost no benefit of using getter/setter over fully public struct, except that it complicates code so it might give you a higher rating if your workplace uses lines of code as a productivity metric.