Featured FREE Whitepapers

What's New Here?


Android: Gallery View without Pictures

Android’s Gallery View is one of the first widgets Android created. It’s so old now that some people even find it hard to find. The Gallery view provides a list of scrollable objects much like the standard ListView. The one main benefit of using the Gallery View is its snap-to-position feature. When the user stops scrolling, the images that end up being displayed are also snapped to the center of the screen. This means the user won’t be looking at half of two separate images at one time, and as a developer, you are also aware of exactly what the user is centered on. Also, the Gallery view works very well in a horizontal mode, instead of a vertical mode like the standard ListView. The nice thing about the Gallery View is that it can be used with any type of View you can think of, not just images. By creating a custom layout with whatever you would like to display in the Gallery View, you’re able to come up with some pretty interesting displays. Making a custom view and adding it to a gallery view is pretty simple. Here is a quick example that displayed a horizontal gallery view with a CheckBox to the left, a TextView in the center, and an ImageView on the right. To start off, we simply create a new Android project (the API level doesn’t matter, this should work in any version). In main.xml (which is the default layout file of the project), we add the Gallery and remove the default TextView like so: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Gallery android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content"></Gallery> </LinearLayout>Now that we have the Gallery widget in our project, lets go ahead and create the gallery item layout. This layout represents exactly how each item in the gallery view will look. Like I said above, we want a CheckBox locked on the left, a TextView in the center, and a ImageView locked on the right. Also, some padding on the right and left sides would be nice to ensure we can see everything fine. To get that desired look, a RelativeLayout is used: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/gallery_item"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:text="TextView" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="14dp"></TextView> <ImageView android:layout_width="wrap_content" android:id="@+id/imageView" android:src="@drawable/icon" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_marginRight="22dp"></ImageView> <CheckBox android:id="@+id/checkBox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_marginLeft="24dp"></CheckBox> </RelativeLayout>Now that all the layouts are ready to go, all we need to do is set up our Gallery Adapter. This is where the Gallery view is a bit different from the standard ListView. In order to get a custom layout, the BaseAdapter needs to be extended to provide a custom view. So we’ll call the new Custom adapter newGalleryAdapter. We’ll simply put the adapter at the bottom of our Activity. Here’s what our Activity looks like now: public class GalleryExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Find our gallery view and set the adapter for it Gallery gallery = (Gallery) findViewById(R.id.gallery); gallery.setAdapter(new newGalleryAdapter(this)); }// The new custom Gallery Adapter for our new layoutprivate class newGalleryAdapter extends BaseAdapter { private Context context; // needed to create the viewpublic newGalleryAdapter(Context c) { Context = c; }// set to three for this example // for normal use this should be set to the length of the data // structure that contains the items to be displayed public int getCount() { return 3;}public Object getItem(int position) { return position; }public long getItemId(int position) { return position; }public View getView(int position, View convertView, ViewGroup parent) { View v;// just a simple optimiztaion - // we only inflate a new layout if we don't have one to reuseif (convertView == null) v = LayoutInflater.from(context).inflate(R.layout.gallery_item, parent, false); else v = convertView; // Now that we have our new custom View, find out widgets in the // view and set them TextView tv = (TextView) v.findViewById(R.id.textView);tv.setText(String.valueOf(position)); CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox); // this just alternates what the checkbox states are if (position % 2 == 0) cb.setChecked(true); else cb.setChecked(false); return v;}}}In onCreate, we just find our Gallery View and set its Adapter to our new Adapter. On line 14 and down, we design our new adapter. The most important method in the adapter class is the getView method (line 37). In this method, our new custom layout(gallery_item.xml) is inflated. We then find the widgets and set them to whatever we would like. Once we’re done setting up the View, simply return it. With everything said and done, We get this:Reference: Android Tutorial: Gallery View without Pictures from our JCG partner Isaac Taylor at the Programming Mobile blog. Related Articles :Android Game Development Tutorials Android Dependency Injection and Testing Libraries “Android Full Application Tutorial” series What every Programmer should know about the memory system Android HTTP Camera Live Preview Tutorial...

The Truly Educated Never Graduate

Science can be very complex in theory and people failing to think in these abstract terms probably get cold feet prematurely in their choice of education. Other people have a hard time to apply theory in practice even though they are all very smart people! Indeed, having a university degree is far from an insurance of being intelligent. Alan Kay, the father of object-oriented programming, shares some very interesting ideas around teaching and understanding. James Bach also touches on the subject in Secrets of a Buccaneer-Scholar. Noam Chomsky and Sir Ken Robinson further acknowledge the failure of modern education in a very deep and interesting analysis. I think this is very unfortunate, because it means that we (the people) are somewhat mislead in a system that does not encourage individuals to pursue our their inner passion. But I have a somewhat optimistic view that it is never too late to pursue your goals, even though you have been mislead in the past, for whatever reasons… Some time ago I read a very encouraging article explaining that intelligence is never constant, it is work in progress. A mountain of evidence suggests that intelligence really is a skill. That is, the harder you work, the more you learn. So, when you encounter something difficult, it is better to treat that as a challenge than as a sign that you have reached your mental limits. It is also better to believe that studying hard will lead to good learning than to believe that studying hard leads to poor learning. By putting in extra effort on difficult concepts, you come away with more knowledge.  Ultimately, this aspect of learning feeds on itself. The more you learn at any given time, the easier it is to learn new things in the future. The effort you put in to learn is rewarded by making it easier for you to learn more things in the future. And it works the other way as well, use your brain or loose it. I sometimes get the question why I do programming and read about it on my spare time. The explanation is that if you have passion and love for what you do, motivation comes naturally because you are acting along the lines of your most authentic self. It is not about “enduring” your job in the traditional sense, it is who you are. This stimulates enthusiasm and creativity in a very powerful way. Focus on your strengths, as Richard Branson points out. I cannot stress enough on the importance of having a responsible attitude towards self-education – learning without someone telling you. Taking the opportunity to learn something new and continuously sharpen your skills, every year. And so I have a few tips for software developers to get into this state of mind. You may of course feel that these advices feel boring and annoying to apply in practice. But if that’s how you feel.. I would advice you to think twice about if software development is for you (if you havent read the links i posted earlier, do so and you’ll see what i mean). So here goes.. Practice continuous self-assessment of your previous work, maybe by looking at old code and try to think out-of-the-box on how it can be improved. Fork and read code from popular Open Source projects and try to change them. Or even better, join a Open Source project that interest you. This can also be a way to extend your social network with bright, caring and driven individuals that also probably will inspire you in positive ways. Improve your ability to perceive many different perspectives by learning something entirely different. Try to take two different ideas and combine them in different contexts to create something new, the basic principle of innovation. I have elevated my way of thinking of design a lot from reading philosophy for example, in particular Ontology (study of reality) and Epistemology (study of knowledge). Or why not learn business strategy and planing, management techniques, or economics? Aristotle’s philosophy covered physics, metaphysics, poetry, theater, music, logic, rhetoric, linguistics, politics, government, ethics, biology etc.. that’s an impressively broad set of subjects! Read books, at least one every year, and try to find timeless books written by people who are famous for their brilliance. If you find out what these people read – add those books to your reading list. Isaac Newton said, “if I have seen further it is by standing on the shoulders of giants”. Eventually you will learn to discover the same fundamental red threads buried underneath different domains, perspectives, shapes and forms. I just started a blog and i regret not doing it earlier. It makes you really reflect and organize your thoughts and pushes you to find and think about new or interesting things to learn. Try to be humble and a good listener – which can be hard in the face of arrogant and ignorant people – the greatest enemy of learning is knowing! Never, ever ever ever, be afraid to ask questions! Socrates used questions to stimulate critical thinking and illustrate ideas, he said, “and in knowing, that you know nothing, makes you the smartest of all”. Richard Feynman summarize this mindset in a beautiful way. The more I learn, the more convinced I get that software development truly is about knowledge acquisition and ignorance reduction. I wish you Good Luck on the lifelong road of learning! For every step you take toward mastery, your destination moves two steps further away. Embrace mastery as a lifelong endeavor. Learn to love the journey.  -George Leonard Reference: The Truly Educated Never Graduate from our JCG partner Kristoffer Sjögren at the Deep Hacks blog. Related Articles :Selling Yourself: Why? and How! Not doing Code Reviews? What’s your excuse? Roles in the IT World Funny Source Code Comments Things Every Programmer Should Know...

Quick tips for improving Java apps performance

Ever had performance problems? Yeah me too. If my manager screams “faaaaster” one more time, i will have hearing impairment for the rest of my life. BTW, did i sense a German pronunciation in all that noise? ;-) Can you believe that there are still people doing ignorant trash talk about the garbage collector (get it?) and performance of the JVM. … i will go back writing C again so i don’t have to worry about performance… *sigh* The JVM is continuously improving its collector algorithms and highly sophisticated optimizations are incorporated into the compiler with every release (and have been doing so for the last 10 years). Do *you* really expect to have the experience, ability and time to write better and more optimized C code than some of the smartest people on this earth? Pleeeeease… If you are like me and 99.99 percent rest of us, you be wise to forget about C. Just get over it. (salute to all hardcore C programmers, do not feel provoked). As much as us developers love abstractions, we cannot deny the fact that they are inherently leaky. Hardware *does* matter. The trend of processor count and memory growth make shared memory thread concurrency a lot harder. Locking, context switching and thread scheduling can make your throughput equal to syrup, thinking that pouring more threads into your shiny new super-beefy-machine will somehow magically will give you more performance. It probably will to some degree, but that’s not my point. So what to do? I do not claim to be a performance expert, i am not, but i have some practical advice that at least helped me squash some nasty performance bugs in the past. 1. Write clean and “dumb” code. Consider making your classes immutable, they are thread-safe hence no need for synchronization and can be cached with confidence that object values do not change after being created. Immutability also leads to code that is easier to understand. Do not try to outsmart the JVM with premature optimization tricks. Donald Knuth said: “Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.“ 2. Spend some time on understanding the how different garbage collectors works. The information is a bit scattered, but its out there. Find the resource sharing sweet-spot between garbage collection and your application. Generally speaking larger heaps means garbage collector needs to work harder (stealing more CPU cycles) and pauses will be longer, but less frequent. In my experience you cannot avoid stop-the-world pauses from happening, even using CMS, because eventually your heap will be fragmented as Swiss cheese, and boom, memory fragmentation failure. The good news is that JDK7 will probably include a new low-pause collector, called G1, which can potentially fully avoid stop-the-world pauses. Also see Garbage-First Collector(G1) in Java 7. 3. Always use java.util.concurrency by default when programming. Read the Java Memory Model and Thread Specification. It will help you understand why your code may not performing as it should. There are very good books on the subject of concurrency as well:Java Concurrency in Practice The Art of Multiprocessor Programming Concurrent Programming in Java: Design Principles and Pattern (2nd Edition)4. Chances are that you are dealing with legacy code (you cannot influence) that have coarse grained synchronization, causing high thread contention. Using CPU affinity with multiple JVM processes on the same machine can help reduce contention for hot locks. 5. If you think you found JVM performance problems by doing benchmarks, first, make sure you know that you *know* your measurements are accurate. If you try measure something, don’t measure other stuff. Ignoring this advice may mislead you from where the real problems lurk. So make sure to properly isolate system parts before you start measuring. For example, if you suspect thread contention, have a look at ThreadInfo or try jstat and look for sun.rt._sync_ContendedLockAttempts. jstat -J-Djstat.showUnsupported=true -snap PID | grep _sync_There are so much to say on this subject, but i don’t have time to write more right now. Happy coding! Reference: Look ma, Usain Bolt from our JCG partner Kristoffer Sjögren at the Deep Hacks blog. Related Articles :Java Best Practices How to get C like performance in Java What every Programmer should know about the memory system Java Memory Model – Quick overview and things to notice...

Rules in JUnit 4.9 (beta 3)

Some time ago David Saff announced a beta release of JUnit 4.9. So I guess it is a good point in time to look into what is new in this version. One of the most useful innovations in the JUnit realm have been Rules. I wrote about Rules here. And I wrote about use cases for JUnit Rules here. Rules are great. And with JUnit 4.9 they get even better. You can think of Rules as a way to encapsulate setup and teardown of a test in one class instead of two methods. But Rules are also a way to modify the way to execute your tests. You can run tests a dozen time instead of once. Or in twenty different threads. Interestingly there were only Rules for single tests. So if you want to stick with the comparison with setup and teardown, aka @Before and @After there wasn’t a @BeforeClass and @AfterClass equivalent in Rules. Now that has changed. You can now annotate a public static field of type TestRule with the @ClassRule and it will behave just like a Rule that is defined for a whole test class instead of a single test. So it is perfect for the stuff that needs setup once for all the tests instead of for each tests. Lets look at an example. The implementation of a Rule might look like this: import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class LoggingRule implements TestRule { public class LoggingStatement extends Statement { private final Statement statement; public LoggingStatement(Statement aStatement, String aName) { statement = aStatement; } @Override public void evaluate() throws Throwable { System.out.println("before: " + name); statement.evaluate(); System.out.println("after: " + name); } } private final String name; public LoggingRule(String aName) { name = aName; } @Override public Statement apply(Statement statement, Description description) { System.out.println("apply: " + name); return new LoggingStatement(statement, name); } }Most implementations will consist of two parts: An implementation of the TestRule interface and an implementation of the Statement interface. TestRule replaces the now deprecated MethodRule interface which was used before. This is because the new interface supports both Rules on class level and on method level, so it had to change a little. TestRule has a single method apply which takes a Statement and returns a Statement. This method gets called before any test in the scope of the Rule gets executed. The Statement passed in actually are the tests that might get executed. Two things to note here: The Statement might and will represent multiple tests, if your Rule gets used with a @ClassRule annotation; And the call to apply doesn’t mean the Statement will actually get executed. Since whatever your Rule returns might get passed to other Rules, the Statements might got mangled in various ways before the contained tests get actually executed. The typical thing todo in the apply method is to wrap the Statement in a new Statement which will perform what ever logic is needed for your purpose. The Statement interface has a single method evaluate which should execute a test or a bunch of tests in the normal case. So if you go with the typical approach mentioned above you do some setup call evaluate of the contained Statement and do some tear down. In the example provided above I print stuff on the console so one can see in which order stuff gets called. The Statement also gets passed a Description which contains useful meta information about the test(s). It contains the name, the class in which the test is defined, the method name and makes annotations available. So your Rule/Statement can fine tune its behavior based on the test method on which it operates. A test class using this Rule might look like this: import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; public class RuleTest { @ClassRule public static LoggingRule classRule = new LoggingRule("classrule"); @Rule public static LoggingRule rule = new LoggingRule("rule"); @Test public void testSomething() { System.out.println("In TestSomething"); assertTrue(true); } @Test public void testSomethingElse() { System.out.println("In TestSomethingElse"); assertTrue(true); } }The only change to JUnit4.8 Rules is the presence of the @ClassRule annotation. Note that the same class is used with @ClassRule and @Rule annotation. When executed the output of the test class looks like this: apply: classrule before: classrule apply: rule before: rule In TestSomething after: rule apply: rule before: rule In TestSomethingElse after: rule after: classruleAs you can see first the class level Rule gets applied and the resulting Statement evaluated. Only as part of the evaluation does the method level Rule applied and the resulting Statement evaluated, once for each test. One word of caution: Be careful to use the correct modifiers with your Rules. They must be public and class level Rules must be static. Depending on what you do wrong (and in what environment you are working in) the resulting errors might not be exactly helpful. This is considered a bug and fixes are in the making. Reference: Rules in JUnit 4.9 (beta 3) from our JCG partner Jens Schauder at the Schauderhaft blog. Related Articles :Java Tools: Source Code Optimization and Analysis Are frameworks making developers dumb? Things Every Programmer Should Know Design Patterns in the JDK Java Best Practices...

The Ten Minute Build

Given a development environment any developer should be able to get hold of the source code, click a button or type a simple command and run a build. The build should compile and perform its unit tests within about ten minutes. This is the Ten Minute Build rule in James Shore’s and Shane Warden’s book The Art of Agile Development and it’s easy to see why this is a good idea because builds that don’t run easily are both frustrating, which lowers moral, and burn project time shoveling your company’s money into some metaphorical furnace. If you build takes more than about 10 minutes there are a couple of things you should look at. The things to consider are tooling and infrastructure, which in plain English really means: do you have a dedicated build machine and are you using the right tool set? Getting a dedicated build machine shouldn’t be too hard as there is a cost benefit here: a developer’s time verses the cost of a virtual or real box, whilst many of the tools you’ll need are open source: Maven, CruiseControl / Hudson, GIT/Subversion etc. If you already have a dedicated build machine and are using all the right tools then the next thing to look at are your unit tests. Builds that include lots of “end to end” or integration tests are usually the culprit. End to end tests are useful in that they prove your classes will work together, but your main testing thrust should be your class’s full set of isolated unit tests covering all necessary cases and edge conditions. This is because end to end test usually involve setting up and tearing down some external service such as a database. Some say, that you don’t really need any end to end tests, but I think that you do as you need to prove that your classes will work together. So how many integration tests should you use? I like to aim for about one or two per scenario, but only if I’ve got a large number (say 10-20) unit tests per class to give me confidence that everything will work. Some time ago, I mentioned the FIRST Acronym (taken from Bob Martin’s Clean Code) where tests should be FAST, INDEPENDENT, REPEATABLE, SELF-VALIDATING and TIMELY, which is a very good starting point when reviewing unit test performance. Being pragmatic, there will be those applications that will never build within 10 minutes. In this case consider splitting your program up in to smaller modules as recommended by the Maven builds manual. Ask your self whether or not you’re building database access classes into the same JAR file as your business logic or presentation code and if so, split them up. You could take this one step further, and create a distributed parallel build environment, but be careful here you may unintentionally break Agile’s ‘keep it simple’ rule.   Reference: The Ten Minute Build from our JCG partner Roger Hughes at the Captain Debug blog. Related Articles :Not doing Code Reviews? What’s your excuse? Using FindBugs to produce substantially less buggy code Developing and Testing in the Cloud Java Tools: Source Code Optimization and Analysis Why Automated Tests Boost Your Development Speed ...

Java Tutorials and Android Tutorials Page launch at Java Code Geeks

Hello all, As you are aware, Java Code Geeks have been running for about one and a half year now. Since our beginning we have managed to publish an enormous amount of articles, written both by our editors and our JCG partners (thank u guys!). A few days ago Byron and I decided to organize this vast sea of posts. Our main purpose was to filter the published tutorials and categorize them, so that a Java Code Geeks reader can easily find a tutorial on a specific subject. The end result was a dedicated page that we are really proud of. It currently contains 130+ tutorials spanning across Core Java, Enterprise Java, Desktop Java, Scala and Android. We will update the page with new entries of course, thus the number is expected to greatly rise. So, without further ado, I proudly present you: Java Tutorials and Android Tutorials There, you can find a wealth of resources to help you with your programming endeavours. We believe that it will be a great aid to the community and we are really glad to have helped be created. We would be delighted if you helped spreading the word and allowing more and more developers to come in contact with our content. Don’t forget to share! Happy coding everyone! Cheers, Ilias Tsagklis ...


DTOs, or data-transfer objects, are commonly used. What is not s? commonly-known is that they originate from DDD (Domain-driven design). There it makes a lot of sense – domain objects have state, identity and business logic while DTOs have only state. But many projects today are using the anemic data model approach (my opinion) and still use DTOs. They are used whenever an object “leaves” the service layer or “leaves” the system (through web services, rmi, etc.). There are three approaches:every entity has at least one corresponding DTO. Usually more than one, for different scenarios in the view layer. When you display a user in a list you have one DTO, when you display it in a “user details” window you need a more extended DTO. I am not in favour of this approach because in too many cases the DTO and the domain structure have exactly the same structure and as a result there’s a lot of duplicated code + redundant mapping. Another thing is the variability of multiple DTOs. Even if they differ from the entity, they differ from one another with one or two fields. Why duplication is a bad thing? Because changes are to be made in two places, issues are traced harder when data passes through multiple objects, and because..it is duplication. Copy & paste within the same project is a sin. DTOs are only created when their structure significantly differs from the that of the entity. In all other cases the entity itself is used. The cases when you don’t want to show some fields (especially when exposing via web services to 3rd parties) exist, but are not that common. This can sometimes be handled via the serialization mechanism – mark them as @JsonIgnore or @XmlTransient for example – but in other cases the structures are just different. In these cases a DTO is due. For example you have a User and UserDetails, where UserDetails holds the details + the relations of the currently logged user to the given user. The latter has nothing to do with the entity, so you create a DTO. However in the case of a DirectMessage you have sender, recipient, text and datetime both in the DB and in the UI. No need to have a DTO. One caveat with this approach (as well as with the next one). Anemic entities usually come with an ORM (JPA in the case of Java). Whenever they exit the service layer they may be invalid, because of lazy collections that require an open session. You have two options here:use OpenSessionInView / OpenEntityManagerInView – thus your session stays open until you are finished preparing the response. This is easy to configure but is not my preferred option – it violates layer boundaries in a subtle way, and this sometimes leads to problems especially for novice developers Don’t use lazy collections. Lazy collections are unneeded. Either make them eager, if they are supposed to hold a small list of items (for example – the list of roles for a user), or if the data is likely to grow use queries. Yes, you are not going to show 1000 records at on go anyway, you will have to page it. Without lazy associations (@*ToOne are eager by default) you won’t have invalid objects when the session is closedDon’t use DTOs at all. Applicable a soon as there aren’t significantly varying structures. For smaller projects this is usually a good way to go. Everything mentioned in the above point applies here.So my preferred approach is the “middle way”. But it requires a lot of consideration in each case, which may not be applicable for bigger and/or less experienced teams. So one of the two “extremes” should be picked. Since the “no DTOs” approach also requires consideration – what to make @Transient, how does lazy collections affect the flow, etc, the “All DTOs” is usually chosen. But even though it is seemingly the safest approach, it has many pitfalls. First, how do you map from DTOs to entities and vice-versa? Three options:dedicated mapper classes constructors – the DTO constructor takes the entity and fills itself, and vice-versa (remember to also provide a default constructor) declarative mapping (e.g. Dozer). This is practically the same as the first option – it externalizes the mapping. It can even be used together with a dedicated mapper class map them in-line (whenever needed). This can generate unmaintainable code and is not preferredI prefer the constructor approach, at least because fewer classes are created. But they are essentially the same (DTOs are not famous for encapsulation, so all of your properties are exposed anyway). Here is a list of guidelines when using DTOs and either of the “mapping” approaches:Don’t generate too much redundant code. If two scenarios require slightly different DTOs, reuse. No need to create a new DTO for a difference of one or two fields Don’t put presentation logic in mappers/constructors. For example if (entity.isActive()) dto.setStatus(“Active”); This should happen in the view layer Don’t sneak entities together with DTOs. DTOs should not have members which are entities. Generally, entities should not be used outside the service layer (this is a bit extreme, but if we use DTOs everywhere we should be consistent and stick to that practice) Don’t use the mappers/entity-to-dto constructors in controllers, use them in the service layer. The reason DTOs are used in the first place is that entities may be ORM-bound, and they may not valid outside a session (i.e. outside the service layer). If using mappers, prefer static mapper methods. Mappers don’t have state, so no need for them to be instantiated. (And they don’t have to be mocked, wrapped, etc). If using mappers, there’s no need for a separate mapper for each entity(+its multiple DTOs). Related entities can be grouped in one mapper. For example Company, CompanyProfile, CompanySubsidiary can use the same mapper classJust make sure you make all these decisions at the beginning of a project and figure out which is applicable in your scenario (team size and experience, project size, domain complexity). Reference: On DTOs from our JCG partner Bozho at the Bozho’s tech blog. Related Articles :Domain Driven Design with Spring and AspectJ Using the State pattern in a Domain Driven Design Problems with ORMs What is Dependency Inversion? Is it IoC? Are frameworks making developers dumb? Things Every Programmer Should Know Design Patterns in the JDK Java Best Practices...

Best Of The Week – 2011 – W36

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * JSR-107, JCache: Alive and Going to be Part of Java EE 7: It seems that JCache will make it to Java EE 7 providing a standard caching mechanism for Java apps. This article discusses the benefits of using a caching mechanism, the major changes and advancements that have been made in the progress of JCache and the specification’s roadmap. * How server-side performance affects mobile user experience: A short article providing an example of how to perform basic analysis of a mobile web site’s performance using the desktop and not the mobile. This way performance issues caused by slow server-side response times or non-optimized resource delivery can be found easily. * Getting Started with JUnit on Android: As the title suggests, an article that will get you started with Unit testing on Android. Also check out our Android Tutorials and our Android Game Tutorials.  * Do You Really Get Memory?: A presentation where Jevgeni Kabanov creates a CPU model in Java in an attempt to explain the underlying mechanism of memory performance bottlenecks and the need for a correlated hardware, OS and JVM improvement. . * How about distributed queues?: In this article, the GridGain approach to distributed queues is presented along with a simple showcase example. The idea is to enable developers to take well known data structures and distribute them over the grid.. * How to use Type safe dependency injection in Spring 3?: A short guide on how to achieve type safe dependency injection with Spring 3. Also check out The evolution of Spring dependency injection techniques and Spring configuration with zero XML. * Functional thinking: Coupling and composition, Part 1: In this article the author discusses functional programming and shows how to refactor Java code in order to use a more functional approach via composition. * Java Threads on Steroids: A Java Concurrency related article introducing the Disruptor framework and its underlying philosophy. The author argues that we can reduce the performance impact of context switching by forcing a thread or a process to run only on a specified set of CPUs, i.e. by leveraging processor affinity. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W35 Best Of The Week – 2011 – W34 Best Of The Week – 2011 – W32 Best Of The Week – 2011 – W31 Best Of The Week – 2011 – W30 Best Of The Week – 2011 – W29 Best Of The Week – 2011 – W28 Best Of The Week – 2011 – W27 Best Of The Week – 2011 – W26 Best Of The Week – 2011 – W25...

On domain-driven design, anemic domain models, code generation, dependency injection and more…

Eric Evans has formulated what domain-driven design (DDD) is. Martin Fowler is a great supporter and advocate of DDD. These are remarkable names and it is almost certain they are supporting something worth. And I’m not here to argue with that. Maybe I’m trying to justify the way I’ve been writing software, or maybe I’m trying just to clear things and be constructive. Let’s see. What is at the core of domain-driven design – the abstract notions of the domain, the domain model, the ubiquitous language. I’ll not go into details with that – for those interested there is wikipedia (with lots of references to read in the footer). This is all very good in theory, and the domain-driven way of building software should appeal to everyone – after all that software is being built for the benefit of that domain, not for the benefit of architects, developers or QAs. But now comes the practical part – how to implement DDD? I’ll answer that question in its contemporary context – that is, using frameworks like spring and hibernate. And I’ll justify their usage. Spring is a non-invasive dependency-injection framework. DI is also strongly supported by Fowler, and is considered a good way to implement DDD. Hibernate is one way to use objects when working with a relational database. Another way is to use JDBC and construct the objects manually, but that is tedious. So hibernate doesn’t influence the architecture part – it is an utility (very powerful one, of course). Throughout this post I’ll use hibernate and spring as “given”, although they may be changed with any DI framework and any ORM or other persistence mechanism that relies on objects. The accepted way to implement DDD with spring and hibernate is:use @Configurable to make the domain objects eligible for dependency injection (they are not instantiated by spring, so they need this special approach) inject repository objects in the domain objects in order to allow the domain objects to do persistence-related operations use a thin, stateless, transactional service layer (a facade) to coordinate the domain objectsImplementation and description of this approach is shown in this extensive article. Another example (without spring) is http://dddsample.sourceforge.net/. I’ll discuss both later. The alternative to this approach is the anemic domain model. It is considered an anti-pattern, but at the same time is very common and often used. The features of the anemic data model are simple – the domain objects have no business logic inside them – they are only data holders. Instead, the business logic is placed in services. The reason this is considered an anti-pattern is because, first, this seems like a procedural approach. It is breaking the encapsulation, because the internal state of the object is, well, not internal at all. Second, as the domain object is the center of the design, it is harder to change it if its operations don’t belong to it, but to a number of stateless service classes instead. And domain-driven design is aimed at medium-to-large scale applications, which change a lot and need an easy way to make changes fast, without breaking other functionality. Thus it is important to have all the functionality of the object within the object itself. This also makes sure that there is less duplication of code. So, instead of having a service calculate the price: ProductServiceImpl.calculatePrice(complexProduct) we should simply have ComplexProduct.calculatePrice(). And so whenever the domain experts say that the price calculation mechanism changes, the place to change it is exactly one and is the most straightforward one. When simple operations are regarded, this looks easy. However, when one domain objects needs another domain object to do its job, it becomes more complicated. With the anemic data model this is achieved by simply injecting another Service into the current one and calling its methods. With the proposed DDD it is achieved by passing domain objects as arguments. In my view, the domain object, which is also the hibernate entity, has its dependencies already set. But not by spring, because spring can’t know which exactly domain object to inject. They are “injected” by hibernate, because it knows exactly which (identified by primary key) domain object should be placed in another domain object. So, a little odd example – if a Product has rotten and has to dispense smell in the warehouse, it has to call, for example, warehouse.increaseSmellLevel(getSmellCoeficient()). And it has its precise Warehouse without any interference from spring. Now, here comes another point where I disagree. Most sources (including the two linked above) state that repositories / DAOs should be injected in the domain objects. No, they shouldn’t. Simply calling “save” or “update” doesn’t require knowledge of the internal state of the object. Hibernate knows everything anyway. So we are just passing the whole object to the repository. Let’s split this in two – business logic and infrastructure logic. The domain object should not know anything of the infrastructure. That might mean that it should not know it is being saved somewhere. Does a product care of how it is stored ? No – it’s the storage mechanism that’s “interested”. And here are the practical disadvantages:CRUD is implemented by simply wrapping repository calls in all domain objects – duplication of code the domain object is transitively dependent on persistence – i.e. it is not a pure domain object, and if repositories change, it has to be changed as well. And in theory it should be changed only when the domain rules and attributes change people will be tempted to include transaction, caching and other logic inside the domain objectI’ll open a bracket here about a proposed solution in one of the above articles for making duplication of code, and boilerplate code easier to handle. Code generation is suggested. And I think code-generation is a sin. It moves the inability to get rid of duplicated or very similar code and abstract it, to tools. The most striking example is generating ProductDAO, CategoryDAO, WarehouseDAO, etc, etc. Generated code is hard to manage, cannot be extended and relies heavily on external metadata, which is definitely not an object-oriented approach. Speaking of the repository, in the proposed examples each domain object should have a repository, which in turn will call the persistence mechanism. What do we get then: User presses “save” in the UI > UI calls save on the service (in order to have transaction support) > Service calls save on the domain object > domain object calls save on the repository > the repository calls save on the persistence mechanism > the persistence mechanism saves the object. Is it just me, or calling the domain object is redundant here. It is a pass-through method that adds nothing. And since a lot of functionality is related to CRUD (yes, even in big business applications), this looks quite bad to me. And finally, I find the @Configurable approach a hack. It does some magic in the background, which isn’t anything of the common language features (and is not a design pattern), and in order to understand how it happens you need a great deal of experience. So, to summarize the big mess abovedomain objects should not be spring (IoC) managed, they should not have DAOs or anything related to infrastructure injected in them domain objects have the domain objects they depend on set by hibernate (or the persistence mechanism) domain objects perform the business logic, as the core idea of DDD is, but this does not include database queries or CRUD – only operations on the internal state of the object there is rarely need of DTOs – the domain objects are the DTOs themselves in most cases (which saves some boilerplate code) services perform CRUD operations, send emails, coordinate the domain objects, generate reports based on multiple domain objects, execute queries, etc. the service (application) layer isn’t that thin, but doesn’t include business rules that are intrinsic to the domain objects code generation should be avoided. Abstraction, design patterns and DI should be used to overcome the need of code generation, and ultimately – to get rid of code duplication.Reference: On domain-driven design, anemic domain models, code generation, dependency injection and more… from our JCG partner Bozho at the Bozho’s tech blog. Related Articles :Domain Driven Design with Spring and AspectJ Using the State pattern in a Domain Driven Design Problems with ORMs What is Dependency Inversion? Is it IoC? Are frameworks making developers dumb? Things Every Programmer Should Know Design Patterns in the JDK Java Best Practices...

How to solve production problems

At my job, I’m finding that a large percentage of the questions that come to my desk are “Hey this thing you did is broken” or “Hey, this thing you worked with is on the fritz.” 99% of the time, I’d have no idea why the behavior they were asking about was occurring! However, I think I’ve got a great problem solving methodology, which I attribute to being key in my success. Maybe some agile writer can take the concepts here and we can develop a formal methodology for solving problems. Preventative Measures As professionals, we should accept that production problems are unavoidable. You will create defects in your code, and no amount of testing will ever weed them all out. Code is rushed, servers crash, disks fail, and datacenters overheat. Accepting the fact that production problems occur is very important, but most importantly you need to plan for them. As one of my favorite financial advisor says, “It’s not a matter of if these events will happen; it’s simply a matter of when they will happen.” Plan your week/month with hours available to investigate strange behavior, crashes or user complaints. Your developers must be on call. I’ve discovered there is a strong correlation between the cleanliness of a developer’s code, and whether or not he had to be on call at some point in his career. People that don’t have to shovel their own shiztpoo do not have stake in preventing problems! Here’s the thing though, the on-call phone is for emergencies. There should be an understanding that if the issue isn’t happening right now, then it doesn’t need to be worked right now. Too often a pager is used to extend an employee’s work day! If you get to the point where you are looking at code, you should probably agree to throw up a 500 page and sick the whole team on the problem in the morning. Furthermore, if a user calls in the middle of the night to report an issue that they failed to report hours ago, chances are it can wait till daylight. It’s important to protect the on call phone, save it for when the meadow is truly on fire! Use a bug tracking system! This is so obvious it amazes me how many companies do not have this. When events occur, update the bug report with an occurrence. It’s very important that you keep record of the event… When you suggest to management they give you time to fix an issue, having a record of the hours spent doing crisis diagnosis is an invaluable resource! Keep an application inventory. Have your developers create a wiki entry for every application, that has the following information:What configuration files are need to run Which databases are connected to What tables are read What EIS systems are interacted with What names of queues/topics are used What usernames are used to interact with above systems Where the logs are located Known problems!Do not underestimate how vital this information is! In your SDLC, you should have a step where the above information is updated! Ok, I’m on call. The phone is ringing. What do I do? Your first step should always be to get an accurate description of the symptoms. You then must narrow the problem scope to either being able: to reproduce it on demand, or predict when it will occur next. For instance, if you have a B2B webservice and the consumer is complaining your sending SOAP faults, your first move should be to have them dump the XML request that is causing the issue. If an end user is complaining about an error message when they click a link, you should have them copy the link and take screenshots. I call this “narrowing the problem.” This is the most important step. It is not optional, you should not proceed to work on a system unless you know what the problem is! You could easily worsen the situation by making arbitrary changes, and the likelihood of doing something random to solve an unknown issue is abysmal. What if the end user causing the problem is not available, or the person on the other end is unwilling to provide the information you’re requesting? I think the best tactic at this point to ask them how they would like you to proceed. Let them finish completely without interrupting. Perhaps they were onto something, or had an alternative. Or perhaps they’re in left field, and if it leans towards left field, explain to them that you cannot solve a problem you don’t understand and can’t recreate. Don’t be afraid to stick up for yourself, it takes information to solve problems! Ok, lets get crackin. It’s late and I want to go back to sleep After you’ve narrowed the problem to a very very specific story or use case, it’s time to get working. First, copy the logs of the production server onto your local computer. If the logs roll while you’re troubleshooting, you may never find root cause. Next, copy any data related to the problem out of the database and store in text format with the log files. This may mean taking a snapshot of configuration tables of an application, the user’s profile rows, and maybe the data they’re trying to access. If you think it’s related, copy it! If you think it’s unrelated, copy it! Finally, note the version of the application, the bugfix level of the server, and the version number of the libraries available on the server. Whew! The next thing is to get a pencil and paper. You should write down ever step you took and the time, and more importantly why you did it. This must be done as you perform the steps, but it doesn’t have to be verbose. For example: “3:12am Noticed the logfile contained many a transaction timeout, meaning the connection pool may be locked. Restarting the application server” There are three parts to this entry, the first is the observation, the second is the analysis, and the third is the action to correct. So how do you find the problem? It’s time to use that application inventory that you did way back in the preventative measures section. Lets say the log is reporting that the user cannot be found in the database. Since you’ve already narrowed the problem, simply refer to your inventory and connect as the application, then proceed to locate the user. If you can’t find them, then problem solved (for now)! Your inventory will tell you exactly what table and database to retrieve this information from. But what if you’re not finding anything? Well… you need to poke around some more. Filter through your logs files and database entries. Do you see anything that looks out of place? Since you’ve already narrowed the issue down and reproduce it, can you try reproducing it using a different user? How about if you tail the log in realtime while the end user create the problem again? Can you enable debug logging in the frameworks (Spring, Hibernate, etc)? Can you reproduce the problem in a non-production environment? How about remote enabling remote debugging and stepping through as the system executes? How about cleaning up temporary files or deleting JSP compilation directories? Has the system ran out of disk space? Finally, does a good old fashioned restart fix the problem? The hangover So you were on the phone for an hour or two last night, what do you do the next day besides show up late? Well before you leave your house, take that pencil/paper with you. Open your bug tracking system, or send an email to the owners and include the original complaint, the logs, the database entries, and what finally fixed the problem. Transcribe your quick notes into the ticket. It’s best if this is done the next day, before your forget how you fixed the problem and why you made the decisions you did. If you followed every step in this entry, you should have no problem giving management a thorough report of what was wrong and how it was fixed. This information is critical to mend over any rough spots with your customers. It can also be used to CYA if any flak comes your way! Finally, I hope this will make you a problem solving rockstar, ready to write better, simpler code (with tons of debug statements using SLF4J). Reference: How to solve production problems from our JCG partner Jonathan at the The Code Mechanic blog. Related Articles :Debugging a Production Server – Eclipse and JBoss showcase Zero-downtime Deployment (and Rollback) in Tomcat; a walkthrough and a checklist Developing and Testing in the Cloud Poor man’s approach in practice Not doing Code Reviews? What’s your excuse? ...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books