In relationship with thoughts

Writing is hard. You need to have coherent, preformed thoughts that you want to transfer to some kind of a document. Thoughts are not something that is learned, their origin is yet another mystery, but at least  we can say that they are the reflection of one’s mind. So in order to have coherent thoughts you need to have a coherent mind, achieved either through training or be some kind of born thoughts genius. You can learn a lot about some person by reading or listening to them, it’s a glimpse into their mind. You can learn a lot about yourself by writing, slowing down your thoughts. It’s calming and sexy.


Coding on the other hand is much easier. Not that I want to trivialize it, it’s a valuable skill, but it’s something you can master by learning, trying, practicing. Mindfulness practitioners would argue that is the same with the mind, and probably they are right, but there is quite a difference between creating a thought, compressing an idea into a language in contrast to writing a command or an expression. For the latter you need the former. Good thing the former isn’t required to be always rational.

Both of these aspects are playing with a similar notion although their nature is different. Additionally, we can also say that inspiration plays a major role, but how does it interact with the mentioned actions? You don’t need to be inspired to code or to write, but most of the time, scripts that were written by an inspired mind are holding a finer quality than the non-inspired works. But, do we need inspiration to write some random code about validating a database transaction? Don’t think so (I’m not counting pay-check as valid inspiration).

Maybe if we started interacting with the machine as evolution nurtured us to communicate, things will get better. At least for the code reviewers. It will be like reading articles, gauging the author’s reasoning through actual human words and sentences. Kudos to all the programming languages that try to be as much prose-like as possible, but it’s not that that.

Let’s see how I assume people approach writing or coding. I can only speak for myself because until now I still haven’t been able to read other people’s minds. So the only thing I have is some anecdotal evidence, invented by myself only.

For example we can start with reasons to do it. Writing – to express something, coding – to express something. Writing – to create memory imprints that can be referenced indefinitely, coding – to create memory imprints that can be referenced indefinitely. Writing – to guide, communicate, coding – to guide, communicate. So much common traits, yet so much difference, so much fallacy in the logic of comparing random uncategorized attributes. Semantics are hard.

Then, we can reason about why we do it. Writing a program most of the time is a problem solution. Code essence is sourced from the need of solving a problem. Making something simpler is part of the solution, it dissolves the problem bit by bit. Writing an article is sometimes a problem solution, but quite often is a problem creator too. Anyhow, there are limitless answers to why do it.

It’s interesting to see how doing things like writing or coding, can actually have an opposite effect on the mind. Doing them will actually train your mind. Like keeping a dairy or keeping logs of your day-work. It is amazing to notice that inspiration and motivation sometimes work in the opposite direction. You can’t do a thing, because you lack motivation. Then you start doing something with the largest friction there is and suddenly – boom – you are starting to get motivated to continue.

I’ll stop myself now, mainly because I’m losing the coherency of my thoughts. I can return to this sometimes, but since probably I wouldn’t, I’ll just break here. Writing is hard, but rewarding.

Don’t think that I will say goodbye without leaving some inspiration.

A Groovy parser for CSV files

Parsing CSV these days is pretty straight-forward and not a big deal especially when we have the handy libraries from Apache Commons (I’m talking bout Java world). In this post I will give you an example how to use the Apache Commons CSV with the magic of Groovy and its closures so it can look and feel a little more fun because parsing in general is job for sad people (not kidding).

We’ll make ourself a simple Groovy class that will hold a reference to the CVSParser file, and a reference to the headers and the current record/line of the file that we will iterate with the closure delegate set to the instance of this CSVParserUtils class.

Something like this:

class CSVParseUtils {

    CSVParser csvFile
    def record
    def headers

    CSVParseUtils(String fileLocation) {
        def reader = Paths.get(fileLocation).newReader()
        CSVFormat format = CSVFormat.DEFAULT.withHeader().withDelimiter(delimiter)
        csvFile = new CSVParser(reader, format)
        def header = csvFile.headerMap.keySet().first()
        headers = header.split(delimiter as String)
    }

As we can see it’s a constructor that takes the location to the CSV file that we want to parse, creates some default parsing format and generates new CSVFile that holds the CSV data.

As we see parsing is easy, but it’s better when we can transform the data on the run as we loop it. For that reason we will define a method called eachLine that will take a params Map and a Closure that will have access to the record/line instance and will do something with it.

/**
 * List each line of the csv and execute closure
 * @param params
 * @param closure
 */
def eachLine(Map params = [:], Closure closure) {
    def max = params.max ?: maxLines
    int linesRead = 0
    def rowIterator = csvFile.iterator()
    closure.setDelegate(this)

    while (rowIterator.hasNext() && linesRead++ < max) {
        record = rowIterator.next()
        closure.call(record)
    }
}

It’s nothing special only a simple loop that iterates through the iterator and calls the closure with the given record for that line as a closure argument.

How to use it?

def parser = new CSVParseUtils(fileLocation)
def result = [:]
// first 2 lines without header
parser.eachLine([max: 2]) { CSVRecord record ->
    result.put(record.recordNumber, record.values.size() > 4 ? 
             record.values[0..4] : record.values[0..record.values.size()])
}

We imagine that we need only the first 2 lines and the first 5 columns or something like that.

As you can see this closure loop is not specially connected with CSV, it’s just a clean way to iterate through any textual file line by line and do something with it. As a matter of fact you can use the BufferedReader which has method eachLine too.

The source code for this whole example can be found on github.

Thanks for reading.

Passing by ‘reference’ in Java

One of the first things that every Java programmer learns (or should learn) is that method parameters in Java are passed-by-value. That is the only truth and there is no so called ‘reference’ passing in Java. Every method call with parameters means that their value is copied in some memory chunk and then they are passed (the copied memory) to the local function to be used.

What is more important though is of what type is the parameter that is passed. Generally there are two different data types: primitive (int, char, double etc…) and complex aka objects (Object, array etc…). The thing that matters is what is the ‘value’ of them when they are used in parameter passing.

When we are passing parameters of primitive type we are passing the actual value of it. So if we pass an integer with value of 4, then the function will receive an integer with value of 4 as parameter value. However, if we pass parameter of complex type let’s say some object of class Company then the function will actually receive the pointer to real object location in memory. Or in Java terms, it will receive the copied value of the reference (address) to the Java object that we want to pass and use.

If in C++ we have: Company *c; to get the pointer , then in Java we have Company c; . It’s pretty much the same, the difference is how things are designed and implemented under the cover.

If we understand this, then we realize that even if there are no out parameters in Java when defining and implementing methods, we can still use the reference advantage to program that thing by our self.

To get things clear and imagine the picture we should actually see the picture, I mean the code.

For example we can use an array of size one to be our data holder. Passing and mutating data this way will change the real value that we want to be changed. An example code, try it:


package com.groggystuff;

/**
*
* @author Igor
*/
public class JavaArguments {

/**
*
* @param argument
*/
public static void mutate(int argument){
argument++;
}

/**
*
* @param argument
*/
public static void mutate(int[] argument){
argument[0]++;
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// example pass by value
int i = 4;
System.out.println("Value of 'i' before mutation: "+i); //prints 4
mutate(i);
System.out.println("Value of 'i' after mutation: "+i); // prints 4

// example pass by value too
int[] j = new int[1];
j[0] = 4;
System.out.println("Value of 'j' before mutation: "+j[0]); // prints 4
mutate(j);
System.out.println("Value of 'j' after mutation: "+j[0]); // prints 5

}

}

Thanks for reading,

I hope this post will be helpful to you in solving the coding mysteries in life, or something similar.

Please comment if you feel that  your comment is needed. Or comment at will, just to say hi for example.