Posts Tagged programming

Using Scala to update LiveJournal tags – Part I

Some days ago I started to use the Scala programming language to update my Livejournal tags using its XML-RPC protocol reference. First I had to check if some tags of mine were entered wrong, so I’ve done this Scala program to list all of them:

   1:import org.apache.xmlrpc.client.XmlRpcClient;
   2:import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
   3:import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
   4:import java.net.URL;
   5:import java.util.Map
   6:import java.util.HashMap
   7:import scala.collection.immutable.TreeSet
   8:
   9:object LJListTag {
  10:     def main(args: Array[String]) {
  11:         val config = new XmlRpcClientConfigImpl()
  12:         config.setEnabledForExtensions(true);
  13:         config.setServerURL(new URL("http://www.livejournal.com/interface/xmlrpc"))
  14:         val client = new XmlRpcClient()
  15:         client.setConfig(config)
  16:         val params = new HashMap[String, String]
  17:         params.put("username", "user")
  18:         params.put("password", "password")
  19:         var paramsToServer = new Array[Object](1)
  20:         paramsToServer(0) = params
  21:         val results = client.execute("LJ.XMLRPC.getusertags", paramsToServer).asInstanceOf[Map[String, String]];
  22:         printEachTag(results)
  23:     }
  24:    
  25:     def printEachTag(results: Map[String, String]) {
  26:        var allTags = new TreeSet[String]
  27:        val iterator = results.values().iterator()
  28:           while(iterator.hasNext()) {
  29:             val resultFromRPCData = iterator.next().asInstanceOf[Array[Any]]
  30:             resultFromRPCData.foreach(singleResult => allTags += extractTag(singleResult))
  31:           }
  32:        allTags.foreach(tag => println(tag))
  33:     }
  34:    
  35:    def extractTag(singleResult: Any): String = {
  36:        val tag = singleResult.asInstanceOf[HashMap[String, String]]
  37:        return tag.get("name")
  38:    }
  39:}

Just fill your user and password to have all of your LiveJournal tags printed on the standard output. The experience was so amazing, since you can use all the Java libraries (Scala is fully interoperable with Java and runs on top of the JVM). I used a TreeSet because I wanted print my tags sorted according its alphabetical order. I’m continuously studying Scala and its API, so the code above doesn’t use any advanced Scala constructs. If you have any suggestion about the code or how to use better the Scala constructs, post your comments here. It will be all appreciated.

Tags: , , , , ,

“Salute #{@Ruby}!”

Some times ago I had to parse a XML messages’ file to produce some i18n properties files.

I decided to try it with Ruby, mainly because of two reasons:

  1. I’m continuosly exploring some dynamically-typed languages, like Python and Ruby
  2. I wanted to try the conciseness of programming with closures

So, I used the REXML API to process the XML file. The result code looks like the one below:

   1:require 'rexml/document'
   2:include REXML
   3:englishFile = File.new('englishFileName', 'w+')
   4:spanishFile = File.new('spanishFileName', 'w+')
   5:portugueseFile = File.new('portugueseFileName', 'w+')
   6:errorMessagesFile = File.new("errorMessages.xml")
   7:document = Document.new(file)
   8:root = document.root
   9:root.each_element("Property") do |propertyTag|
  10:  id = propertyTag.attributes['id']   
  11:  propertyTag.each_element("element") do |elementTag|
  12:      elementAttr = elementTag.attributes['otherTag']
  13:      error = elementTag.text == nil ? "" : "#{id} = #{elementTag.text}\n"
  14:      if elementAttr = "pt"
  15:          portugueseFile << error
  16:      elsif elementAttr == "es"
  17:          spanishFile << error
  18:      else 
  19:          portugueseFile << error
  20:      end
  21:  end
  22:end
  23:errorMessagesFile.close()
  24:englishFile.close()
  25:spanishFile.close()
  26:portugueseFile.close()
  27:  

I like to solve this kind of tasks with programming languages (mainly the dynamically-typed ones..) I don’t know very much because it’s an opportunity to put my hands on them! This way I could experience Ruby’s closures syntax, it was really nice and I’m gonna try something new with it often!

*Updated: line 13

Tags: , , , , ,

Bean Validation – Emmanuel Bernard on JSR 303

JavaLobby released an interesting interview with Emmanuel Bernard, the spec lead of of JSR-303: Bean Validation..

One of the important goals of the Bean Validation spec is, as Emmanuel Bernard says, is

to provide a default runtime engine that is used to validate the constraints around the domain model, in Java.

The development team decided to use annotations to express the constraints applied at the domain model. They argued that with annotations the constraints are put directly at the properties in the code, expressing the constraints associated with the property.

I highlighted some interesting parts of the interview:

Bean Validation lets you standardize the way you declare the constraints. So an application developer will just know one way to declare constraints, and just forget about all the different models. There’s no duplication around the validation on the layers.

If you think about a constraint, a constraint is really some kind of an extension of the type system.

Bean Validation lets you validate an object graph using the @Valid annotation. Basically saying, ‘Well, when you validate this object, make sure the associated object is validated as well.’ By the way, even if Bean Validation is primarily annotation focused, there is the equivalent in XML.

Any framework that is having a need to use validation, to apply validation, can either use the runtime engine of Bean Validation or go extract the metadata and play with that. So the user declares it once, in one place, and every framework in the Java space can actually go and either apply the validation routine …

You can listen the podcast of the interview also. It’s very noteworthy to read or listen the interview and see what’s next on validation in Java. Before the Bean Validation API become public to all of us, which framework do you use to validate constraints on the Java platform?

Tags: , , ,

Joshua Block on How to Design a Good API & Why it Matters

In this talk (recorded at Javapolis), Joshua Block presents guidelines about how to design good APIs. I highlighted what i think are the most important parts of the talk:

  • Functionality should be easy to explain: If it’s hard to name, that’s generally a bad sign
  • Good names drive development
  • Be amenable to splitting and merging modules (If names are nasty, take a step back and make things easy to describe)
  • When in doubt, leave it out
  • You can always add, but tou cannot take it out
  • Implementation Should Not Impact API
  • Always omit implementation details
  • Inhibit freedom to change implementation
  • Don’t let implementation details “leak” into API (For example: Serializable, hash functions)
  • Minimize Accessibility of Everything (This maximizes information hiding)
  • Public classes should’nt have public fields
  • API should be easy to learn, read and use: It should be consistent, it’s a little language
  • Documentation matters (Example: Method contract between it and it’s clients)
  • Think of preconditions, postconditions, side-effects
  • Don’t Transliterate API’s
    • What’s the problem it solves?
    • What shoud abstractions did it use?
  • Don’t Make the Client Do Anything The Module Could do
  • Throw Exceptions to Indicate Exceptional Conditions

When you see the talk, post your comments here.

Tags: , , , ,

DomainDrivenDesign: Domain Services or Method on an Entity?

There has been too much discussion on the DDD list regarding where to put the business logic control, whether in a service or entity. Being more specifically, in order to ship an order, the followthings should happen:

  1. Validate that the order can be shipped
  2. Update quantity
  3. Set the status to shipped
  4. Save the order
  5. Send an email to the customer that the order has been shipped

So, nickgieschen suggested the following C# implementations:

1. Everything in the domain:

 1:class Order
 2:{
 3:    IOrderShippedNotificationPolicy _notificationPolicy
 4:    IOrderRepository _orderRepository
 5:
 6:    void Ship()
 7:    {
 8:        if (!CheckIfOkayToShip()) {
 9:            throw new InvalidObjectException();
10:        }
11:        UpdateQuantity();
12:        _orderRepository.Add(this);
13:        _notificationPolicy.Notify(this);
14:    }
15:}
16:
17:class OrderShippedNotifyByEmailPolicy : INotificationPolicy
18:{
19:    // The object that gets injected is implemented
20:    // in the infrastructure layer
21:    IEmailGateway _emailGateway
22:    
23:    void Send(Order this)
24:    {
25:        // Create email here
26:        _emailGateway.Send(email);
27:    }
28:}

2. Or have an application service coordinate:

   1:class OrderService
   2:{
   3:    // _orderRepository and _orderShippedNotificationPolicy 
   4:    //  are injected dependencies
   5:
   6:    void ShipOrder(Order order)
   7:    {
   8:        order.Ship(); // in this case it only validates and updates quantity
   9:        _orderRepository.Save(order);
  10:        _orderShippedNotificationPolicy.Notify(order);
  11:    }
  12:}

There’s been a lot of replies also. I highlighted the interesting ones:

“The advantage of the latter scenario is that you’re calling _orderRepository. Save in the application layer, which I prefer since it’s easier to see the transactional control. The problem with the latter scenario is that it seems it’s putting things in the application layer which don’t need to be there. The action to Ship() seems to me an atomic, domain centered action and should therefore sit in the domain. I consider the application layer to be like a thin domain facade as defined by Fowler. That is, it is only there to direct/coordinate domain activities. Like I said, Ship() seems like it should be considered one activity, and therefore coordination from a service layer shouldn’t be necessary.”

“The way I look at it – what needs to go into Ship() is the stuff that _must_ happen before shipping can happen. And shipping can happen without the notification part. You only have a rule that says “send a notification to the customer upon shipping the order”. You don’t have a rule that says “make sure the customer gets the notification or there are no shipments”.

“So, perhaps as a rough, preliminary rule we can say anything which affects the state of the domain should go be placed in the domain. (Of course, the application layer can affect the state of the domain, but only by using domain items to do so maybe think of it as the Law of Demeter among layers.) The email doesn’t have any meaning within the domain – it’s simply a reflection of the domain.

“Notificitation of an order and the order itself is two separate concepts.”

“This could as easily be implemented using AOP.”

I think DDD advocates are a little bit extremists with some concep
ts, like repository. I wouldn’t have designed it on the domain layer, because I want transactional control on the application service layer. I think the domain has to deal with its particularities, not with sending email or adding things to a repository, even being decoupled of theirs implementations (the domain has a reference only to interfaces). So I prefer the latter approach. And you? What are yout thoughts about this design? How would u have designed it? Everything on the domain or have an application service coordinating the activities?

Tags: , , , ,

Is Java on a evolutionary dead end way?

Artima is running an article where Bruce Eckel talks about about Java’s objective on backwards compatibilities and the problem of combinatorial complexity when you combine a new feature in every possible way with the other language features already present.

It’s the combinatorial complexity that you get when you combine a new feature in every possible way with the other language features. The combinatorial complexity can produce horrifying surprises, typically after the feature is added when it’s too late to do anything about it.

It’s clear Eckel is mentioning the Java closures’ proposals to become part of the language on the Java 7 and the major improvements occured when Java 5 appeared.

If Java is unwilling to break backwards compatibility, then it is inevitable that it will acquire both unproductive complexity and incomplete implementation of new features. I’ve made the case in Thinking in Java 4e that Java Generics are only a pale imitation of real generics, and one of the more appealing suggestions for closures is an incomplete implementation of true closures, but it would actually be preferable to a complete implementation because it produces clearer, more straightforward code.

I particularly agree with him, when he also says

Fundamental new features should be expressed in new languages, carefully designed as part of the ecosystem of a language, rather thanbeing inserted as an afterthought.

He also considers Scala as an alternative for the Java language. Eckel also declares

Java values backward compatibility over the clarity of its abstractions.

I don’t agree with him at this later point, the Collections’ framework is an example of good API design rules with a lot of well designed abstractions by Joshua Block, separating things that change from things that stay the same.

And you? What do u think about it? Should Scala be considered as an exit for Java?

Tags: , , , ,

Strongly Java typed safe delegates

This great post explores an interesting Java implementation about using the delegate programming feature, in a type safe way. Delegate is a form of function pointer, commonly used to implement callbacks. It specifies a method to call, which is dispatched in runtime. From Wikipedia, we have:

The short definition is that delegation defines method dispatching the way it is defined for virtual methods in inheritance: It is always the most specific method which is chosen during method-lookup – Hence it is the original receiver entity which is the start of method lookup even though it has passed on control to some other object(through a delegation link, not an object reference). Delegation has the advantage that it can take place at run-time and affect only a subset of entities of some type and can even be removed at run-time. Inheritance on the other hand typically targets the type rather than the instances and is restricted to compile time.

We almost know weakly typed Java delegate implementations, relying upon Strings to delegate to named methods. This way, it lets you mistype the method name easily and it also does not not allow method completion in the IDE. Alex shows us a type-safe Java delegate implementation, which enhances readibility and supports code completion on the IDE, using the cglib dynamic proxy facility. The article is very worth reading. As a developer on a daily basis I’ve never seen a concrete use of this programming feature, despite being very interesting. Have you ever used the delegate feature?

Tags: , , ,

Swing tips and tricks

Some days go I was given the task to customize the Java Swing widgets for a project in our company. The default look and feel of a JDialog, specifically, has the Java logo trademark icon on the upper corner left, the close button on the right one and the title panel is painted according to the default MetalLookAndFeel probably. As an example, we have something like this:

We wanna have an option to change the title’s panel color, to remove the close button and not to have the Java trademark logo showing on the panel. The final JDialog should look like this:

I’ve thought it was a nearly difficult task, because I had to override a default look and feel and some hidden properties, sometimes difficult to find. Shame on me. Searching through some forums, I’ve found some interesting tips and tricks about how to customize a the entire dialogs of a Swing application, even without creating a look and feel or overriding an old one.

For your knowledge, here are some overridden properties to make the JDialog seems like the latter above. These properties let you define new colors for the active caption of your widgets, other font colors, custom family types and much more (for other properties see through the documentation API or the forums below).

UIManager.put(“activeCaption”, Color.BLUE);
UIManager.put(“activeCaptionText”, Color.WHITE);
UIManager.put(“InternalFrame.titleFont”, new Font(“Arial-12-i-2”, Font.BOLD, 11));
Border cuverdBorder = new LineBorder(new Color(210, 210, 210), 2, true);
dialog.getRootPane().setBorder(cuverdBorder);
dialog.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame.setDefaultLookAndFeelDecorated(true);
dialog.setUndecorated(true);

As a little example, below is the Java code to remove the close button from the panel’s title. This little code snippet below traverses the component hierarchy, passed as a parameter, in a recursive method.

   1:public static void removeCloseButton(Component comp)
   2:{
   3:    if (comp instanceof AbstractButton)
   4:    {
   5:        Action action = ((AbstractButton) comp).getAction();
   6:        String cmd = (action == null) ? "" : action.toString();
   7:        if (cmd.contains("CloseAction"))
   8:        {
   9:            comp.getParent().remove(comp);
  10:        }
  11:    } else if (comp instanceof Container)
  12:    {
  13:        Component[] children = ((Container) comp).getComponents();
  14:        for (int i = 0; i < children.length; ++i)
  15:        {
  16:            removeCloseButton(children[i]);
  17:        }
  18:    }
  19:}

Here are some Sun forums I’ve searched so far to find the possible helps for this solution:

Hope you make use of those tricks in your projects :-).

Tags: , ,

How Hard Could It Be? Five Easy Ways to Fail

Pedro da Ros has pointed me an interesting article from Joel Spolsky about ways software projects go wrong. Five Easy Ways to Fail shows us five step-guide to ensure software failure:

  1. Mistake No. 1: Start with a mediocre team of developers
  2. Mistake No. 2: Set weekly milestones
  3. Mistake No. 3: Negotiate the deadline
  4. Mistake No. 4: Divide tasks equitably
  5. Mistake No. 5: Work till midnight.</li

Have you ever been in any situation like those above?

Tags: ,

Reducing the distance between programming and project management

Some days ago me and [info]bpfurtado were talking about different areas of interest on software development and the distance created by programmers in not involving themselves on another interesting (for me :-)) areas, such as process management, requirement analysis, change control processes, etcetera.
Programmers tend to create a barrier between their tasks and other areas on software development, they prefer to be more specialist. Most of them don’t like to participate on requirement analysis discussions, design sessions, development of test cases. They prefer to code instead of being involved on such activities.
When you work on a software development company, you must have interest at the *big thing*, you need to have the whole vision of your area. People around will put better eyes on you, if you show these interest.
Nowadays at my company I’m participating in activies like use case requirement analysis and programming, because I wanna be involved in the best of both worlds. I wanna increase my analysis and programming skills. It was my decision to participate part time on requirement analysis and the rest on programming activities. I think it’s very important to have this vision and consequently it makes you a better professional. And you? Dou you like to be involved not only in programming tasks?

Tags: , ,