Java Master Ep.3 – Naming Conventions | Coding Interview


Naming things, right is eventually, a huge piece of the puzzle that makes your application maintainable, scalable and free from high levels of technical debt. Not to mention some of the ultimate coding goals. We will start with the basic clean up of an example class in order for it to follow the core Java Bean naming conventions. Next, we will get into the implications of a mindset of coding faster and leaving your code base full of abbreviations, single letter names and other scenarios where the naming is not crispy clear and understandable straight away. Following that, we’ll delve in detail into the world of class naming, and we will try to understand that following generally accepted patterns is the way to go here. When talking about naming things, we have to take a peek into the world of testing and try to apply some simple principles to make that area of code base a pleasure to work with. Finally, we will see how important it is to keep the naming of variables, methods and classes in line with the domain of your application. And what ramifications are looking around for ones that will astray from that. If you find the content to be of value then don’t forget to click the subscribe button in order to get notified about any future episodes. Also, if you’re interested in software craftsmanship techniques and automated testing, then go ahead and check out my web site. Also, all the timestamps for today’s chapters are in the description box. If you want to skip to the one that is of interest to you. Now without any further ado, roll it! There is an etiquette regarding the naming of your variables, methods and classes, whether you like it or not. I know following the rules is not much fun, but do you want to be fixing a bug in a class that involves the rules which you know about, or whether you would like to spend additional time on trying to understand a custom naming etiquette of each of the developers? This method is far from being the perfect example of the Java etiquette going from top to bottom, the very first line gives us an idea that the developer wirting this method, well, was not very experienced, to say the least. All the variable and method names always start with a lower case. Next, we have the name, which is definitely missing a verb which is kind of mandatory for a method. As of now, this method seems to be a quite friendly chapter. Well, let’s leave this for now. Next, we have an exception in the definition, but the class is not marked as an exception. This needs to be fixed to comply with the standard. Next line we have a bunch of getters, but they do not start with a get prefix. This needs to be fixed. Otherwise, a lot of frameworks like Spring, Hibernate, or Jackson might not work as intended as they expect that get prefix to be present as per convention. Going further, we have a constant reference. It is defined, though, as a variable with camel-case. This should be upper-cased and words split with underscore. Next up, we set a certain instance variable. But again, we do not follow convention here. We must prefix the method to have a set to follow the etiquette. Finally, we have a seemingly correct getter at the end that simply returns whther the dragon is slane or not. There is an exception when it comes to boolean getters though they should start with an is prefix. OK. After the review, this story does not seem to be so nice and polite like the original naming suggests, it is quite intense, to be honest. Let us see how the final version looks after all the small naming problems have been fixed. Now, this looks like it. The naming and conventions are met thanks to which the method will be easier to read, understand and maintain. And that is the point. Once we know the basic prefixes, suffixes and camelcasesing, it is time to touch upon the notion of shortcuts in your names. This literally neutralizes the benefit of sticking to the Java Bean Convention as your code is still a hell of a complex riddle to solve. We do not want that in our code base. Ok. Here we can see the work of another inexperienced developer who on top of that was very lazy in my opinion. You should be able to clearly understand the intention and the workings of the method. Then a couple of seconds after looking at it, there is no way in hell this time is achievable in this example. We have some generic names like arg one and arg two, math classroom variables that are completely meaningless, and even the method name that can mean anything really. Is the hero stealing something from outside of the castle, or is someone from the castle trying to steal from him? We don’t know for sure. All we know at first glance there is some sort of a hero and a castle in the picture. Also, we can see there is a bunch of lockpicks and some jewelry that is added to arg one as the conclusion of this implementation. Fantastic. The next developer working on this piece of code will be jumping from joy for sure. But seriously, let’s try to do something about it before actually anyone else from the team sees this train wreck. OK. Now we know for sure that a hero breaks into the castle and he does it using the main door. That’s a hell of a brave attempt. I guess he knows what he’s doing. Then he simply tries to open the door using his set of lock picks. If he succeeds at some point. Great. He opened the door and get in. If not, well, the hero is off to find a different castle, I suppose. Then it is clear that he tries to steal only from a jewelry box right now. Maybe more to the implementation later on. That is why the method name is generic. But for now, that is only the biggest deal, which is the jewelry box. Also, it is clear now that the game will only saw the warmth of the jewelry. That said, the jewelry itself will not be kept in the memory. Just to keep the game simple. Class names are what hits the eye of each of the developers first when they are presented with a certain project or one of its modules. If class naming follows a commonly agreed pattern, then an experienced programmer would behave like fish in water and understand straight on what is going on here. If the names are blurry and suffixes completely custom, then development time will start to slow down considerably. We are going to take a look at the usual class design and the REST driven Java Micro Service architecture, which is a staple architecture currently. The outer classes that directly pick up requests sent to particular servers are called controllers. Their aim is to parse the h_t_m_l_ request into a POJO class, validate it and pass on to a service or a Facade. A Facade suffix classes taken directly from the facade design pattern is a high level class that groups service calls. Ideally, methods of facade classes would contain a minimal amount of logic with main aim focus around the service call management. If the application is not complex enough, facade are an optional layer. The service suffixed classes are the heart you can say when it comes to the amount of logic they contain. This is basically where all the logic and algorithms are placed. The number of service classes is usually considerably higher compared to the number of controllers, facades and repositories. Repositories are the final lowest level classes that interact directly with a data source which can be a database, filesystem or even memory directly. They should not contain any crucial logic, only what is needed to get the requested data. Let us look now what happens class-naming wise inside the most interesting layer, the service layer. The service layer is usually where all the magic happens. A lot of times the service method simply become too large to keep them as single methods as they would simply be unmaintainable at some point. We cannot name all other classes services though. That would be childish and boring. There are over a dozen standard class suffixes that every Java developer should be familiar with. Here are the most common ones from that group. We start off with a classic factory. Imagine that in certain areas of our game can spawn orcs in them. The type, of orc, is depending on location and also the hero level. Based on these conditions, the game would create adequate orc enemies for our hero to fight with. Even the smallest applications would have a few of these factory classes at hand. Next, we got singletons. These classes can have only one instance of them. Imagine that in game. There are tens of different drug types. They can randomly spawn at certain locations numerous times. There is one dragon though that is unique and can spawn only once during the course of the entire game. There is always a bunch of unique opponents in any game as well as there are unique classes in each application. Next, we will have the most versatile of the bunch. The Handler. Anything that is deeply specialized could fall under this category. For example, a blacksmith that handles the maintenance of only iron swords. Then we have proxies, these constructs are wrapped around calls to various other classes in order, for example, to perform authorization or perform audit. You could imagine a relentless guardian that does not let anyone near the King before a thorough revision, for example. Then we have tasks. In Java these would be separate threads that perform given job asynchronously so that the application does not freeze for that time but keeps on working. The equivalent would be our hero giving a letter to a messenger that would deliver it for him. He, meanwhile, can go about slaying dragons, seducing ladies or just wandering around. Finally, we got callbacks. These classes relate directly with tasks. They’re executed once a certain asynchronous task is finished. Imagine that a duel between two nights is a task. Then for a hundred percent after the fight is finished and there is a winner, the prettiest girl in town will give the him a kiss. In the testing area over a code base, the rules are a bit different than the sources themselves. Here it is about expressing behaviors. The behavioral driven design is the way to go here and your test suite should also be literally soaked with it. Fighting with the Boss seems to be a straightforward action and unit testing seems easy. There are quite a few details, though. The casting of a spell before the battle, checking for critical hits, deadly blows. Doing that in the loop until one of the attackers gets slained. So eventually it turns out there are a couple of scenarios to test here. Let’s see how not to write unit test for this method. The first mistake is in the name. Already we do not use test in test method names. That is obvious. We do not need to put in there. Another mistake is the usage of the same name as the original method name. This seems logical at first, but imagine that the original method name changes and someone forgets to change the test suite. This will cause confusion and increase the technical debt. Also, we do not know what we are testing for exactly. We must know that just by looking at the test method name. Going further, someone has packed all the possible test scenarios under this one method. The killing of the boss in one hit. A longer, tougher bottle and also the defeat of the hero itself. Imagine that the original method will be extended considerably. Then our test method would get bloated to hundreds or even thousands of lines. This would make it unreadable and unmaintainable. Let’s see how things should be done. First of all, we can see that each of the test cases has its own specialized method. Second of all, the method names use the behavioral driven design style of naming. Thanks to that we know exactly why the test failed, under what circumstances and for what kind of input variables. Now we have a clean, clear, maintainable and readable testing suite in front of us. It amazes me how abstract the language of some developers can get. And yes, all that we do is literally virtual and intangible There’s a pile of zeros and ones in the end somewhere in the memory. What I would like from you is to stop being purely logica, generic, machine like and repetitive. Get to know the domain you’re coding in and adjust your coding language. Be creative and in line with what the current application is all about. For our last example, we will go through the increaseCareerProgress method. What the hell is this? And we’ll be doing this for a person. Wow. OK, I did not expect that. First we increase the career progress by one. This is for now seems to be some sort of a corporate tycoon game that is just so boring. Anyway, going further every 10 career points, we add some sort of a special equipment to our generic person. So like a new graphics card to his laptop? OK. Next, every five career points we generate a bonus. I guess he gets a bunch of cash at his disposal. And finally, if there is no drug in that person, we generate one and give it to him. Wow. Now that starts to be dodgy. I need to talk to the developer that is responsible for this thing. Okay. So we sat down together and refactored that pesky method a bit. Now things might get more familiar as expected. We can see straight away that we aim at leveling up our hero, and we start by setting his level up by one. Right now we know where we stand. Moving forward. It is not about a generic equipment piece. It does about a special armor piece. Now we’re talking. Next, our hero does not care about some cash. He wants gold, for God’s sake. And finally, we do not give him any drugs, but add some beneficial potions that he can use later on to increase his strength, speed or agility. Did any of you expect that at the beginning? As you saw, such a seemingly trivial thing as naming conventions and standards can have a huge impact on the general maintainability, readability and overall pleasure of working within a given code base. We have gone through the basic Java Bean conventions, made sure that our class names give us an initial idea of the responsibility, proven that abbreviations have their place on the graffiti walls, but not in a respectable code base. We did not forget about the testing area and how the behavioral driven design plays a huge role there. Finally, all should be aware that if you’re coding an RPG game, do not use the domain language from a financial application that was your previous gig. Now I hope you enjoyed today’s content and I hope it has added a few ideas to your software craftsmanship toolkit. Now I’m looking forward to seeing you again on our next episode.

Leave a Reply

Your email address will not be published. Required fields are marked *