How to get libcore sources for HttpUrlConnectionImpl.java and other classes missing from the base android SDKs

November 11, 2013 @ 10:40 am Posted to Android, Java by Antony Koch

I’m doing some work that requires the usage of the libcore library, specifically using the class HttpUrlConnectionImpl.java or so my trusty IntelliJ debugger tells me.

Unfortunately, these sources aren’t shipped with the standard sources that come with your android sdk in the sources directory, and you have to do some work to get them up and running.

Here’s the steps I took to allow me to step into the classes and see what’s going on.

First, you need to pull down the libcore sources from google into a location on your computer:

git clone https://android.googlesource.com/platform/libcore

Now visit the libcore site and find the tag representing the version of the android OS you’re using (or the one your IDE is bound to source-wise. Mine was android-4.1.2_r1 which I found by clicking on “more” at the bottom of the tag list. This presented me with the list of tags

From here, I copied the name of my tag, and in terminal, after checking out the source, I executed


cd libcore

git checkout -b tags/android-4.1.2_r1 android-4.1.2_r1

This checkout out the tag I required into a new branch on my machine. Then, in finder, I located the folder ./luni/src/main/java and copied the libcore folder into my <sdk>/sources/android-16 folder and hey presto, I could now step through the source!

No comments (click to be first!)

OO Principles, #1: Tell don’t ask

October 30, 2013 @ 8:21 am Posted to .Net, Java, OO by Antony Koch

I first heard “Tell don’t ask” during a course being given by ThoughtWorks and it’s certainly one of a set of phrases and one-liners that run through my head when coding.

I find that a core set of easy to remember principles help govern my coding both during the planning, implementation and refactor and ultimately save me quite a bit of time in the process. One could argue that I’m performing a miniaturised version of Agile in my head, holding a planning session, then performing code reviews before having a retrospective, all in the space of a few minutes.

The main principal behind “Tell, don’t ask” (which I’ll refer to as TDA from now on) is that you should tell your objects what you want them to do, rather than asking them about their state and performing additional callsbased on the answer. This encapsulates the business logic in the correct place and can prevent mutable properties from leaking to external classes where their state can be changed incorrectly, causing a direct and negative effect on the system’s overall state.

Example

Here’s a trivial example but hopefully it helps to explain the principle in greater detail.

public class Converter {
    private boolean convertFromBase;
    private IMap mapper;

    {
        convertFromBase = false;
        mapper = new XmlResponseMapper();
    }

    public boolean getConvertFromBase() {
        return this.convertFromBase;
    }

    public void setConvertFromBase(boolean convertFromBase) {
        this.convertFromBase = convertFromBase;
    }

    public MappedObject createFrom(Response response) {
        return mapper.map(response);
    }

    public MappedObject convertFromBase(Response response, MappedObject mappedObject) {
        return mapper.map(response, mappedObject);
    }
}

So here we have a simple class that performs conversion to either a fresh instance of an object, or maps properties from the response into an existing object. Nothing too daring. Let’s look at an example of this object’s consumer:

public class ResponseConsumer {
    private Converter converter = new Converter();
    private MappedObject mappedObject;
    public ResponseConsumer(MappedObject mappedObject) {
        this.mappedObject = mappedObject;
    }

    public MappedObject handleResponse(Response response) {
        converter.setConvertFromBase(mappedObject != null);
        if (converter.getConvertFromBase()) {
            return converter.convertFromBase(response, this.mappedObject);
        }

        return converter.createFrom(response);
    }
}

This object consumes our convert and based on its own instantiation and state asks the converter if it should convert from base and then calls a different method based on whether the response is true or false. This is awful code and breaks a number of other paradigms in the process, but that only serves to prove the point!

The main focus of this code is the handleResponse method. We tell it to set convertFromBase to a boolean (meaning the class is mutable), then (stupidly, I’ll admit) ask it whether we should convert from base and call convertFromBase if it’s true and createFrom if it’s false. What this code, in effect, is doing is handling the business logic of conversion outside the converter class.

That doesn’t sound right.

So if we were to fix this, how might we do that? Well, for starters, let’s think about the abstraction. We have a response and we want to convert it into an object our system understands. So our class which understands how to handle response should hand off the response, or parts of it, to a class that understands how to convert it. So a single point of entry ‘convert’ would be ideal. Let’s make one! First of all, here’s our response consumer class:


public class ResponseConsumer {
    private Converter converter;

    public ResponseConsumer(MappedObject mappedObject) {
        converter = new Converter(mappedObject);
    }

    public MappedObject handleResponse(Response response) {
        return converter.convert(response);
    }
}

We can see this has been greatly reduced in size, with methods down to a single line, including our new ‘convert’ method. Let’s look at the converter class:


public class Converter {
    private final MappedObject mappedObject;
    private IMap mapper;

    {
        mapper = new XmlResponseMapper();
    }

    public Converter(MappedObject mappedObject) {
        this.mappedObject = mappedObject;
    }

    private boolean getConvertFromBase() {
        return this.mappedObject != null;
    }

    private MappedObject createFrom(Response response) {
        return mapper.map(response);
    }

    private MappedObject convertFromBase(Response response, MappedObject mappedObject) {
        return mapper.map(response, mappedObject);
    }

    public MappedObject convert(Response response) {
        if (getConvertFromBase())
            return convertFromBase(response, mappedObject);

        return createFrom(response);
    }
}

This now holds the logic of conversion, encapsulated within one method: convert. This method knows how to convert and knows it very well, handing off to other (now private) methods. The state of this class cannot be changed now either, making it immutable, therefore allowing instances to be more trustworthy.

The secret here was to first consider how we might tell the class what to do, in this case: convert. Once we realise we only have one thing to convert (a Response) then we should create the class according to that. We should tell the converter to convert and let it do all the dirty work.

Summary

I hope this made some sense, especially as it’s my first attempt at this sort of blog post. I also stopped writing it half way through to go on honeymoon so a bit of a refresh had to happen in order to finish it. The main crux is as soon as you spot branches of code using if/else structures, examine the object(s) upon which your if statement relies. If your if statement is asking another object to fulfill the business logic, that is an indicator to extract that into the object in question as a derived property (C#) or a method (java). Tell it to figure out the boolean value instead of asking it!

No comments (click to be first!)

Java equivalent of C#’s Func

May 3, 2013 @ 11:07 pm Posted to .Net, Java by Antony Koch

If you’re wondering how to translate a .Net Func<T, T1> (up to the 16th item) into comparable java code, then here’s how. First, the C#

public class Car {
  // ID
  public string ModelId { get; set; }
}

public class Account {
  // ID
  public int Id { get; set; }
}
// some code
public void AddIdsToList<T>(Collection<T> collection, List<string> ids, Func<T, string> extractId) {
  foreach (T item in collection) {
    ids.add(extractId.Invoke(item));
  }
}

public List<string> CollectIdentifiers() {
  var car = new Car { ModelId = "Fiesta" };
  var account = new Account { Id = 45 };

  var ids = new List<string>();
  AddIdsToList(new Collection<Car>(car), ids, x => x.ModelId);
  AddIdsToList(new Collection<Account>(account), ids, x => x.Id.ToString());
}

And now, the same in Java using inner classes

public class Car {
  private String modelId;

  public Car(String modelId) {
    this.modelId = modelId;
  }

  public String getModelId() {
    return this.modelId;
  }
}

public class Account {
  private int id;

  public Account(int id) {
    this.id = id;
  }
  // ID
  public int getId() {
    return this.id;
  }
}

interface GetTheIdFunc<T> {
  String getTheId(T item);
}
// some code
public <T> void AddIdsToList(Collection<T> collection, List<string> ids, GetTheIdFunc<T> extractId) {
 for (T item : collection) {
   ids.add(extractId.getTheId(item));
 }
}

public List<string> CollectIdentifiers() {
  Car car = new Car("Fiesta");
  Account account = new Account(45);

  List<string> ids = new ArrayList<string>();
  AddIdsToList(new ArrayList<Car>(car), ids, new GetTheIdFunc<Car>() {
    public String getTheId(Car item) {
      return item.getModelId();
    }
  });
 AddIdsToList(new ArrayList<Account>(account), ids, new GetTheIdFunc<Account>() {
    public String getTheId(Account item) {
      return item.getId().toString();
    }
  });
}

Quite different but conceptually pretty clean and logical really when you consider that an interface offers a contract. Not as flexible on the fly as C#, but not a lot of extra code. Where these internal interface types should rest package-wise is an interesting one though. Any thoughts?

No comments (click to be first!)