Nucu Car Devlog: 0x03 – Android

Hello everyone!

I’ve been working lately on my little project involving Raspberry Pi and .NET, during my free time. Now, I’ve introduced a new technology, Android!

The project needed a front-end and It took me a long time to decide how to implement it and what technology to use.

I was conflicting between a cross platform desktop application or a web application. I initially thought Electron would have been a great choice since it covers both, but it doesn’t work out of the box with gRPC and I needed some proxies which complicated the things on the backend, not to mention JavaScript is horrible in every imaginable way.

Luckily for me, I started dabbing in Android and somehow I manage to get a simple activity up which reads the data from the NucuCar.Sensors component.

It connects to it via gRPC directly. I didn’t expect that setting up gRPC on the Android would be so easy to be honest, you can literally just follow the gRPC tutorial for Java and everything works.

Getting that to work got me motivated and I’ve fixed some bugs in the NucuCar.Telemetry component. This made it possible for NucuCar.Sensors to run for four straight days, non-stop without crashing, it’s still running at this moment.

The component reports sensor reading to Firestore every one minute, since there are 24h in a day it reports around 1.4K readings a day.

At this point I’m pretty proud of this project, I wrote a simple Python script to plot the Temperature, Humidity and VOC resistance from my apartment, for the last 3 days:

As you can see the spikes on 2020-11-28 12:00 indicate that I’ve opened the windows and let some fresh air come into the apartment. The temperature and the humidity dropped while VOC resistance rises. The higher the VOC value the better the air quality.

This project is open-source and it can be found on my Github profile.

Thanks for reading!

LeetCode: Reverse Linked List Solution and Explanation

Hi,

In this article I will explain my solution for the following LeetCode problem: Reverse Linked List.

If you’re interested in solving this problem then please try to spend at least one hour or more on it before looking at my solution.

To help you solve this problem I’ve created the following table:

CurrentPrev
1NULL
21
32
NULL3

Think about how you can use this table to write an iterative or recursive algorithm that reverses the linked list.


The Solution

Bellow you’ll find my iterative and recursive solutions with explanations. The solutions are written in C#.

The Recursive Solution

If you look at the table I made, you may notice that in order to reverse the list all you need to do is make the current node to point to the previous node during each recursive call, then move to the next node.

The stopping condition happens when the current node is null. Then you need to return the previous node, which points to the previous node, which points to the previous and so on. You’ve got a reversed linked list.

The complexity will be O(n) for time, because we need to cover the whole list and O(n) for space, because for every call made the program will allocate a new stack frame.

The Iterative Solution

The iterative solution is similar with the recursive one, except it doesn’t allocate any extra space, it just iterates over the list, modifying it in place.

It updates the current node to the previous one and at the end it returns the last node.

The complexity is O(n) for time and O(1) for space.


using System;

namespace LeetCode.November
{
    public class ReverseLinkedListProb
    {
        public class ListNode
        {
            public int val;
            public ListNode next;

            public ListNode(int val = 0, ListNode next = null)
            {
                this.val = val;
                this.next = next;
            }
        }
        
        // Space O(1) ; Time O(n)
        public ListNode ReverseListIterative(ListNode head)
        {
            ListNode prev = null;
            while (head != null)
            {
                // save next
                var next = head.next;
                // next -> prev
                head.next = prev;
                // prev -> head
                prev = head;
                // head -> next
                head = next;
            }

            return prev;
        }

        // Space O(n) ; Time O(n)
        public ListNode ReverseListRecursion(ListNode head, ListNode prev)
        {
            if (head == null)
            {
                return prev;
            }
            var next = head.next;
            head.next = prev;
            return ReverseListRecursion(next, head);
        }

        public ListNode ReverseList(ListNode head)
        {
            var last = ReverseListIterative(head);
            return last;
        }


        public static void Test()
        {
            var problem = new ReverseLinkedListProb();
            var r = problem.ReverseList(new ListNode(1, new ListNode(2, new ListNode(3))));
            while (r != null)
            {
                Console.Write($"{r.val} ");
                r = r.next;
            }
        }
    }
}

Thanks for reading!

Constructor Injection and Null Object Design Patterns

The Constructor Injection design pattern is a pattern that helps you declare all the required dependencies of a class in it’s constructor.

This is useful because it helps you decouple the code, you can specify an interface instead of a concrete type, remember, program to an interface.

Also, in the constructor it is easier to guard against null objects. The calling code doesn’t have to worry about null exceptions every time it uses a dependency.

Avoid providing defaults when using this pattern, as this will couple the code with a concrete type. When a dependency is not needed, use the Null Object pattern.

We’re going to pickup from the last article and show you how you can modify the application to use the constructor injection and null object design patterns.

The class graph will look like this:

In order to demonstrate this pattern I will introduce a new class MessageTranslator.

class MessageTranslator:
    def __init__(self, translator: Translator, printer: Printer):
        if not translator:
            raise ValueError("Translator cannot be None.")
        if not printer:
            raise ValueError("Printer cannot be None.")

        self._translator = translator
        self._printer = printer

    def translate(self, message):
        return self._translator.translate(message)

    def print(self, message):
        self._printer.print(message)

And modify the Application code to use it:

class Application:
    def __init__(self):
        self._input_listener: InputListener = ConsoleInputListener("< ")

    def start(self):
        print("starting application.")
        message_translator = MessageTranslator(RomanianTranslator(), ConsolePrinter(">"))
        while True:
            user_in = Message(self._input_listener.get_input())
            if str(user_in) == "exit":
                exit(0)

            translated_message = message_translator.translate(user_in)
            message_translator.print(translated_message)

That’s it! You’ve used the constructor injection pattern.

Now, if don’t want to print the translated message into the console we can’t just pass a null Printer, that would raise an exception.

We need use the null object pattern to implement a Printer that does nothing.

class VoidPrinter(Printer):
    def print(self, message):
        pass

If we modify the Application code to use our VoidPrinter, the output would be:

starting application.
 < hello Dev
 < 

Thanks for reading! As always, the full code can be found on my Github.

Composition Root Pattern: How to Write Modular Software

The composition root is a design pattern which helps you structure a software application by implementing a class that builds all the other classes.

In this example we will examine this pattern in Python.

Here’s the object graph of the classes that we’re going to implement:

I have designed a sample application that we’re going to use. It contains three components: ConsoleInputListener, ConsolePrinter and RomanianTranslator and a value object class: Message.

The classes are described as follows:

  • Application: The composition root, glues all the classes together.
  • ConsoleInputListener: Component, it reads string from the standard input.
  • ConsolePrinter: Component, it prints to the standard output.
  • RomanianTranslator: Component, it translates English words to Romanian.
  • Message: Value object, it encapsulates the message string.

Program to an interface not an implementation

Before implementing the Application component, I’m going to define the interfaces for the ConsoleInputListener, ConsolePrinter and RomanianTranslator. I’m going to call them InputListener, Printer and Translator for simplicity.

The reason I’m defining interfaces* is because I want to be able to swap the objects that the Application class references. In Python variables don’t constrain me to any type, but if I’m going to implement other objects, I’d like to have a template so it will help me reduce the number of mistakes that I can make.

Python doesn’t have support for interfaces so I’m going to use abstract classes:

class Printer(metaclass=abc.ABCMeta):
    def print(self, message):
        raise NotImplementedError("print is not implemented")

class InputListener(metaclass=abc.ABCMeta):
    def get_input(self) -> str:
        raise NotImplementedError("get_input is not implemented!")

class Translator(metaclass=abc.ABCMeta):
    def translate(self, message: Message) -> Message:
        raise NotImplementedError("translate must be implemented!")

Every class that extends my abstract classes must implement it’s abstract methods:

class ConsolePrinter(Printer):
    def __init__(self, prefix: str):
        self._prefix = prefix

    def print(self, message: Message):
        print(self._prefix, message)

class ConsoleInputListener(InputListener):
    def __init__(self, prompt: str):
        self._prompt = prompt

    def get_input(self) -> str:
        return input(self._prompt)

class RomanianTranslator(Translator):
    def translate(self, message: Message) -> Message:
        words_map = {"hello": "salut"}
        message_words = str(message).split(" ")

        for index, word in enumerate(message_words):
            if word.lower() in words_map.keys():
                message_words[index] = words_map[word]

        return Message(" ".join(message_words))

The Message class, for the sake of completeness only holds a string.

class Message:
    def __init__(self, message):
        self._message = message

    def __str__(self):
        return self._message

And finally, the Application class will glue all the components together and instantiate them:

from input_listener import InputListener, ConsoleInputListener
from message import Message
from printer import Printer, ConsolePrinter
from translator import Translator, RomanianTranslator


class Application:
    def __init__(self):
        self._printer: Printer = ConsolePrinter(">")
        self._translator: Translator = RomanianTranslator()
        self._input_listener: InputListener = ConsoleInputListener("< ")

    def start(self):
        print("starting application.")
        while True:
            user_in = Message(self._input_listener.get_input())
            if str(user_in) == "exit":
                exit(0)

            self._printer.print(self._translator.translate(user_in))

The main method will just run the Application:

from application import Application


def main():
    app = Application()
    app.start()


if __name__ == '__main__':
    main()

Running the application would output:

 starting application.
 < hello Denis!
 > salut Denis! 

Now, most real world applications aren’t this simple, the reason we went through all this code in order to implement a simple hello world is the following: Imagine that you have 10 translators: English, French, German… and two Printers: Console and File.

You could modify the application code to take in two parameters: translator and printer use the arguments to instantiate the correct translator and printer without needing to change the other classes. You can add as many printers, translators and input listeners as you wish. That’s a huge benefit.

If you were to inline all the code in a single class, adding more translations and more printing options would have been very painful and frustrating.

I hope my article gave you some insight into the Composition Root pattern, if I made any mistake please feel free to correct me. 🙂

The full code is on my Github.

Thanks for reading!