<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrés Alberto Estevez on Medium]]></title>
        <description><![CDATA[Stories by Andrés Alberto Estevez on Medium]]></description>
        <link>https://medium.com/@andres.estevez?source=rss-a043755dae74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ANQEUySAz7pr_tlm</url>
            <title>Stories by Andrés Alberto Estevez on Medium</title>
            <link>https://medium.com/@andres.estevez?source=rss-a043755dae74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:22:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andres.estevez/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Arquitectura de Flutter con Provider]]></title>
            <link>https://medium.com/@andres.estevez/arquitectura-de-flutter-con-provider-ff95dbe2d879?source=rss-a043755dae74------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff95dbe2d879</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Andrés Alberto Estevez]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 11:23:04 GMT</pubDate>
            <atom:updated>2024-08-13T14:14:52.409Z</atom:updated>
            <content:encoded><![CDATA[<p>Flutter es un framework declarativo. Ante cambios de estado, el árbol de widgets se reconstruye. No existe forma de referenciar un widget y cambiar sus propiedades directamente, sino que la interfaz de usuario se reconstruye a través de los métodos build de los widgets para representar al estado de la aplicación.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/0*7qua3C83cP9K7-C3.png" /></figure><p>Viendo la ecuación anterior, la mayor complejidad viene dada por como mantener el estado de la aplicación en los widgets y como aplicar modificaciones sobre el mismo, manteniendo sincronizada la interfaz.</p><h4>Manejando el estado</h4><p>Los Stateful Widgets pueden contener estado y pueden notificar sus cambios a través del método setState, el cual desencadena un rebuild.</p><p>El primer impulso que podemos tener es usar estos widgets para crear y mantener el estado de nuestra aplicación. Pero a medida que nuestra aplicación se agrande, pueden ir apareciendo complicaciones.</p><ul><li>Solo podemos compartir el estado con widgets descendientes. Para esto podemos pasar información como parámetro al momento de la creación de los widgets, pero cuanto mas grande es la jerarquía, esto se vuelve cada vez mas tedioso y puede forzarnos a crear widgets muy grandes y con muchas responsabilidades o pasar información multiples niveles.</li><li>Si queremos permitir a otro widget modificar el estado, podemos pasarle callbacks al crearlos, pero al igual que el anterior, no escala en jerarquías grandes y ademas, solo sirve para widgets descendientes.</li><li>Podemos utilizar repositorios o servicios para guardar y recuperar el estado de nuestra aplicación, lo cual también nos obligaría a mantenerlo sincronizado en todos los widgets, pero esto puede complejizar el proyecto</li><li>Si estos widgets se encargan de la creación, modificación y representación del estado, les estaríamos atribuyendo muchas responsabilidades.</li></ul><p>Muchos de estos problemas pueden solucionarse con el uso de Inherited Widgets como intermediarios entre los widgets, pero su implementación puede ser difícil.</p><h4>Provider al rescate</h4><p>Esta librería nos permite compartir información dentro de la jerarquía de widgets. En principio es un wrapper que facilita la creación de Inherited Widgets, pero contiene muchas mas funcionalidades para facilitar el acceso y uso de la información.</p><p>Nos provee tanto widgets que son capaces de crear y/o mantener objetos, como widgets capaces de obtenerlos y recibir notificaciones cuando cambien.</p><h3>Definiendo la arquitectura</h3><p>Antes de plantear la arquitectura tenemos que tener en claro que es lo que esperamos de ella:</p><ul><li>Simpleza: Minimizar el boilerplate y las abstracciones innecesarias para facilitar el entendimiento del código y las futuras iteraciones. Además, minimizando la cantidad de actores del sistema, es más fácil saber cual es la responsabilidad de cada uno.</li><li>Resilencia: La arquitectura debe ayudarnos a adaptarnos rápidamente a los nuevos requerimientos en vez de dilatar el tiempo de desarrollo ajustándonos a sus reglas.</li><li>Testing: No hay nada peor que tener una suite de tests en verde y que aún así la aplicación falle. Al utilizar abstracciones y no testear con clases reales, estamos dejando una parte de nuestra aplicación sin cobertura. Para solucionar esto es necesario que, en la medida de lo posible, la arquitectura nos permita testear fácilmente elementos visuales, reducir la cantidad de mocks en los tests y permitirnos realizar tests de integración para probar el sistema en su conjunto.</li></ul><p>Teniendo esto en cuenta, plantearemos la arquitectura sobre tres actores</p><ul><li>Estado: Solo debe contener datos para que los widgets lo representen y encargarse de notificar cuando los mismos cambian. Pueden no estar ligados únicamente a una vista de la aplicación. Como será la principal forma de comunicación en nuestra arquitectura, no les agregaremos dependencias con servicios o repositorios para que sea más fácil desarrollar los tests.</li><li>Comandos: Representan operaciones que realizan cambios sobre el estado. No deben devolver una respuesta. En caso de tener que devolver información, será a través del estado. Aquí debería estar la lógica de nuestra aplicación y los accesos a nuestro backend.</li><li>Widgets: son los encargados de representar el estado e invocar a los comandos. Siempre buscaremos de minimizar las responsabilidades de los mismos para facilitar el testing. Cómo regla general, segregar los widgets según si invocan comandos o representan al estado</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*psX7CCz9k8EqG4uEEgWGPQ.png" /></figure><h3>Caso de ejemplo</h3><p>Se nos pide crear una aplicación que muestre un listado de misiones. Estas tienen un nombre y un progreso, dado por una cantidad actual y una total. Al abrir la aplicación, deberemos obtener la lista de misiones de nuestro backend para mostrarlas en pantalla.</p><h4>Creando el estado</h4><p>Como se planteo anteriormente, nuestros widgets deben representar la interfaz del usuario en base al estado, así que inicialmente deberemos definirlo:</p><pre>class MissionsState extends ChangeNotifier {<br>  bool isLoading = false;<br>  List&lt;MissionState&gt; missions = [];<br><br>  void setLoading() {<br>    isLoading = true;<br>    notifyListeners();<br>  }<br><br>  void load(List&lt;MissionState&gt; missionsToLoad) {<br>    isLoading = false;<br>    missions = missionsToLoad;<br>    notifyListeners();<br>  }<br>}<br><br>class MissionState {<br>  int id;<br>  String text;<br>  int current;<br>  int total;<br><br>  MissionState(this.id, this.text, this.current, this.total);<br><br>  get isComplete =&gt; current == total;<br>}</pre><p>Como podemos ver, nuestro estado hereda de ChangeNotifier. Esto nos da la posibilidad de notificar sus cambios llamando al método notifyListeners().</p><p>Dejar todos los campos públicos (al menos esta limitación está presente en la versión que use en este momento) nos da la posibilidad de modificar sus valores en runtime utilizando las DevTools de Flutter, lo que además notifica los cambios y reconstruye la UI, ahorrándonos tiempo al momento de probar manualmente nuestra aplicación.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5KDIjA7u-tgx_nCd4dvfg.png" /><figcaption>la pestaña provider nos permite ver todos estos widgets en el árbol</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DmyuD3AsUlaTOpiQ3LTPvg.gif" /><figcaption>al modificar sus propiedades podemos ver los cambios en runtime</figcaption></figure><p>Ahora que tenemos el estado definido, deberemos crearlo y disponibilizarlo para el resto de los widgets. Para esto crearemos un Provider (mas específicamente un ChangeNotifierProvider) dentro del árbol de widgets.</p><p>Dónde elijamos crearlo dependerá de que widgets necesiten poder acceder a él y que vida queremos que tenga dentro de nuestra aplicación. Los widgets descendientes podrán consumirlo, así que deberemos ver donde tiene sentido ubicarlo. Por otro lado, si lo ubicamos en una parte del árbol que puede reconstruirse, podríamos perder el estado.</p><p>En nuestro caso de ejemplo, lo pondremos en el principio del árbol.</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  // This widget is the root of your application.<br>  @override<br>  Widget build(BuildContext context) {<br>    return ChangeNotifierProvider(<br>      create: (context) =&gt; MissionsState(),<br>      child: MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        theme: ThemeData(<br>          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>          useMaterial3: true,<br>        ),<br>        home: const Home(),<br>    );<br>  }<br>}</pre><p>Si más abajo en el árbol de widgets necesitamos utilizar el estado, podemos usar un Consumer. Este widget busca un provider del tipo especificado hacia arriba en el árbol de widgets y llama a un builder con su valor. Como nuestro MissionState esta dentro de un ChangeNotifierProvider, cada vez que se llame a notifyListeners(), los consumers volverán a ejecutar la función build, manteniendo todos los widgets sincronizados con el estado.</p><h4>Representando el estado</h4><p>Ahora que tenemos el estado definido, podemos comenzar a crear widgets para representar la interfaz de usuario según sus datos. El siguiente se encargará de listar las misiones.</p><pre>class MissionsListWidget extends StatelessWidget {<br><br>  const MissionsListWidget({super.key});<br><br>  @override<br>  Widget build(BuildContext context) =&gt; Consumer&lt;MissionsState&gt;(<br>      builder: (ctx, missions, child) =&gt; Scaffold(<br>        appBar: AppBar(title: const Text(&quot;Missions&quot;)),<br>        body: _buildBody(missions)<br>      )<br>  );<br><br>  Widget _buildBody(MissionsState state) {<br>    return state.isLoading<br>      ? const Center(child: CircularProgressIndicator())<br>      : _missionsList(state);<br>  }<br><br>  Widget _missionsList(MissionsState state) =&gt; ListView.builder(<br>      itemCount: state.missions.length,<br>      itemBuilder: (context, index)<br>      {<br>        final item = state.missions[index];<br>        return MultiProvider(providers: [<br>          Provider&lt;Index&gt;.value(value: index),<br>          Provider&lt;MissionState&gt;.value(value: item)<br>        ],<br>        child: const MissionWidget());<br>      }<br>  );<br>}</pre><p>Aquí, podríamos haberle pasado el MissionState y el índice por constructor al MissionWidget, pero utilizar providers nos da la ventaja de que en caso de tener que agregar mas widgets dentro, no tendremos que hacer argument drilling y además, como todos los widgets deberán usar consumers o selectors, será más fácil probarlos en aislamiento.</p><p>Si quisiéramos hacer un test para este widget, solo necesitaríamos cargarlo junto con un ChangeNotifierProvider con una instancia de nuestro estado y modificarlo para validar que el árbol de widgets se construya como debe. Ademas, como nuestro estado no tiene dependencias, prácticamente no tendremos boilerplate en el test.</p><pre>late MissionsState _state;<br><br>void main() {<br>  setUp(() {<br>    _state = MissionsState();<br>  });<br><br>  testWidgets(&#39;show progress while loading&#39;, (tester) async {<br>    await _givenPumpWidget(tester);<br><br>    _state.setLoading();<br><br>    // para esperar que se reconstruya<br>    await tester.pump();  <br><br>    expect(find.byType(CircularProgressIndicator), findsOneWidget);<br>  });<br><br>  testWidgets(&#39;show items while loaded&#39;, (tester) async {<br>    await _givenPumpWidget(tester);<br><br>    _state.load([<br>      MissionState(1, &quot;Mission 1&quot;, 3, 10)<br>    ]);<br><br>    await tester.pump();<br><br>    expect(find.text(&quot;Mission 1&quot;), findsOneWidget);<br>    expect(find.text(&quot;3/10&quot;), findsOneWidget);<br>  });<br>}<br><br>// Recordar que los tests también son código, siempre buscar facilitarlos<br>// extrayendo extensiones o helpers para reducir el boilerplate.<br>Future&lt;void&gt; _givenPumpWidget(WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(<br>    home: ChangeNotifierProvider&lt;MissionsState&gt;(<br>      create: (ctx) =&gt; _state,<br>      child: const MissionsListWidget())));<br>}</pre><p>De esta manera no solo testeamos este widget, sino que también, al utilizar una instancia de nuestro estado y no un mock, también quedará testeado. No debería ser necesario realizar un test del estado de forma aislada ya que al ser nuestro intermediario, a medida que vayamos agregando cobertura de nuestros widgets y comandos, este irá quedando cubierto.</p><p>También podremos elegir si queremos hacer los tests mas unitarios o integrales. Podríamos haber hecho al MissionListWidget más unitario validando que se hayan creado los providers y el MissionWidget dentro del árbol de widgets, aunque esto nos deje con un test más implementativo, y luego podemos atacar el test de MissionWidget en aislamiento.</p><h4>Usando el estado en diferentes widgets</h4><p>Siempre debemos tener en cuenta que no hay una relación directa entre el estado y un widget en particular. Si por ejemplo tuviéramos el requerimiento de poner la lista de widgets dentro de una tab view en el home de nuestra aplicación y tuviéramos que mostrar un badge en el tab de misiones si hay alguna completa, podemos resolverlo con un widget independiente a MissionListWidget:</p><pre>class CompletedMissionsBadge extends StatelessWidget {<br>  final Widget child;<br><br>  const CompletedMissionsBadge({super.key, required this.child});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Stack(children: [<br>      child,<br>      Selector&lt;MissionsState, bool&gt;( // además existe Selector2 o 3 por si necesitamos consumir varios providers<br>        selector: (_, state) =&gt; state.hasAnyMissionCompleted,<br>        builder: (ctx, hasMission, _) =&gt; hasMission ? _badge() : _shrink(),<br>      )<br>    ]);<br>  }<br><br>  Widget _badge() =&gt; Transform.translate(<br>    offset: const Offset(0, 10),<br>    child: const Badge());<br><br>  Widget _shrink() =&gt; const SizedBox.shrink();<br>}</pre><p>y su test correspondiente:</p><pre>late MissionsState _state;<br>final _completedMission = MissionState(1, &quot;1&quot;, 1, 1);<br>final _inProgressMission = MissionState(1, &quot;1&quot;, 0, 1);<br><br>void main() {<br><br>  setUp(() {<br>    _state = MissionsState();<br>  });<br><br>  testWidgets(&quot;when has completed missions show badge&quot;, (tester) async {<br>    await _givenWidgetPumped(tester);<br><br>    _state.load([_completedMission]);<br><br>    await tester.pump();<br><br>    expect(find.byType(Badge), findsOneWidget);<br>  });<br><br>  testWidgets(&quot;when has missions in progress dont show badge&quot;, (tester) async {<br>    await _givenWidgetPumped(tester);<br><br>    _state.load([_inProgressMission]);<br><br>    await tester.pump();<br><br>    expect(find.byType(Badge), findsNothing);<br>  });<br>}<br><br>Future&lt;void&gt; _givenWidgetPumped(WidgetTester tester) =&gt; tester.pumpWidget(<br>    MaterialApp(<br>      home: ChangeNotifierProvider&lt;MissionsState&gt;.value(<br>        value: _state,<br>        child: const Scaffold(<br>          body: CompletedMissionsBadge(<br>            child: Tab(icon: Icon(Icons.add_business_outlined))<br>          )<br>        ))<br>      )<br>  );<br>}</pre><h4>Modificando el estado con comandos</h4><p>Para realizar modificaciones al estado usaremos comandos. Estos deberán contener la lógica de negocio de nuestra aplicación, accesos a nuestro backend y además deberán mantener el estado consistente durante toda la operación.</p><p>Algunas aplicaciones o módulos pueden llegar a tener más lógica de negocio del lado del cliente que del servidor. En este caso recordemos que nuestro estado puede contener la información necesaria y su ciclo de vida puede durar durante toda la sesión dependiendo de donde lo ubiquemos.</p><p>No es necesario crear un modelo, repositorio u otras abstracciones para lograr una separación de capas. Flutter es declarativo así que nuestros widgets solo pueden representar el estado y el framework no nos permite modificar un widget directamente, así que deberíamos estar seguros.</p><p>Volviendo a nuestro ejemplo, nuestro comando deberá consultar la lista de misiones de nuestro backend y volcarla en nuestro estado. Además deberemos dar feedback de que la operación está en curso:</p><pre>class FetchMissions {<br>  final MissionsService _missionsService;<br>  final MissionsState _state;<br><br>  const FetchMissions(this._missionsService, this._state);<br><br>  Future call() async {<br>    _state.setLoading();<br>    var missions = await _missionsService.fetchMissions();<br>    _state.load(missions);<br>  }<br><br>  // para facilitar la creación en diferentes widgets<br>  static FetchMissions of(BuildContext context) =&gt;<br>      FetchMissions(context.read(), context.read());<br>}</pre><p>Para mantenernos alineados con el patrón, no deberíamos devolver una respuesta o recibir parámetros en los comandos. Todas las dependencias que tengamos idealmente deberían ser resueltas desde el contexto para que sea más fácil realizar los tests.</p><p>Ahora que tenemos el comando, necesitamos invocarlo desde algún widget. Como queremos que se cargue automáticamente podemos hacerlo en el initState() del widget. Además, para mantener desacoplados la modificación del estado con la representación del mismo, este widget solo ejecutará el comando y no tendrá ningún componente visual:</p><pre>class MissionsFetchWidget extends StatefulWidget {<br>  final Widget child;<br><br>  const MissionsFetchWidget({super.key, required this.child});<br><br>  @override<br>  State&lt;MissionsFetchWidget&gt; createState() =&gt; _MissionsFetchWidgetState();<br>}<br><br>class _MissionsFetchWidgetState extends State&lt;MissionsFetchWidget&gt; {<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    WidgetsBinding.instance.addPostFrameCallback((_) {<br>      FetchMissions.of(context).call();<br>    });<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return widget.child;<br>  }<br>}</pre><p>y ahora podemos agregar el widget junto con un provider del MissionsService requerido por el comando:</p><pre>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return MultiProvider(<br>      providers: [<br>        ChangeNotifierProvider(create: (_) =&gt; MissionsState()),<br>        Provider&lt;MissionsService&gt;(create: (_) =&gt; FakeMissionsService())<br>      ],<br>      builder: (ctx, _) =&gt; MaterialApp(<br>        title: &#39;Flutter Demo&#39;,<br>        theme: ThemeData(<br>          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),<br>          useMaterial3: true,<br>        ),<br>        home: const Home(),<br>    );<br>  }<br>}</pre><p>Al igual que con los otros widgets, podemos realizar el test agregando los providers requeridos por el comando:</p><pre>late MissionsState _state;<br>late MissionsService _missionsService;<br><br>var _missions = [<br>  MissionState(1, &quot;mission 1&quot;, 0, 10),<br>  MissionState(2, &quot;mission 2&quot;, 0, 5),<br>];<br><br>void main() {<br>  setUp(() {<br>    _state = MissionsState();<br>    _missionsService = MockMissionsService();  // usando mockito<br>  });<br><br>  testWidgets(&quot;set loading while request pending&quot;, (tester) async {<br>    var completer = _givenMissionsFetchHangs();<br>    await _givenWidgetPumped(tester);<br><br>    await tester.pump();<br><br>    expect(_state.isLoading, true);<br>    expect(_state.missions.length, 0);<br><br>    completer.complete([]);<br>  });<br><br>  testWidgets(&quot;load missions from request&quot;, (tester) async {<br>    _givenMissionsFetchReturns(_missions);<br>    await _givenWidgetPumped(tester);<br><br>    await tester.pump();<br><br>    expect(_state.isLoading, false);<br>    expect(_state.missions.length, 2);<br>  });<br>}<br><br>void _givenMissionsFetchReturns(List&lt;MissionState&gt; missions) {<br>  when(_missionsService.fetchMissions()).thenAnswer((_) =&gt; Future.value(missions));<br>}<br><br>Completer&lt;List&lt;MissionState&gt;&gt; _givenMissionsFetchHangs() {<br>  var completer = Completer&lt;List&lt;MissionState&gt;&gt;();<br>  when(_missionsService.fetchMissions()).thenAnswer((_) =&gt; completer.future);<br>  return completer;<br>}<br><br>Future&lt;void&gt; _givenWidgetPumped(WidgetTester tester) async {<br>  await tester.pumpWidget(MaterialApp(<br>      home: MultiProvider(<br>        providers: [<br>          ChangeNotifierProvider.value(value: _state),<br>          Provider&lt;MissionsService&gt;.value(value: _missionsService),<br>        ],<br>        child: const MissionsFetchWidget(child: SizedBox.shrink())<br>      )<br>    )<br>  );<br>}</pre><p>En este caso, verificaremos que el estado se encuentre en el estado correcto durante y después de la ejecución del comando, ya que la representación del mismo quedará delegada a los widgets con esa responsabilidad.</p><p>En algunos casos, puede ser posible que necesitemos invocar comandos ante cierta condición del estado. Esto también podríamos resolverlo con esta arquitectura.</p><p>Por ejemplo, si necesitáramos recargar la lista de misiones en cierto flujo de nuestra aplicación, algún comando podría marcar un flag de “isDirty” en nuestro estado para indicar que debe recargarse y, por otro lado, podríamos escuchar sus cambios en el widget anterior:</p><pre>class MissionsFetchWidget extends StatefulWidget {<br>  final Widget child;<br><br>  const MissionsFetchWidget({super.key, required this.child});<br><br>  @override<br>  State&lt;MissionsFetchWidget&gt; createState() =&gt; _MissionsFetchWidgetState();<br>}<br><br>class _MissionsFetchWidgetState extends State&lt;MissionsFetchWidget&gt; {<br>  late MissionsState _state;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _state = context.read&lt;MissionsState&gt;();<br>    _state.addListener(_tryFetch);<br>    WidgetsBinding.instance.addPostFrameCallback((_) =&gt; _tryFetch());<br>  }<br><br>  @override<br>  void dispose() {<br>    super.dispose();<br>    _state.removeListener(_tryFetch);<br>  }<br><br>  _tryFetch() {<br>    if (_state.isDirty) {<br>      FetchMissions.of(context).call();<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return widget.child;<br>  }<br>}</pre><p>De esta manera podemos comunicar diferentes módulos de nuestra aplicación utilizando el mismo concepto, el estado como nexo entre los diferentes widgets.</p><p>Si te interesa ver un poco más, dejo el link del ejemplo completo. Algunas clases no fueron testeadas ya que eran servicios falsos para simular el acceso a API, pero aún así se pudo lograr una muy buena cobertura de tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*JsKsKausw7preEuX_XQt7g.png" /></figure><p><a href="https://gitlab.com/andres.estevez/flutter-architecture">Andres Estevez / flutter-architecture · GitLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff95dbe2d879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A component-based architecture for Unity]]></title>
            <link>https://medium.com/etermax-technology/a-component-based-architecture-for-unity-ff211ca478fe?source=rss-a043755dae74------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff211ca478fe</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Andrés Alberto Estevez]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 19:30:14 GMT</pubDate>
            <atom:updated>2023-01-25T20:13:31.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWPDsMOGnR2KxD5ygjwB-Q.jpeg" /></figure><h4>An MVVM-inspired approach to building games faster and easier</h4><p><strong><em>By Andrés Estevez, Technical Leader, and </em></strong><a href="https://medium.com/u/4537ab766225"><strong><em>Augusto Salgado</em></strong></a><strong><em>, Software Engineer at etermax</em></strong></p><p>What’s the deal with Software Architecture in Unity?</p><p>Why is it so hard to find articles focusing on the different existing approaches and how to implement them in this acclaimed engine?</p><p>Here at <a href="https://etermax.com/home/?lang=es"><strong>etermax</strong></a> we have tried several options, and though there is no silver bullet or magical answer, we have recently found an interesting approach that is helping us build scalable and easy-to-test games faster than ever.</p><p>But first of all…</p><p>What do we want out of an architecture?</p><p>Before we can start talking about a specific software architecture design, we should first think about what we need from it, which of the advantages it offers suits best our needs and which of its disadvantages are not that painful to us… specially when building mobile games that will be played by millions of users around the world.</p><h4>Simplicity</h4><p>What we mean by simplicity is not some utopian concept of the code being written by itself, rather the architecture not complicating things just for the sake of it. For example, making a button play a sound whenever it’s tapped should not require a lot of classes and boilerplate code in order to go through different layers of abstraction, only because your architecture is forcing you to do so. Not only does this extend the amount of time required to code the feature and feels frustrating, but it also makes the code harder to read and follow as the project grows and new teammates are incorporated to it.</p><p>In other words, we want our architecture to minimize boilerplate and the amount of classes involved in specific functionality.</p><h4>Resilience</h4><p>Either because you are working in the mobile games market with agile or SCRUM methodologies, or because you need your project to react fast and smoothly to changes in the requirements, you’ll need the architecture you use to be resilient to changes. Thus, having an architecture more oriented towards components rather than inheritance helps us react to those changes by simplifying, removing, changing, or adding new components. This reduces the necessity to modify existing code in order to adapt functionality and makes the workflow of the whole team more agile.</p><h4>Reusability</h4><p>Yet another benefit of having a component-oriented architecture… It is very common to have the same functionality repeated across different screens and features. For example, playing a sound whenever a button is tapped (yes, again) will certainly be needed lots of times. Having the functionality well separated in a general purpose component enables you to simply reuse the same component wherever you need it. This reduces duplicated code, makes things easier to develop, and enhances prototyping times.</p><h4>Testability</h4><p>At a first glance, the possibility to test your code efficiently may not seem related to the architecture you choose. However, when building games with Unity, there is always a temptation to decouple your code from the engine as much as possible, with the excuse of making it more testable, as “testing monobehaviours is a headache”.</p><p>Following that approach in other opportunities has led us, for instance, to creating an interface for each component (meaning the component inherited from MonoBehaviour as well as from the interface). Those components would have a “Presenter” in charge of handling it, so we would finally make unit tests of those presenters, in which we would have a substitute for the component interface and we would assert that the expected methods were called.</p><p>However, as you can imagine, the components themselves were not tested, so the implementation of those methods could be completely wrong and our unit tests would have never failed. In conclusion, we can’t completely trust our suite of tests <em>unless </em>they also include the components that interact directly with the engine.</p><p>Our approach, which we will elaborate further in this post, allows us to have small components with clear responsibilities and few dependencies. This makes the process of unit testing them much easier, by simply creating game objects and attaching the components to them, resulting in much bigger code coverage and eliminating the need to interface the components (which also requires you to architect your code in a way that supports that).</p><h4>Thinking in Components</h4><p>To comply with these pillars, we changed the way we see features. We went from building them as large and closed modules to designing them oriented towards more specific components.</p><p>When creating them, we seek to make these components as atomic as possible. This way, they’ll be more reusable, easy to test, and remove or replace in case they are no longer needed.</p><p>But, if each of these components had its own state, it’d be tricky to know the general state of the application. This is why <strong>ViewModels</strong> were introduced. These objects are in charge of maintaining the state, and components modify them or react to their changes.</p><p>Having this separation between ViewModels and input and output components allows us to have many input components modifying the ViewModels. This is not the case for output components, where the process is transparent as they only showcase the information of the ViewModels when their data changes, and it doesn’t matter what changed them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*jFKYgwN09SViDFTYQs-QjA.png" /></figure><p>Does the term <strong>ViewModel</strong> ring a bell? This is because, to make the architecture easier to understand — and given that it presents some similarities — , a few concepts from <strong>MVVM </strong>were borrowed.</p><p>In <strong>MVVM </strong>architecture, the view interacts with a <strong>ViewModel </strong>giving commands and reacting to changes of state for them to be represented. In addition, the ViewModel knows the model and is in charge of managing access to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*1IV7997j8cP7JwQa" /></figure><p>In our case, <strong>ViewModels </strong>become data containers, and the view is integrated by different components, some of which modify the state of the <strong>ViewModels</strong>, while others react to these changes of state. The flow of the application doesn’t remain within the <strong>ViewModels</strong>, but it’s the result of the changes on its properties.</p><p>Given that our games are mostly client/server based, we consider the model to be our application’s backend, while only an abstraction layer remains on the customer side for communication purposes.</p><h4>Practical Example: “Active Quests List”</h4><p>We’re asked to build a scene in which the three active missions of the user are showcased. Once completed, missions must allow the user to obtain the reward by clicking a button. Otherwise, the button must not be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*Gm1IbOaF4pCE7vAt6Vz4WQ.png" /></figure><p>To showcase the mission’s details, we need a source. In our case, this role is played by the ViewModels. We chose to use scriptable objects as they offer the following advantages:</p><ul><li>As the project can be created as assets, these objects can maintain the value between scenes.</li><li>We can see and modify the value of the ViewModel’s properties selecting the asset at any time while the application is running.</li><li>Because they’re not associated with a scene in particular, they can be referenced from various scenes, prefabs, or other assets.</li><li>We can create multiple instances and give them different uses, unlike with a Singleton or static references.</li></ul><p>What we need from each mission for this scene is:</p><ul><li>The title</li><li>To know whether it has been completed to enable the “claim” button</li><li>To know how much gold it gives as a reward when claiming it</li></ul><p>Also, the ViewModel must be able to notify components when its data changes. In this regard, we chose to use the <a href="https://github.com/neuecc/UniRx">UniRx</a> library, which provides us with <strong>reactive properties</strong> that will allow us to subscribe to changes from the components to represent the state of the ViewModel. This library is not compulsory as the same may be implemented using events or applying the observer/observable pattern, but it simplifies the code so much and brings so many tools to the table that it’s difficult not to use it.</p><p>This way, we defined the ViewModel of a mission the following way:</p><pre>[CreateAssetMenu(menuName = &quot;Quests/Quest ViewModel&quot;, fileName = &quot;QuestViewModel&quot;)]<br>public class QuestViewModel : ScriptableObject<br>{<br>    public StringReactiveProperty Title = new StringReactiveProperty(string.Empty);<br>    public BoolReactiveProperty IsCompleted = new BoolReactiveProperty(false);<br>    public IntReactiveProperty GoldReward = new IntReactiveProperty(0);<br>}</pre><p>Now that our ViewModel has been defined, we can begin to develop the <strong>output components </strong>(in case you don’t remember them, refer back to the architecture’s graph clicking <a href="#5894">here</a>). These components will be responsible for showing the data on the scene. To remain resilient to change, we chose to make these components as atomic as possible, so they can be added or removed when needed:</p><pre>public class DisplayQuestTitle : MonoBehaviour<br>{<br>    public QuestViewModel Quest;<br>    public TMP_Text Label;<br><br>    public void Start()<br>    {<br>        Quest.Title.Subscribe(title =&gt; Label.text = title).AddTo(this);<br>    }<br>}</pre><pre>public class DisplayQuestGoldReward : MonoBehaviour<br>{<br>    public QuestViewModel Quest;<br>    public TMP_Text Label;<br><br>  public void Start()<br>    {<br>        Quest.GoldReward.Subscribe(amount =&gt; Label.text = amount.ToString()).AddTo(this);<br>    }<br>}</pre><pre>public class DisplayOnQuestCompleted : MonoBehaviour<br>{<br>    public QuestViewModel Quest;<br>    public GameObject Target;<br><br>    public void Start()<br>    {<br>        Quest.IsCompleted.Subscribe(Target.SetActive).AddTo(this);<br>    }<br>}</pre><p>Because of their atomic nature, these components are easily reusable and can be added to any game object. Also, in case they’re no longer needed, we can remove them from the scene without affecting the functionality of other components. Yet another advantage is that, because they’re so simple, running tests is very easy:</p><pre>[TestFixture]<br>public class DisplayOnQuestCompletedTest<br>{<br>    private DisplayOnQuestCompleted _component;<br>    private QuestViewModel _quest;<br><br>    [SetUp]<br>    public void SetUp()<br>    {<br>        // create an instance of the viewmodel<br>        _quest = ScriptableObject.CreateInstance&lt;QuestViewModel&gt;();<br>        <br>        // create a gameobject, add the component and assign it&#39;s dependencies<br>        var gameObject = new GameObject();<br>        _component = gameObject.AddComponent&lt;DisplayOnQuestCompleted&gt;();<br>        _component.Quest = _quest;<br>        _component.Target = new GameObject();<br>    }<br><br>    [Test]<br>    public void target_inactive_when_quest_is_not_completed()<br>    {<br>        _component.Start();  // GivenComponentStarted()<br>        <br>        _quest.IsCompleted.Value = false;  // WhenQuestIsNotCompleted()<br>        <br>        Assert.AreEqual(false, _component.Target.activeSelf);  // ThenTargetIsInactive()<br>    }<br><br>    [Test]<br>    public void target_active_when_quest_is_completed()<br>    {<br>        _component.Start();  // GivenComponentStarted()<br>        <br>        _quest.IsCompleted.Value = true;// WhenQuestIsCompleted()<br>        <br>        Assert.AreEqual(true, _component.Target.activeSelf);// ThenTargetIsActive()<br>    }<br>}</pre><p>Going back to Unity, if we wanted to test what we implemented, we should create an instance of our ViewModel for each of our missions first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*DuZGeZNmxp-BSYcnD-SWqA.png" /></figure><p>Then, if we add the components mentioned before to the game objects of each mission and assign their references, when we run the application we will see how the elements of the scene change their value when the data of the ViewModels is changed in runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3ktE8gYMMlyWJCvnr4doJA.gif" /></figure><p>To ensure the integrity of the scene, we can carry our tests that validate the presence of these components in it, while also validating that their references are assigned.</p><pre>[TestFixture]<br>public class QuestSceneTest<br>{<br>    private const string ScenePath = &quot;Assets/Scenes/Quests.unity&quot;;<br><br>    [SetUp]<br>    public void SetUp()<br>    {<br>        // Load scene in editor so we can assert the components are included<br>        EditorSceneManager.OpenScene(ScenePath);<br>    }<br><br>    [Test]<br>    public void contains_display_quest_title()<br>    {<br>        // Find all objects in scene containing DisplayQuestTitle component<br>        var components = Object.FindObjectsOfType&lt;DisplayQuestTitle&gt;().ToList();<br>        <br>        // There should be 3 of them<br>        Assert.AreEqual(3, components.Count);<br>        foreach (var component in components)<br>        {<br>            // assert their references are not null<br>            Assert.IsNotNull(component.Quest);<br>            Assert.IsNotNull(component.Label);<br>        }<br>    }<br>    ...<br>}</pre><p>Now that we can display the data of the missions on the scene, we need a way to stimulate the properties of the ViewModels.</p><p>Following the previous steps, we would need a component that obtains data from missions (whether it comes from a backend, an in-memory repository, or other) and assigns the values to the corresponding ViewModels.</p><p>To reduce complexity, we added an abstraction to communicate with the data access layer, in our case, using the Facade design pattern; this way, the interface is much simpler. We may change its implementation in the future and reduce the number of dependencies on the component, which makes testing it easier.</p><pre>public class LoadQuestsOnStart : MonoBehaviour<br>{<br>    public List&lt;QuestViewModel&gt; Quests;<br>    public IQuestsFacade QuestsFacade = new QuestsFacade();<br><br>    public void Start()<br>    {<br>        var questsResponse = QuestsFacade.GetQuests();<br>        for (var i = 0; i &lt; Quests.Count; i++)<br>        {<br>            Quests[i].Title.Value = questsResponse[i].Title;<br>            Quests[i].GoldReward.Value = questsResponse[i].GoldReward;<br>            Quests[i].IsCompleted.Value = questsResponse[i].IsCompleted;<br>        }<br>    }<br>}</pre><p>Just like the previous components, we can test this one quite seamlessly. We just need to create instances of the ViewModels and replace the implementation of the Facade with a mock before calling the Start method. We encourage you to try it out!</p><p>But…even if the component complies with the use case, there’s some room for improvement:</p><ul><li>The data load is done directly in the Start event. If we wanted to execute this same use case in other event, such as clicking a button, we would have to repeat the code</li><li>If there are several instances of this component, we would have to assign the same references to each of them.</li></ul><p>To address the first point, we could extract the logic of searching for data with the Facade and assign it to the ViewModels using the Command pattern.</p><pre>public class LoadQuestsCommand<br>{<br>    private readonly List&lt;QuestViewModel&gt; _quests;<br>    private readonly IQuestsFacade _questsFacade;<br><br>    public LoadQuestsCommand(List&lt;QuestViewModel&gt; quests, IQuestsFacade questsFacade)<br>    {<br>        _quests = quests;<br>        _questsFacade = questsFacade;<br>    }<br>    public void Execute()<br>    {<br>        var questsResponse = _questsFacade.GetQuests();<br>        <br>        for (var i = 0; i &lt; _quests.Count; i++)<br>        {<br>            _quests[i].Title.Value = questsResponse[i].Title;<br>            _quests[i].GoldReward.Value = questsResponse[i].GoldReward;<br>            _quests[i].IsCompleted.Value = questsResponse[i].IsCompleted;<br>        }<br>    }<br>}</pre><p>This way, components can instantiate this Command and execute it. For our previous component, it would look like this:</p><pre>public class LoadQuestsOnStart : MonoBehaviour<br>{<br>    public List&lt;QuestViewModel&gt; Quests;<br>    public IQuestsFacade QuestsFacade = new QuestsFacade();<br><br>    public void Start()<br>        {<br>            new LoadQuestsCommand(Quests, QuestsFacade).Execute();<br>        }<br>    }</pre><p>This brings us a new problem: if various components used this Command, and the constructor signature were to change (for instance, if a new parameter was added), we would have to change all the components. Additionally, our second suggestion for improvement would get worse given that we would have to add new references to all these components.</p><p>To address this, we delegated the construction of the Commands to a Command Factory. These factories also inherit from ScriptableObject, allowing us to assign the references from the editor.</p><pre>[CreateAssetMenu(menuName = &quot;Quests/Command Factory&quot;, fileName = &quot;QuestsCommandFactory&quot;)]<br>public class QuestsCommandFactory : ScriptableObject<br>{<br>    public List&lt;QuestViewModel&gt; Quests;<br>    public IQuestsFacade QuestsFacade = new QuestsFacade();<br><br>    public LoadQuestsCommand LoadQuests()<br>    {<br>        return new LoadQuestsCommand(Quests, QuestsFacade);<br>    }<br>}</pre><p>Finally, if we modify out component to use the Command Factory, it looks this way:</p><pre>public class LoadQuestsOnStart : MonoBehaviour<br>{<br>    public QuestsCommandFactory CommandFactory;<br><br>    public void Start()<br>    {<br>        CommandFactory.LoadQuests().Execute();<br>    }<br>}</pre><p>If we apply these changes to the initial architecture diagram, we’d obtain the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*mMY94rnWnu_mA0ATAZWUQg.png" /></figure><h4>Final Thoughts</h4><p>Neither this nor any architecture design is a silver bullet that will be perfect for all cases. As you can imagine, some architectures suit better for some contexts depending on the technologies, workflows, or other characteristics of the project. So why do we like <em>this one</em> more than others? Well… it feels like this architecture can talk Unity. And that’s because in some way it does not go against the nature of the engine.</p><p>Let’s think about it. If you didn’t think of having an architecture at all, your intuition-guided use of Unity would be to just create components for any piece of feature you’d need (we’ve actually all been there) and to put the logic of those requirements inside the components. Then, whenever you’d need different data to be used across different screens you would probably create <em>Scriptable Objects</em> and make the <em>components </em>reference them in order to modify and read their information. You see, you’ve given your code a more <em>data-oriented </em>approach, which adds up to the already <em>component-oriented </em>characteristic of Unity and, without even realizing you almost already used the MVVM architecture in your project. The next big step is just adding <em>commands </em>in the middle of the road which helps you keep your game logic well-separated and reusable by any component without the need of duplicating it. And…</p><p>that’s pretty much it!</p><p>As you see, the daily task of coding a game feature using this architecture feels a lot like you are doing what you would normally do in Unity, with just a bit of extra considerations in order to keep the code reusable, maintainable, and organized across a whole big project with lots of team members involved.</p><p><a href="https://gitlab.com/etermax_blog/mvvm-blog">etermax_blog / mvvm-blog · GitLab</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff211ca478fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/etermax-technology/a-component-based-architecture-for-unity-ff211ca478fe">A component-based architecture for Unity</a> was originally published in <a href="https://medium.com/etermax-technology">etermax technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>