<?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 Danilo Oliveira on Medium]]></title>
        <description><![CDATA[Stories by Danilo Oliveira on Medium]]></description>
        <link>https://medium.com/@dmendoncaoliveira?source=rss-862d7ebaf8f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*La0R3tyhrv0tGRKcszpUHQ.png</url>
            <title>Stories by Danilo Oliveira on Medium</title>
            <link>https://medium.com/@dmendoncaoliveira?source=rss-862d7ebaf8f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:09:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmendoncaoliveira/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[Go and the absence of generics]]></title>
            <link>https://dmendoncaoliveira.medium.com/go-and-the-absence-of-generics-1c64e3aafc7f?source=rss-862d7ebaf8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c64e3aafc7f</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Danilo Oliveira]]></dc:creator>
            <pubDate>Sun, 20 Dec 2020 17:12:37 GMT</pubDate>
            <atom:updated>2020-12-20T17:25:16.430Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Java programmer with some experience in C# and Scala, I was always skeptical about how good a statically typed language can be without generics. Some users are glad Go does not have generics, because it would be against the core values of the language (simplicity and minimalism). Other users affirm having generics wouldn’t be a bad thing to have, but it’s completely okay to live without them. With this skepticism in mind, I learned the language so I could do some criticism and avoid getting debunked for not knowing the language. Just kidding, the language is useful on its own and fun to learn, after doing some research I decided it would be worthy of learning.</p><p>Java without generics was horrible. Dealing with general purpose data structures (list, maps, and trees) or general purpose algorithms (sort, find) implied using unsafe code with instance-of and typecast. I understand Go is different because it has maps and slices baked into the core of the language, therefore using Go does not feel like using Java 1.4. It is not entirely true saying that Go does not have generics: functions like make, copy, and append, <strong>are</strong> generic: they work with any list of any type. Yet you are limited to use what is provided for you, you cannot (yet) create your own generic code.</p><p>How comfortable is it to program with such language? Let’s find out with some examples.</p><h3>Generic set type</h3><p>After maps and lists, sets are the third best data structure we have at disposition when writing algorithms (this is personal opinion). Go does not provide sets as first-class citizens like maps and slices. This is okay since we have maps, you just need to use a map and place the elements as the keys. The values can be either a constant value like true or 1. Checking if an element belongs to the set can be done via the _, ok := map[element] idiom.</p><p>Doing union, intersection and other operations must be done manually, but 99% of the time when I use sets, I just add and check if elements belong to the set. So far, so good. For me, it is okay to use maps as sets.</p><h3>Generic collections other than slices and maps</h3><p>Lists, maps, and sets alone can provide me everything I need in terms of data structures for my algorithms. Yet, some algorithms require more specialized data structures like ordered sets/maps or priority queues. If Go does not provide them as first class citizens like maps and slices, and generics are not included in the language, what should we do instead?</p><p>Well, in this case, we are unlucky. Either you write the implementation focusing on a specific type, or you use the wildcard type, interface{}. Using the first option is quite limiting since it restrains the usability of the structure, and the second option is basically Java 1.4.</p><p>You can see this implementation of a treeset follows the second approach:</p><p><a href="https://godoc.org/github.com/emirpasic/gods/sets/treeset#Iterator.Value">https://godoc.org/github.com/emirpasic/gods/sets/treese</a>t</p><h3>Sorting and shuffling slices</h3><p>“How do I sort a slice in go?”</p><p>“How do I shuffle a slice in go?”</p><p>I submitted those questions to Google when I was trying to get some small program done, while I was learning the fundamentals of the language. Before I looked at the answer, I thought:</p><p>“Maybe they will have a generic sort implementation for primitive values and strings, but for structs, they will rely on the interface{} type, like the qsort function does in C using void* pointers”</p><p>The answer was not what I was expecting, it was quite surprising to see how it is done. By having good support for closures, sorting an slice can be done in a slightly better way than C (from <a href="https://yourbasic.org/golang/how-to-sort-in-go/">this tutorial</a>):</p><pre>family := []struct {<br>    Name string<br>    Age  int<br>}{<br>    {&quot;Alice&quot;, 23},<br>    {&quot;David&quot;, 2},<br>    {&quot;Eve&quot;, 2},<br>    {&quot;Bob&quot;, 25},<br>}<br><br>// Sort by age, keeping original order or equal elements.<br>sort.SliceStable(family, func(i, j int) bool {<br>    return family[i].Age &lt; family[j].Age<br>})</pre><p>This is a very smart trick: to rely on a closure that uses the index of the positions as parameters and the original list as an <a href="https://www.lua.org/pil/27.3.3.html">up-value</a>/<a href="http://www.lispworks.com/documentation/lcl50/aug/aug-110.html#:~:text=Common%20Lisp%20uses%20function%20objects,needed%20beyond%20their%20normal%20lifetime.&amp;text=The%20value%20of%20lexical%2Dclosure,refers%20to%20the%20variable%20a%20.&amp;text=Since%20*a*%20is%20a%20special,no%20lexical%20closure%20is%20created.">lexical variable</a> from the closure. This is fair enough for me, it’s not a bad way to sort lists with a custom comparator.</p><p><a href="https://yourbasic.org/golang/shuffle-slice-array/">Shuffling slices</a>, however, looks uglier:</p><pre>a := []int{1, 2, 3, 4, 5, 6, 7, 8}<br>rand.Seed(time.Now().UnixNano())<br>rand.Shuffle(len(a), func(i, j int) { a[i], a[j] = a[j], a[i] })</pre><p>It is necessary to give as an argument a lambda for swapping the elements of two different positions. It does not feel pleasant to write and read, in my opinion, since with any other language (dynamic or static with generics) we can do something like “list.shuffle() or Collections.shuffle(list)”.</p><h3>Removing elements from the middle of a slice</h3><p>Appending values to a slice is quite easy with the append function, however, there is no function to remove an element from a slice. Looking for a way on how do this, I found the <a href="https://stackoverflow.com/questions/37334119/how-to-delete-an-element-from-a-slice-in-golang">following answer</a>:</p><pre>func remove(slice []int, i int) []int {<br>  copy(slice[i:], slice[i+1:])<br>  return slice[:len(slice)-1]<br>}</pre><p>You need to resort to slice trickery and use the copy function just to remove an element from the middle of a slice. Once again the language does not feel pleasant to use, knowing that in any other language I can just type “list.remove(i)” and get the job done. Removing an element from the first or last position is slightly easier:</p><pre>slice = slice[1:len(slice)]<br>slice = slice[:len(slice)-1]</pre><p>But don’t forget to set the removed element to nil if it is a pointer, so the GC can collect it.</p><h3>Conclusions</h3><p>Go is a very intriguing language. In the time where all other languages are getting more bloated and introducing more aspects of declarative programming, Go is making a tremendous success despite being as imperative as Pascal or C (its design is directly influenced by both languages). I don’t deny it has many right points and that it is a very capable language, however, the lack of generics can be a bit frustrating.</p><p>I’ll continue to learn and use the language, but I still prefer Java, C# and Scala. If I wrote any incorrect argument, or if some code example could be better done in a better way, I would appreciate to know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c64e3aafc7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some advice for aspiring PhD students from someone who struggled on being a PhD candidate (part I)]]></title>
            <link>https://dmendoncaoliveira.medium.com/some-advice-for-aspiring-phd-students-from-someone-who-struggled-on-being-a-phd-candidate-part-i-56285aa0ae83?source=rss-862d7ebaf8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/56285aa0ae83</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[phd]]></category>
            <dc:creator><![CDATA[Danilo Oliveira]]></dc:creator>
            <pubDate>Sun, 24 May 2020 14:42:34 GMT</pubDate>
            <atom:updated>2020-05-24T19:03:09.429Z</atom:updated>
            <content:encoded><![CDATA[<p>PhD is the highest academic title you can ever earn¹. It can boost your career, it can please your ego, or it will be a necessary step if you aim to be a professor in some university. The third item of this list was my main motivation when I applied for a PhD position at Federal University of Pernambuco. The professorship was a good career path to pursue in Brazil at that time: many campuses were being built in the countryside and there was a demand for professors to lecture at them. In some countries, however, there is little or virtually no expansion of this segment in the educational system and the only chance to get a professorship position is waiting for someone to retire and compete with thousands of talented researchers in your expertise field. In these countries, however, people are still motivated to get a PhD for whatsoever reasons.</p><p>If you are finishing your master’s degree and you are considering applying for a PhD position afterward, it would be advantageous to read or listen from someone who finished a PhD to know what you should do and what you should avoid during your PhD years. There are countless blog posts and some books about the subject, but I still want to share my personal experience, because it’s very different from what I read. If I could travel back to the past with this information, surely I would have done things in a completely different way, <strong>or maybe I wouldn’t even apply for a PhD in the first place.</strong></p><p>As this PhD I’ve done was an important and remarkable part of my life, I have a lot to say about it. Therefore I will have to split what I want to share in more than one article, otherwise, it would be tiring to read it all at once. In this article we are going to consider two important questions (often ignored in other writings) related to PhD: how is your life going to be <strong>after </strong>you finish the PhD, and how you are going to survive <strong>during </strong>the PhD.</p><h3>Things to consider before applying for a PhD</h3><h4><strong>How are you going to survive after the PhD?</strong></h4><p>Before you apply for a PhD position, you have to consider if this is the right choice for you.<strong> </strong>Having a PhD doesn’t mean you are going to have a successful life afterward. I knew that it was possible for my country to face some recession and the number of open positions for professors in computer science would diminish. Ironically, this happened exactly during the first year of my PhD: we were hit by a very profound economic recession in 2014 that continued for the next five years. I always knew I could apply for a teaching position in private universities or I could go back to the IT segment and be a developer like I was in the past. This would go against my initial plans of being a government employee in a public university, but still it was a fair plan B.</p><p>Unfortunately, lots of PhDs and PhD students aren’t lucky as I am to have IT skills (which are needed everywhere), and this means that enrolling in a PhD can be a risky move depending on the research theme. There is a chance that you go very deep in a complex research theme and afterward there is nothing for you. No post-doc position, no teaching/professorship position, and no demand for your skills in the industry. I’m not stating that some areas of knowledge are useless, but the main possible employer for many PhDs is the government, either as a post-doc or as a professor. The government is the sole entity who cares about preserving some aspects of our culture, of our music, of our ancient languages, among other things, that would be otherwise ignored by the society according to the rules of supply and demand. Also, the industry is driven by return-of-investment, thus, there’s little incentive for them to invest in more abstract and theoretical topics in science.</p><p>Therefore, you have to think with intense care about your future after the PhD and be prepared to change plans later, especially if the job market cannot easily make use of your skills. Even if you complete a PhD in some non-popular theme in history, literature, philosophy, or sociology, you always can earn money and acknowledgment by creating a Youtube channel (I’m serious, look at <a href="https://www.youtube.com/user/GeographyNow">this </a>and <a href="https://www.youtube.com/channel/UCNhX3WQEkraW3VHPyup8jkQ">this </a>channel, they are amazing) and promoting your field of expertise for a more general audience, or writing articles for a newspaper using your skills.</p><p>Don’t dive so deep in your research and ignore your career management, because the PhD is not the end of your career (it’s the beginning, instead). I found some sane advice in <a href="https://www.linkedin.com/pulse/5-career-killing-mistakes-phds-make-4-very-common-hankel-ph-d-/">this article</a>. Also consider the situation of your country and your area of expertise. In Brazil, things are quite depressing:<a href="https://www.correiobraziliense.com.br/app/noticia/brasil/2019/03/10/interna-brasil,741968/desemprego-entre-mestres-e-doutores-no-brasil-chega-a-25.shtml"> unemployment rate is 25% for PhD holders.</a></p><h4>How are you going to survive during your PhD?</h4><p>If you are a young and single person, probably you can afford a more frugal lifestyle during your PhD. If you are older and you have a partner and children, it may be difficult to afford to live on the scholarship offered by many PhD programs. In both cases, you may even be jealous of your colleagues earning much more money than you in a normal job in the industry, at some point in your PhD when things get bad. In some countries, being a PhD is the same as having a normal job and you pay the same taxes and have the same rights as any other “normal” worker. This is the case of Germany for some positions: the TV-L 13 category grants a pretty decent salary and this can be very motivating. Unfortunately, not all positions fall into this category: some programs will grant a fraction (of 50 or 75%) of the TV-L 13 salary.</p><p>Things are a bit worse when you are given a scholarship instead of a normal wage. This is the case for Brazil and other countries. You will earn a monthly amount of money that is free of any taxes, but typically it is substantially lower than the salary of the jobs that you could have applied if you haven’t opted for a PhD after finishing your bachelor’s. For many Brazilians PhD candidates, living on a scholarship means living a frugal life. For banking institutions, a scholarship is not a “real salary” because it is too small and it has an end date, therefore you will have problems when trying to finance a house or car, for instance.</p><p>Things are completely bad if you don’t earn money for doing your PhD. This was my case in the first three years of my PhD. Some PhD programs have more positions than they can fund. Therefore, the candidates with the worst CVs (fewer publications, less teaching experience, etc.) will have to continue on their PhDs without any financial aid from the institution they are enrolled. To survive, PhD candidates in this category must have a part time job or be sponsored by someone else. If you have a part-time job at the same time as your PhD, it may be difficult to be productive in your research and your advisor will get angry at you for sure. If you don’t have a part-time job, your only option to survive is being sponsored by your family and you may even have to live under your parent’s home in your late-20’s or 30’s, which is kinda depressing for many of us.</p><p><strong>The means of living during the PhD years will greatly affect your motivation in finishing your research. Having a part-time job during your PhD will drain your time and energy that would be otherwise spent in your research. </strong>Therefore, you must be careful about this issue, as motivation and time+energy are the main ingredients of your PhD.</p><h4>Final remarks</h4><p>Before you enroll as a PhD student you have to consider if this is a worthy move. <strong>Also, there is always a chance of failing at a PhD</strong>, this is not a rare event. It’s not a trivial task to succeed at a PhD: you have to choose a good topic, you have to put a disciplined effort on it over four years (in average), but also you have to actually propose and validate some original idea in your domain and get it peer-reviewed in a good venue. Even if you succeed, things can get harder after you try to land a job while holding this title. The knowledge and skills you developed may not be of interest to potential employers, and you may regret having devoted too much of your life in this endeavor.</p><p>I don’t want to discourage you and I apologize if I did. Being a researcher can provide joy and enlightenment in your life and it will surely be rewarding after you defend your thesis. It can grant you many opportunities that would not be applicable for a bachelor or master of science. However, starting a PhD is a huge commitment, therefore, you must be sure this will be a good idea. <strong>Consider also that I’m on the first year after my PhD, maybe I’ll have a different opinion after ten years. </strong>Someone more experienced and mature will have a different opinion, so you may want to hear from them too.</p><p>In the next article I’ll write about choosing a research topic and your work as a researcher.</p><p>________________</p><p>¹ A lot of people believe that post-doc is a title above PhD, but this is not correct. Post-doc is a job, not a title. Someone who just got his/her PhD, a post-doc, and an associate professor, all of them belong to the same educational level.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56285aa0ae83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The curse of being a programmer: turning everything into a programming problem]]></title>
            <link>https://dmendoncaoliveira.medium.com/the-curse-of-being-a-programmer-turning-everything-into-a-programming-problem-eb5fa0c20404?source=rss-862d7ebaf8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb5fa0c20404</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[programming-stories]]></category>
            <dc:creator><![CDATA[Danilo Oliveira]]></dc:creator>
            <pubDate>Wed, 29 Apr 2020 12:53:18 GMT</pubDate>
            <atom:updated>2020-04-29T16:30:35.339Z</atom:updated>
            <content:encoded><![CDATA[<p>What is the worst part of being a programmer? Is it sitting down for hours straight and killing yourself slowly? Is it tending towards being socially inept, and having more in common with computers than with other fellow humans? When I searched the title of this post on Google I found exactly the same thing I had in mind:</p><pre>(...) I try to automate everything I touch. I can’t help it. It’s the curse of being a programmer.[1]</pre><p>Yes, exactly. Every problem I face in my normal activities, I try to convert it into a programming problem. This is bad because I have only 24 hours per day, on which 8 are sleeping hours, 8 are devoted to my regular job, and I have to use some small fraction of the remaining 8 hours to pursue other endeavors and personal projects. But after working 8 hours writing code in my regular job, I don’t have too much brain energy to spend on personal projects. Yet I keep insisting on converting every problem in a programming problem. The outcome is failing in solving the original problem and having a half-baked and useless piece of code.</p><p>Let me illustrate with some examples. At some point, I realized I needed to keep track of my expenses. Let’s examine the existing options to help with this project:</p><p>“Why not to use Mint or Ynab?”, I asked myself. Nah, let’s avoid spending money on a commercial solution.</p><p>“Why not to use Gnucash then?” — Too difficult to learn and use properly.</p><p>“Why not a damn Excel spreadsheet?” — I never found a good template… It is too cumbersome to automate small things with macros, I pass.</p><p>“I can write my own software” — Why not? It seems a great idea. I can prototype it quickly in Python. Initially, I can use just plain text files to store my data, and I can use Pandas to create nice charts, and… And the ideas keep flowing. I created the FinancesPy project more than one year before the time of writing this post (<a href="https://github.com/danilomo/FinancesPy">https://github.com/danilomo/FinancesPy</a>). The idea still looks promising, but I still don’t use it to track my finances. It is not useful in helping me to overcome my laziness towards tracking my expenses. Probably due to the lack of organization in this area, I wasted much more money than the yearly fee of a great tool like Ynab.</p><p>The same phenomenon happened when I tried to start learning German. I could have used Duolingo since the beginning, or Anki, or Memrise, etc. I opted for writing my own flashcard software, instead. The existing options did not suit my taste, so I decided to write my own (<a href="https://github.com/danilomo/PyLernkarten">danilomo/PyLernkarten</a>). After I started writing the first lines of code, new ideas to make my command line tool “smarter” keep appearing, but I could never finish due to my lack of energy in my spare time. Sadly, the time I spent writing this bunch of scripts could have been employed in actually learning German. Now I have a useless project on my Github that no one will care about and an underdeveloped German skill.</p><p>Okay, the experience was not a complete waste of time, I had some fun and I also improved my programming/Python-programming skills, but I find depressing the fact that I am unable to pursue other activities than programming, with the same passion and discipline.</p><p>[1] <a href="http://ccnmtl.columbia.edu/compiled_sappho/released/how_to_get_pcp_on_the_web.html">http://ccnmtl.columbia.edu/compiled_sappho/released/how_to_get_pcp_on_the_web.html</a>, accessed at 04/29/2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb5fa0c20404" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Turning the compiler into an ally — Part One (getting rid of null references)]]></title>
            <link>https://dmendoncaoliveira.medium.com/turning-the-compiler-into-an-ally-part-one-getting-rid-of-null-references-2e011fcd432?source=rss-862d7ebaf8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e011fcd432</guid>
            <category><![CDATA[null]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Danilo Oliveira]]></dc:creator>
            <pubDate>Fri, 27 Jul 2018 09:06:32 GMT</pubDate>
            <atom:updated>2018-07-27T15:09:18.884Z</atom:updated>
            <content:encoded><![CDATA[<p>Statically typed languages may be cumbersome for small programs, but the compiler of such languages can do wonders for us when dealing with large codebases. The type checker of a statically typed language doesn’t let you pass wrong arguments to a method. Therefore, runtime errors like Ruby’s NoMethodError and Python’s AttributeError will never manifest in your programs, since you cannot compile a program with type errors in static languages. We are encouraged to reason about our abstractions and interfaces since we do not have “duck typing”, and still we want a flexible code which can be easily extended or modified.</p><p>Nevertheless, many programmers (including myself just a few weeks ago) do not put too much thought into how powerful a compiler can be as a programmer’s ally. As a consequence, we neglect the invaluable support it provides, and we stick to certain practices which can turn the compiler “off” and lead us to make mistakes. What does “turning the compiler off” mean? It means not relying on the compiler’s ability to catch errors at compilation time and letting those errors to infect and reproduce in our code without our awareness. We reproduce the behavior of a scripted language (manifesting errors only at runtime) but without all the benefits of a scripted language. The program gets the worst of both worlds.</p><p>This article series aims to show how to turn the compiler into an ally by means of exerting discipline while programming. We need to sustain awareness 100% of the time we are coding and do not employ the bad practices which prevent the compiler acting in our favor. All the things covered in this article were extensively discussed in the past two decades, so the reader can feel there’s no novelty here. Yet, I insist on writing this article, as many programmers still do not acknowledge such practices as harmful and keep using them. I hope I’ll be able to convince some of them to change their programming habits and create more robust programs, when programming in statically typed languages.</p><p>The first point I would like to talk about is:</p><h3>1 - Getting rid of all null references</h3><p>If you want to create more robust Java/C#/C++/etc. programs, please stop storing <em>null</em> references in variables or object’s fields, passing <em>null</em> references as method parameters, and do not allow methods to return <em>null</em> references. Seriously, not even a single <em>null</em> should be allowed in your program at runtime.</p><p>In Java, <em>null</em> values are assumed to be proper values for any reference-typed variable/field/parameter. The most frequent situations we get <em>null</em> pointers are:</p><ul><li>When representing optional attributes of an object. For instance, a tree node can have a “parent” attribute for representing its parent, but the root node does not have a parent at all;</li><li>Some methods may return <em>null</em> instead of a proper object when an error happens during its execution (possible reasons are: 1) it got incorrect parameters; 2) it fails to read something from the disk; 3) it fails to parse some XML, etc.);</li><li>When accessing non-existent keys in <em>HashMaps</em> with get , null references are returned instead of an exception being thrown;</li><li>When not completely initializing an object on its creation. We expect the caller to invoke object.setSomething(x) to pass the missing piece of information that the object needs to work.</li></ul><p><em>NullPointerException </em>is by far the most common cause of runtime errors in Java programs. They are so painful to deal with since we do not promptly know when we failed to provide a proper instance, and we need to backtrack the entire program to find where the bug was introduced. For further clarification, please consider this example below:</p><pre>(Somewhere.java)<br>Something obj = getSomething(); // this may fail and return a null<br>SomethingElse selse = new SomethingElse(obj);</pre><pre>...<br>(SomewhereElse.java)<br>SomethingElse selse = getSomethingElse();<br>selse.getSomething().doSomethingUseful()¹; // BANG!</pre><p>In some Java class (Somewhere.java) we invoke an operation to create an object and pass its reference to another object. If the getSomething() operation fails and we let it return a <em>null</em> reference, it creates a problem. If sometime later, in another class, or even in another thread, we make use of this object’s attribute for doing something useful, a disgusting <em>NullPointerException</em> will pop up in our faces. What happens next is: we need to debug the hell out of our program and go back to Somewhere.javain order to discover we failed to provide a proper Something object to our SomethingElse object.</p><p>The compiler cannot enforce us to do a if(obj != null){ ... test every time we touch a reference. If we let <em>null</em> references to spread in our program, it will be as loose as any scripted language program with many potential errors to be manifested at runtime.</p><p>I’ll repeat it: <strong>do not let <em>null</em> references to be stored as variables/fields, do not let methods to return <em>null</em> when they fail to do something, do not pass null references as parameters, and beware <em>Hashmap.get(key)</em> since it can return a <em>null</em> reference in case of a missing key.</strong></p><p>Be conscious at every second while you are programming. When you feel the need of using a <em>null</em> reference, consider instead consider instead the advice on the following sections.</p><p><strong>1.1 - Using the null object pattern.</strong></p><p>When representing a missing object, sometimes you can use a specific object living on the heap instead of a damn <em>null</em> reference. For instance, having children nodes is optional for a node object (a leaf node does not have children nodes). So, the null object for representing the children of a leaf node is an empty list. Using a <em>null</em> reference instead of a empty list is a bad decision in this case.</p><p>A null object usually contains empty operations instead of some behavior. It is different than a null reference as it is a live object and it is able to respond to method invocations without breaking the program at runtime. It follows the expected interface and the compiler can guarantee this for you. It just happens that it does not represent a meaningful object and it may do nothing instead of doing something. As an example, assume you created a graphical toolkit like Swing. Assume also you want to let a Window object to have an optional listener object property to let its users to be notified when the <em>closed/maximized/restored/minimized</em> events occur.</p><p>The most naive approach for implementing this is:</p><ol><li>Creating a WindowListener field and not initializing it in the constructor (letting it be null);</li><li>Providing a setListener method in order to third parties be able to specify a custom listener;</li><li>Using if(listener != null) every time you want to notify the listener, if it exists.</li></ol><p>If you follow the naive approach, do not expect the compiler to warn you when you forget to use the <em>if-not-null </em>test every time you want to touch the reference. The (Java) compiler have no means to do this for you. So, why not use a null object instead? Just initialize the listener field with a null object, like:</p><pre>private WindowListener listener = new WindowListener(){<br>public void windowOpened(){}<br>public void windowMaximized(){}<br>...<br>}</pre><p>Then you can safely use the object without caring if it was initialized or not. The methods on the null object are empty and completely harmless to your program.</p><p>Some final observations about the null object pattern:</p><ul><li>Is it the ultimate technique against <em>null</em> references? <strong>Absolutely not. </strong>Sometimes you cannot afford using a null object, and you want to have something being done at all. If so, you need to put more thought into your program design. Each particular case will be different, and I cannot give you an ultimate advice which will work for every situation. <strong>Non expected null objects can “swallow” method invocations and introduce subtle bugs in your program, like an empty “catch” swallowing exceptions which should be handled by the program;</strong></li><li>What about performance and memory usage? If spawning lots of the same null object is an issue, just use a singleton or a static final attribute. You also should consider using the Flyweight pattern in some situations.</li></ul><p><strong>1.2 Using Map.getOrElse( key, defaultvalue ) instead of Map.get</strong></p><p>Maps are a very useful data structure, but sadly the Java designers opted for allowing <em>null</em> references being returned when a get is called with a non-existent key as a parameter. I would let it throw a <em>RuntimeException</em>-based instead of returning a <em>null</em> reference to ensure a fail-fast approach, but I’m not the chief Java architect. This is what Python does, by the way. Accessing a non-existent key in Python throws a KeyError.</p><p>How can we make use of this nice data structure in Java without the perils of <em>null</em> references?</p><p>Well, it would be nice having a Map decorator like this:</p><pre>public class NullNotAllowedMap implements Map&lt;K,V&gt;{<br>private Map&lt;K,V&gt; map;</pre><pre>public NullNotAllowedMap(Map&lt;K,V&gt; map){<br>   this.map = map;<br>}<br>public NullNotAllowedMap(){<br>   this.map = new HashMap&lt;&gt;();<br>}<br>...<br>public V get(K key){<br>   if( ! map.containsKey(key) ){<br>      throws new KeyNotFoundException(key);<br>   }<br>   return map.get(key);<br>}</pre><p>If there is something like this in Maven central, please let me know.</p><p>An alternative is using getOrDefault, which takes a default value as a parameter and returns it if the key is not found. By doing this, you prevent a <em>null</em> reference to be generated. You can argue with me that you are still obligated to check if the returned object is equal to the default value and that it would be the same as using get and a if(obj != null) test. Let me tell you something: you couldn’t be more wrong!<strong> </strong>Why? Because by doing so you affirm that <strong>NULL REFERENCES ARE NOT ALLOWED TO EXIST IN YOUR PROGRAM</strong>, and this is what I’m trying to convince you to do. You also can combine this approach with the null object pattern method, and no test will be necessary (in some circumstances).</p><p>Of course, another sane alternative is always calling containsKey before calling get. The compiler cannot enforce we always are protecting get calls with a containsKey call and a conditional statement. However, make sure to protect yourself against nulls being retrieved from a Hashmap object.</p><p>In other words: for any given <em>Hashmap</em>, get is a <strong>partial function</strong>. Partial functions are not defined to all possible parameter values. The get method is not defined to all possible strings, but only to the map’s keys. It is similar to the division operator, which is not defined when the denominator is zero. It is okay throwing an exception when we try to divide something by zero. It is okay to assume programmers will test if the denominator is different than zero before doing the division. Likewise, it is okay to assume <em>Hashmap</em> users will invoke containsKey before getting anything. The division operator can also produce some strange value like “INFINITY” or “NOT A NUMBER”. This is so wrong. They are not even numbers. By allowing a division operation to generate an INFINITY/NaN value², errors can be silently introduced in our program. Our program state may become inconsistent and this can be difficult to detect. Allowing Hashmap.get to return null references hurts our programs in the same way.</p><p><strong>1.3 Using Optional&lt;Type&gt; instead of Type to indicate that you are dealing with a potentially missing attribute.</strong></p><p>By employing the Optional type, it’s easy to become aware that you are dealing with a potentially non-existent object. Rewriting our previous code with:</p><pre>Optional&lt;Something&gt; opt = getSomething(); // an Optional.none() is created if the method fails to create a meaningful object</pre><pre>SomethingElse selse = new SomethingElse(opt);</pre><p>The Optional&lt;Something&gt; opt object can be either an envelope with a proper Something object, or it can be an empty envelope with nothing inside. We can check if the envelope contains an object with opt.isPresent() and we can access the existing object withopt.get(). We still can get an error if we do:</p><pre>obj.getSomething().get().doSomething()</pre><p>without first checking this envelope contains something inside with the isPresent() method. <strong>But this is way less likely to happen in comparison to using null references as proper objects. When you wrap an object with the Optional type, the compiler gets in your way (in a positive sense) every time you try to access it.</strong> When accessing an object boxed with the Optional type, you automatically become aware you are dealing with a potentially missing object, and certainly, you will remember to use the isPresent test. You also can operate it via the flatMap method, which also is nice.</p><h3>What the compiler has to do with null references, null objects, default values, and optional types? How can the compiler be our ally in this sense?</h3><p>By letting null references being stored and being forwarded in our programs, we end up with broken abstractions/interfaces. A null reference does not fit in the OOP World. Many programmers think it is okay to use null to represent missing or optional data. However, <em>null</em> is a poor abstraction for representing missing/optional data. Objects are handled by their references (memory addresses). Valid references point to a living object which is able to respond to messages. A null reference, by the other hand, is just an invalid address pointing to no object. It does not have a type, it does not respond to messages, and it breaks our program at runtime if we try to use it.</p><p>A null reference does not tell anything on how we failed to provide an object. Was it a bug? Was it wrong input data? Is it representing the absence of information? We have no means to guess. <strong>Therefore, using nulls turns our programs ambiguous.</strong> We are not able to distinguish non-nullable types (objects which aren’t supposed to be null in any situation) from nullable types (object which may be absent to represent missing information). <strong>That’s why using null “turns down” the ability of the compiler to detect errors.</strong></p><p>The solution is to employ legitimate types instead of nulls. A null object represents an object with a type. A default (non-null) value has a proper type. Optional&lt;Something&gt; is also a legitimate type: it represents a container with zero or one element of Something.</p><p>By assuming that all references point to proper objects, our lives become easier when developing/maintaining Object Oriented programs. By using a special type (like Optional&lt;*&gt;) to representing potentially missing information, we are able to declare our intention without ambiguity. This practice helps ourselves, the compiler, and our fellow programmers working with the same code.</p><p>Some of you may think the Optional type is cumbersome to use. It is, indeed, but it is cumbersome because the Java language doesn’t help us to protect against nulls. In Haskell, for instance, representing potentially missing date information is easy:</p><pre>data OptDate = Date Int Int Int | MissingDate </pre><pre>isMissing :: OptDate -&gt; Bool</pre><pre>isMissing (Date _ _ _) = False<br>isMissing MissingDate = True</pre><p>Handling OptDate instances is easily done by using Haskell’s pattern matching capabilities. The compiler <strong>enforces</strong> us to deal with the possibility of getting a MissingDate , and we deal with this by employing pattern matching as in the example above. There’s no way in Haskell to break our program by assuming some MissingDate instance is a (Date Int Int Int), and the compiler guarantees this for us. We aim to get this safety level in Java when we use the Optional&lt;*&gt; type instead of using <em>null</em>.</p><p>If you think the Optional&lt;*&gt; type is clumsy, it is not difficult to represent a union type Something | Nothing in a different way:</p><pre>interface Nullable {<br>  public boolean isMissing();<br>}</pre><pre>interface Date {<br>  public int day();<br>  public int month();<br>  public int year();<br>}</pre><pre>interface NullableDate extends Date, Nullable {<br>    public static final NullableDate MISSING = new NullableDate() {<br>    <a href="http://twitter.com/Override">@Override</a><br>    public int day() {throw new UnsupportedOperationException();}<br>    <a href="http://twitter.com/Override">@Override</a><br>    public int month() {throw new UnsupportedOperationException();}<br>    <a href="http://twitter.com/Override">@Override</a><br>    public int year() {throw new UnsupportedOperationException();}<br>    <a href="http://twitter.com/Override">@Override</a><br>    public boolean isMissing() {<br>      return true;<br>    }<br>  };<br>}</pre><pre>class ConcreteDate implements NullableDate {<br>  private final int day;<br>  private final int month;<br>  private final int year;<br>  <br>  public ConcreteDate(int day, int month, int year) {<br>    this.day = day;<br>    this.month = month;<br>    this.year = year;<br>  }<br>  <br>  <a href="http://twitter.com/Override">@Override</a><br>  public int day() { return day; }<br>  <a href="http://twitter.com/Override">@Override</a><br>  public int month() { return month;  }<br>  <a href="http://twitter.com/Override">@Override</a><br>  public int year() { return year;  }<br>  <a href="http://twitter.com/Override">@Override</a><br>  public boolean isMissing() {  return false; }<br>}</pre><p>By using proper types we avoid any kind of ambiguity. A Date d reference will <strong>always </strong>point to a valid date. A NullableDate nd reference can either point to a valid date or represent a missing date. This is the way the Kotlin language works: a Date d reference never stores null (the compiler itself forbids it), and aDate? d reference may contain null. Therefore, when dealing with types without a question mark, we can sit comfortably in our chairs and expect a NullPointerException will never happen.</p><p>________________________________________</p><p>¹ Some of you guys may realize that this example violates “Demeter’s law”, but I’m not a strict adherent of this “law”.</p><p>² Guess WHICH language produces an “Infinity” when you divide something by zero. If you guessed “Javascript”, bingo, you are right!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e011fcd432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is elegant Object Oriented Programming Functional Programming?]]></title>
            <link>https://dmendoncaoliveira.medium.com/is-elegant-object-oriented-programming-functional-programming-2fe46e45660f?source=rss-862d7ebaf8f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe46e45660f</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Danilo Oliveira]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 12:27:17 GMT</pubDate>
            <atom:updated>2018-06-15T06:43:34.921Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I stumbled upon a curious group of programmers on Internet. They claim to know the “true Object Programming”, and condemn some practices normally seen as okay in the world of OOP. The main laws of true OOP can be summarized as:</p><ol><li>Not using NULL references;</li><li>Not using static methods;</li><li>Using only immutable classes;</li><li>Not using instanceof, performing type casting, or using reflection.</li></ol><p>There are many other laws such as: do not put multiple return statements in a function [1], refactor a method if you see a blank line [2], only assignments are allowed inside constructors [3], get rid of all getters [4], and many others. I think those additional OOP laws are quite debatable, but my aim in this post is not judging them.</p><p>The leader of this group is called <strong>Yegor Bugayenko</strong>, and he is quite famous up to now. He already published two books on object oriented programming (Elegant Objects 1 &amp; 2), beside giving talks in some conferences. Unfortunately, I don’t own the books yet, but we can learn a lot about his ideas on his personal website. It is quite apparent I cannot judge the entire EO methodology as I did not read his books, but I would like to write about his strongly opinionated ideas from his publicly available posts.</p><p>In this post, I will examine his “Stream vs Decorators” article: <a href="https://www.yegor256.com/2017/10/10/streams-vs-decorators.html">https://www.yegor256.com/2017/10/10/streams-vs-decorators.html</a></p><p>In this article, he makes a case against Java 8 Stream API. First, he introduces a problem he wants to solve. Then, he exposes three solutions: a procedural solution, a solution based on the stream API, and finally his EO solution.</p><p>Lets take a look at the Java 8 solution:</p><pre>AtomicInteger index = new AtomicInteger();</pre><pre>StreamSupport.stream(probes.spliterator(), false)<br>  .filter(probe -&gt; probe != 0.0d &amp;&amp; probe != 1.0d)<br>  .limit(10L)<br>  .forEach(<br>    probe -&gt; System.out.printf(<br>      &quot;Probe #%d: %f&quot;,<br>      index.getAndIncrement(),<br>      probe * 100.0d<br>    )<br>  );</pre><p>The AtomicIndex workaround is a serious flaw indeed. We cannot blame him for giving a defective solution for proving his point, as this solution is also found in some answers in this StackOverflow thread:</p><p><a href="https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8">https://stackoverflow.com/questions/18552005/is-there-a-concise-way-to-iterate-over-a-stream-with-indices-in-java-8</a></p><p>Yegor states:</p><blockquote>“(…) First, see how easily we got into trouble when we didn’t find the right method in the Stream interface.”</blockquote><p>He is completely right. The Stream&lt;T&gt; interface is so damn difficult to extend. This is an option only experts would choose. Extending an interface is fulfilling a contract, and it is very hard to accomplish this when the interface has such huge amount of methods. Sadly, the Stream API version 8 lacks the zip function so we could process the elements of a stream paired with indexes.</p><p>The solution I found for overcoming this issue was creating an Iterator and converting it to a stream via the utility method StreamSuport.stream . This is my solution:</p><p><a href="https://gist.github.com/danilomo/999c9d209e97218fe58c8a9042ca1261">https://gist.github.com/danilomo/999c9d209e97218fe58c8a9042ca1261</a></p><p>While trying to implement this solution, I found the following issues:</p><ul><li>Java does not have a tuple API, so I end up using javafx.util.Pair. This sucks so hard. The JDK overlords supposedly wanted to prevent us from overusing pairs instead of relying on proper abstractions [5]. I understand the good intentions behind this, but after introducing support for functional programming, tuples are needed;</li><li>Besides zip, Java 8 also lacks dropwhile and takewhile, what is a shame. What is the point of having potentially infinite lazy lists without having takewhile?</li><li>Stream.generate and Stream.iterate are nice methods for generating infinite streams, but what if I want to stop generating items at some point? Java 8 does not allow this. Java 9 introduced an additional iterate implementation which takes a Predicate object. In Java 9 you cannot stop generate , but you can call generate(gen).takewhile(pred)for this purpose.</li></ul><p>We can save our zip utility static method in a library for overcoming its absence in the standard API. In the mentioned StackOverflow thread, many libraries were suggested: Guava, jOOL, etc.</p><p>Now lets take a look at Yegor’s solution:</p><pre>new AndWithIndex(<br>  new Mapped&lt;Double, Func&lt;Integer, Boolean&gt;&gt;(<br>    new Limited&lt;Double&gt;(<br>      new Filtered&lt;Double&gt;(<br>        probes,<br>        probe -&gt; probe != 0.0d &amp;&amp; probe != 1.0d<br>      ),<br>      10<br>    ),<br>    probe -&gt; index -&gt; {<br>      System.out.printf(<br>        &quot;Probe #%d: %f&quot;, index, probe * 100.0d<br>      );<br>      return true;<br>    }<br>  )<br>).value();</pre><p>It uses his Cactoos API (<a href="https://github.com/yegor256/cactoos">https://github.com/yegor256/cactoos</a>) primitives and it heavily relies on decorators. Nothing is done until the value() method is called, so it behaves just the Stream API. It is more flexible than Java 8’s fluent interface approach.</p><p>My point in this post is that Yegor’s solution is quite close to functional programming. For sake of comparison, lets examine the equivalent Haskell code:</p><pre>zip [1..] (map (* 100.0) (filter (\x -&gt; not (x == 1.0 || x == 0.0)) (take 10 probes)))</pre><p>Due Haskell’s non-strict semantics, the list is traversed only once, and we can compose as many zip/filter/map/takewhile/dropwhile/etc. as we want. In Yegor’s solution, each decorator layer express an intention of transforming some input, but it does not touch the actual data structures until it is necessary. This is exactly how Haskell expressions behave in its lazy evaluation semantics. In others words, those Cactoos objects are similar to <em>thunks</em> in Haskell. They express a function application, and capture the parameters to be used, but they do not evaluate immediately. To conclude this text, one more convincing example:</p><pre>List&lt;String&gt; s = Arrays.asList(&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;);</pre><pre>Filtered&lt;Integer&gt; f = new Filtered&lt;Integer&gt;((x) -&gt; x % 2 == 1,<br>                new Mapped&lt;String, Integer&gt;(<br>                        (x) -&gt; Integer.parseInt(x),<br>                        s.iterator()));</pre><p>, and the Haskell equivalent:</p><pre>let s = [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;] in filter odd (map read s)</pre><p>The “Mapped” object behaves exactly like the “map read s” expression. Haskell will not, by default, immediately apply the mapping. The “Mapped” object behaves the same, since Cactoos was also designed with lazy evaluation in mind.</p><h3>Final remarks</h3><p>If EO is functional programming, why not using a functional language instead? I praise Yegor for his originality, but I also follow the mottos “practicality beats purity”, and “in Rome, do as the Romans do”. Java is an imperative language. Trying to stick to a pure declarative solution may lead to a code which is cumbersome to write and read. When programming in Java, I absolutely do not care using imperative programming when it is more convenient. Java does not favor declarative programming, and often it gets in the way when we try to program in this style.</p><p>Nevertheless, the problems of Java 8&#39;s fluent interface design are evident. Not offering tuples/takewhile/dropwhile/zip/etc. is inexcusable for an API which claims to be functional/declarative.</p><p>_______________</p><p>References:</p><p>[1] <a href="https://www.yegor256.com/2015/08/18/multiple-return-statements-in-oop.html">https://www.yegor256.com/2015/08/18/multiple-return-statements-in-oop.html</a></p><p>[2] <a href="https://www.yegor256.com/2014/11/03/empty-line-code-smell.html">https://www.yegor256.com/2014/11/03/empty-line-code-smell.html</a></p><p>[3] <a href="https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html">https://www.yegor256.com/2015/05/07/ctors-must-be-code-free.html</a></p><p>[4] <a href="https://www.yegor256.com/2016/04/05/printers-instead-of-getters.html">https://www.yegor256.com/2016/04/05/printers-instead-of-getters.html</a></p><p>[5] <a href="http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003995.html">http://mail.openjdk.java.net/pipermail/core-libs-dev/2010-March/003995.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe46e45660f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>