Horror of impl classes

12/12/2014 Leave a comment

If you’ve checked me on Twitter, you may have noticed My Twitter profilemy profile (screenshoot on right) and tag (?) line “Problem solver and father of many impl classes (not to proud about it).

That (not to proud about it) part is the reason why I’m writing this blog post. I’ve received a very long question regarding that part: “Why?”. In follow up discussion I’ve agreed to share why I hate xxxImpl classes so much, even thou I’ve had written so many of ’em in my life.

Impl ==> no idea of what I’m doing

Let’s start first from that Impl suffix implies that we have properly named interface (at least something ;)). Going to basics, what an interface is? By wiki definition

Interface: In object-oriented programming, a protocol or interface is a common means for unrelated objects to communicate with each other.

In my own words, it’s a contract between client and class that’s realizing the interface, it’s also a one foundation of OO which allows us to do a polymorphism and realize encapsulation. We can leave encapsulation and go straight to polymorphism, which is why we do Java, OO and everything else ;)

Interface is just a contract, way in which it’s going to be realized is totally dependant on implementation and there may be more than one (and even should!). Having just one implementation is not necessary wrong, and may have sense, however the biggest fail of ’em all is if that one implementation is called sthImpl. Why? Because it does not tell us anything at all (!) about how contract is being realized. In order to check it, we need to dive into code and figure it out.

We could do so much better! Let’s take for example my project, and something I’ve been doing a week ago (while waiting for plane on lovely Munich airport).

We’re extracting part of system functionality into a set of new projects which will be deployed on many servers. We needed a configuration module, however we could not decide about how we should realize that in distributed environment.

For first implementation I’ve decided to go with property files, tied close to implementation (please don’t judge, has nothing to do with this post). So step one was to create a contract

public interface Configuration {
    public Optional<String> get(String key);
}

and follow it with first implementation

public class LocalPropertyFileConfiguration implements Configuration {

     //Constructor

     public Optional<String> get(String key){/*reading in .properties file*/};

}

We already consider to use ZooKeeper or some other 3rd party service for config, and it will be as simple as adding additional class (ZookeeperConfiguration ?:)) implementing our configuration interface. We may leave first implementation so it can be used in tests or just discard it, does not matter. What matters is that it has proper name.

True, but what comes with proper name is fact that if I ever decide to add more functionality or modify existing one, the name of the class itself will tell me if the change I want to introduce really fits the class. And if I need to expand responsibilities, then it’s super easy to rename the class. Additional bonus: if new name is too cumbersome to say, maybe it’s a good time to split it into couple classes?

So in this example if I’d see anything related to networking inside LocalPropertyFileConfiguration class, then I would start looking what the heck is happening right away, even if I’d see the class for first time. Impl does not give you that benefit.

 

There is also additional code smell coming from the fact we’re missing proper name: no one knows what is exactly the responsibility of the implementation. From vague names often comes God Classes to life. If anyone seen any xxxDaoImpl or xxxManagerImpl then you know what I’m taking about. That is also somewhat related to bad name of interface and not clear enough contract, however Impl classes tend to make things worse.

Also please think about Strategy pattern. It’s really simple to just avoid creating new classes and instead add conditional statements inside one and only Impl. Proper name encourages you to write more classes instead of expanding existing one.

Takeaway

Please always consider what your class is doing, and name it after something specific to the class, even if it’s as stupid as UserJpaDao instead of UserDaoImpl. More importantly, please consider if you need interface at all, if there is going to be just that impl class. Extracting interfaces using IDE is really simple! It’s around 6 keystrokes away at any point of time!

Also don’t sweat too much over names. I’ve come up with names in this post while writing that (c’s I don’t remember what are actual names in code), and IMHO it’s good enough. Remember, improving naming later on is usually super easy :)

So have a nice day and make life better for everyone from Monday with not putting impls in your code.

Categories: English Tags:

Book review: Michał Bartyzel, “Tailored software”

11/05/2014 1 comment

Tailored software

That will be quite unusual post for at least two reasons. That’s my first book review and what may sound dumb, I’m reviewing Polish book, that has not been translated to English yet (original title: Oprogramowanie Szyte na miarę). If you wonder why I write this review in English, the answer is simple: I’ve heard rumors about the translation and I want to add my 2 cents to motivate the author to speed it up a bit :)

Recently I was discussing with Tomasz Dziurko on Twitter why I think that book Clean Code should be read 3 times by every developer on this planet. Tailored Software is quite similar in this matter. It should be obligatory on last year of University and after a year or two in the field, for every IT professional that has to work with the client.

Let’s start with the author of the book. Michal Bartyzel is coaching IT teams in soft skills and is a real expert in this field. You don’t have to trust me on that, if you’ve got a chance, then attend to one of his conference talks. That should not be hard as he’s  speaker on all major conferences in Poland  and as far as I know he’s now speaking in many conferences in Central Europe.

Tailored Software” is a book that explains techniques of gathering requirements from the client, explains how to speak with other people, and shows couple of tricks that may be useful in the meetings. Michał gives a lot of examples and explains them in easy way so that even most hardcore backend developer, that never takes his earphones out, will be able to understand how to behave in given type of situation. And that is in my opinion, the biggest strength of this book: it’s 1 on 1 with soft skills, but written in non boring and simple to absorb way for developers.

For graduates it should give a solid fundamentals that will allow them to avoid a ton of simple mistakes that I made during my first contacts with the client. If you’re already working with the client day by day, this book can offer you a lot too. For me it was a great way to do retrospective on what I already learned on the subject.

Subtitle says: How to talk with the client that does not know what he wants. On the very beginning of the book, Michał explains that client always knows what he wants, however he may not know what he needs. And that is so very true. This book is full of such thoughts that are simple but can be game changing when you are in the meeting and getting angry on everyone else in the room. Remembering one of those quotes in tight situation can be a difference between having a project and punching someone in the face.

Michał did one more great thing in this book. When I was finishing reading this book today, I wanted to do standard notes about everything that is out there in the book. However that was not necessary. Last chapter is such summary with all the useful graphics and diagrams. So you have condensed knowledge ready whenever you need it. I would write exactly same thing, but without all the graphics, and those pictures are very helpful.

Summary

It’s a great book, one of must haves in your library. Please ping Michał to motivate him to translate it into English. Also if you happen to live in tricity, then please do note that Michał donated several copies of his books to our library. We’ve given out most of them already, except for one in JUG library. So you’ve got a chance to read that book and in return me expect just a simple review (which may be in Polish of course). Review may be on your blog, site like goodreads or on the shop site. Please let me know (or any other of JUG leaders) that you want it or any other book that we have in our bookshelf.

 

One thing worth remembering: title translation to Tailored Software is done by me. I don’t know what will be the English title, so please write down author name if you want to wait for the book. I’ll try to remember to update the post when translation is going to be published.

Categories: English Tags: ,

Geb goodness

09/02/2014 Leave a comment

Recently I’ve been playing around with Spock and a bit with Geb. I’m under big impression so today let’s check out what Geb is.

Version for managers -> It’s a technology that will make your developers test and allow you to cut costs. Now go send email to dev team that they should check it out, shoo.

Version for devs -> It’s a sexy framework with jQuery like DSL over Webdriver/Selenium allowing easy use of Page Objects and wiring it all up with Groovy. Those of you that had chance to work with Selenium and write traditional functional web tests in Java, most likely are now wondering what sexy can be in Webdriver.

Well, most importantly, Geb takes away all the boilerplate code and Java ceremony, leaving for you to fill only the important parts with simple syntax, that all of jQuery users know already (most of the examples are taken from Geb site).

$("div.some-class p:first[title='something']")
$("h1", 2, class: "heading")
$("p", text: contains("Geb"))
$("div").find(".b")
$("div").filter(".c").parents()
//Manipulating forms
$("form").name = "Geb"
assert $("form").name == "Geb"

Well, for me it looks like a jQuery. When you get out of syntax and reach test context, it’s even better. Regardless of what testing framework you’re currently using, Geb will work out of the box with it. Personally I’ve been using it with Spock, but it has support for JUnit, TestNG, EasyB and Cucumber. So you don’t have to be concerned about learning another tool.

Let’s check out example below where it’s used with Spock

class LoginSpec extends GebSpec {
    def "login to admin section"() {
        given:
        to LoginPage

        when:
        loginForm.with {
            username = "admin"
            password = "password"
        }

        and:
        loginButton.click()

        then:
        at AdminPage
    }
}

As you can see, it’s just a standard Specification. Only difference is that you use one of Geb spec classes.

Big win in Geb are Page Objects. I haven’t used them in Selenium, however as I understand they are available there. What is a Page Object? As name suggests, it’s an object representation of a page :) To be bit more specific: it’s a class inheriting from geb.Page class which role is to encapsulate all the interaction with the HTML page.

class SignupPage extends Page {
    static url = "http://izawody.pl/signup"
    static at = { title == "Logowanie | iZawody" }
    static content = {
        loginField { $("input#login") }
        passwordField { $("input#password") }
        loginButton(to: DashboardPage) { $("input#loginButton") }
    }

    void login(String login. String password) {
        loginField.value login
		passwordField.value password
        loginButton.click()
    }
}

class DashboardPage extends Page {
    static at = { waitFor { title.endsWith("| iZawody dashboard") } }
}

//Test script
Browser.drive {
    to SignupPage
    login("admin", "admin")
    at DashboardPage
}

It helps as you create a lot of reusable code that encapsulate a lot of moving parts, like text on pages, id’s, HTML structure. So after updating page template you need to only update page object in order to fix dozens of failing unit tests! That’s just a huge win! As a side bonus, all the elements specified in the content section, are reachable in test script, so each element may have an abstraction layer :)

As Geb is just an more readable abstraction layer over Webdriver, as a bonus you get a full support for all the browsers that selenium uses, so you may run your tests in FF, Chrome, Opera, IE and there is experimental support for mobile browsers. If you’re running on a server there is a driver for headless browser, so all covered :)

Only place where Geb falls short is if you aim for job security. Even with code obfuscator you’re going to fail. Code is just damn too simple :(  Other than that Happy coding!

Categories: English Tags: ,

Embedded Mongo and Windows Firewall alerts

29/01/2014 Leave a comment

Long time no see :) I’ll start slowly, so that the pace of writing helps me get back to writing.

Finally I had some time to work on code in the project, and found out most annoying thing ever. We’re using MongoDB in production so for couple of integration tests we use embedded Mongo. It’s a simple tool that we are using the same way as HSQL or H2 DB. DB instance is created by tests that need it and after they are done DB is cleaned up automatically. During that short period when instance is available it may be accessed same way as any normal Mongo instance. We have few tests using it, just to prove that our DB layer is working as expected.  The annoyance I’ve mentioned in the beginning, comes when somebody miss-configure it and try to use under Windows with Firewall turned on. Below example of how to start it without mentioned issue.

CustomMongoDBProperties dbConfig = new CustomMongoDBProperties();         
MongodStarter runtime = MongodStarter.getDefaultInstance();
Net netSettings = new Net("127.0.0.1", Network.getFreeServerPort(), Network.localhostIsIPv6());
_mongodExe = runtime.prepare(
	new MongodConfigBuilder().version(Version.Main.PRODUCTION).net(netSettings).build());
_mongod = _mongodExe.start();

Looks simple? And it is, however if you’re going to remove ip address, being first parameter of net constructor “127.0.0.1”, Windows Firewall will raise alarm every time you run those damned tests. Code compiles, tests are green, just FW pops up a lot!

I hope that it will help you to save some nerves. Of course the proper fix is to install Linux, however this one is good enough workaround for me ;)

A busy week for developers in Tricity

11/12/2013 Leave a comment

Hi all,

long time no see. I’m still struggling what I want to blog about, as this year changed a lot. Most likely I’ll start from those changes, but I need some time for that :E As for now, let me run a short update about what’s happening in Tricity.

First of all, tomorrow we’ve got 50th TricityJUG meeting :D Hell yeah! So if you want to learn something about GWT from someone who worked with it for about 2 years, then you should definitely be on the meeting tomorrow! Check out news on JUG site.

Second thing you should look forward to is a Global Day of Code Retreat in Tricity. This year finally we’ll host it in Gdańsk :D I was waiting for that for years, and it finally happens ! I’m super excited about it. I’ll miss the chance to pair up with people, as I’m on organizing side. Still I’m super fired that TJUG is going to enable a big group of devs an opportunity to take a part in that event :) More good news: we still got some tickets left. Event is free. Food, passionate geeks and code deletion are taken for granted. If you’re in Tricity this Saturday then join us now.

Finally last, but not least. This Saturday there is career expo: careercon.pl If you’re a software professional looking for job opportunities then you should check it out. It’s a great chance to catch up with what’s happening in Tricity. Also there will be 2 conference tracks full of tech stuff, including my talk about what’s new in JDK 8. As time slots are rather short, you can treat that as a prelude to what will  be happening on TJUG starting from Feb till end of the year ;)

And yeah, to give that talk, I’ll have to skip on Code Retreat lunch, which is provided by the Set Restaurant :(

 

Finger crossed for the blog. If all goes well, then this time I’m bringing it up for good (a.k.a. I won’t be so lazy this time)

 

Categories: English

End of the world post mortem

28/12/2012 5 comments

As we all know, on last Friday world was supposed to end.

Luckily your friendly neighbor Java programmer found in the internet a piece of code responsible for running that, left by Evil Mayans, which looked like this:

public class World {

	private WorldDestroyer worldDestroyer;

	public void end(){
		Date endOfTheWorldDate = worldDestroyer.getApocalypseDate();
		if(endOfTheWorldDate.equals(new Date())){
			worldDestroyer.run();
		}//no need for ending bracket as the world ends :D But Java compiler does not know that :( Feathered Snake damn you holy Sun!
	}
}

So what our hero could do?

First of all he could delete the if check or even remove whole World class, however that would most likely fail some tests and would result in alarm raised by Evil Mayan CI server. They would know that something is wrong,  fix the code, hence the world would end!

So he had to be smarter. Our hero sat and thought for some time, but not for so long, remember The End Of The World is coming! Using all his Java knowledge and team work experience he did the change!

public void end(){
		Date endOfTheWorldDate = worldDestroyer.getApocalypseDate();
		endOfTheWorldDate.setYear(20);
		if(endOfTheWorldDate.equals(new Date())){
			worldDestroyer.run();
		}
	}

So what he did? He used one of biggest flaws of java.util.Date MutabilityYes, you may change internal state of Date using one of it’s method. No need for some sophisticated techniques.

I’m doing all of Java interviews in DC, and it astonishes me how many people don’t know that this class is Mutable. Yes, after instantiating it, you may change it internal value freely, which may lead to a lot of problems.

It surprises me how many people does not know about it. During last interview, right before Christmas, Senior Java Dev (with >5yrs of experience) tried to convince me that the class is immutable and that may be one of it flaws.

And what’s the big deal?

You should never trust in Date object, you’ve shared or received from external World (in OO terms -> outside your class).

It is possible to build anything on top of java.util.Date. In most cases, no one will try to harm you, but I would not build large application / framework on top of that assumption. So while working with Date, you’re going to learn everything about defense programming. Quick enough you’ll understand that it’s not enough to just copy input parameters, but you also have to return defense copies while returning values.

But okay, let’s stop bashing Date class for a moment. If you want to learn more about techniques that may be useful to work with it, please check the book that EVERY Java programmer should read: Effective Java by Joshua Bloch. It may not have anything about Date class, but it for sure shows how to achieve immutability and how to work with mutable code.

Other good solution is to use 3rd party library, like e.g. JodaTime It will solve a lot of your problems. It’s also quite popular, so most of the frameworks will provide support for it’s classes.

Ok, let’s investigate second flaw of this code. It’s not testable.

You just can’t test code that is dependent on time. It has to fail from time to time, raising false alarm. If you assert based on year, it may fail at midnight every 5-8 years. If you assert on month, it may fail before payday, etc. But don’t worry, the battle is not lost yet. The solution is trivial: create an external class called Clock / TimeService / TimeManager / DateFactory or something along the line, consistent with you’r project naming convention, and just move instantiation of Date there. What we achieve this way? You can switch implementation of that class for test purpose and you won’t get broken CI builds from time to time :)

So how it should look like in the end? (at least this variant of code)

public class World {

	private WorldDestroyer worldDestroyer;
	private Clock clock;

	public void end(){
		Date endOfTheWorldDate = worldDestroyer.getApocalypseDate();
		if(endOfTheWorldDate.equals(clock.now())){
			worldDestroyer.run();
		}
	}
}
Now much better. Good that evil Mayans did not know about it :)
Categories: English Tags: , , ,

Working with java util Date

28/12/2012 Leave a comment

as promised, I’m blogging again :)

http://rits.pl/2012/12/28/end-of-the-world-post-mortem/

Some basic knowledge about one of fundamental classes of Java.

Categories: English
Follow

Get every new post delivered to your Inbox.