background preloader

Best practices and common mistakes

Facebook Twitter

12 common programming mistakes to avoid | Geek Files. Programming is an art and science and like all art and science the only way to learn is from mistakes. I have made many… and I would like to share with you the mistakes that I have made over my journey with development. These are some of the most common programming mistakes made by developers (including me) and how to avoid them (not listed in any specific order) Can you imagine a program without comments. Just imagine how difficult it would be to read someone else’s code without comments. The reason why we as developers miss out on comments is because when we write code, we are so engrossed in developing logic that we forget this essential step. I recommend that let you develop with the flow of logic that you have and plug in comments after you finish coding.

{*style:<b>2. </b>*}Once you get that big ‘AAha’ feeling looking at your code after you have completed it, it’s best to review your code immediately and try finding issues if any. {*style:<b>4. {*style:<b>6. {*style:<b>8. Don't repeat yourself. Applying DRY[edit] DRY vs WET solutions[edit] Violations of DRY are typically referred to as WET solutions, which is commonly taken to stand for either "write everything twice" or "we enjoy typing".[2][3] See also[edit] References[edit] External links[edit]

How to think about OO. By Miško Hevery Everyone seems to think that they are writing OO after all they are using OO languages such as Java, Python or Ruby. But if you exam the code it is often procedural in nature. Static Methods Static methods are procedural in nature and they have no place in OO world. I can already hear the screams, so let me explain why, but first we need to agree that global variables and state is evil. This means that for a static method to do something interesting it needs to have arguments. But most justifications for static methods argue that they are "utility methods". In the end I am sometimes (handful of times per year) forced to write static methods due to limitation of the language. Instance Methods So you got rid of all of your static methods but your codes still is procedural.

The problem here is the method may as well be static! The funny thing about the getter methods is that it usually means that the code where the data is processed is outside of the class which has the data. Flaw: Brittle Global State & Singletons. Accessing global state statically doesn’t clarify those shared dependencies to readers of the constructors and methods that use the Global State.

Global State and Singletons make APIs lie about their true dependencies. To really understand the dependencies, developers must read every line of code. It causes Spooky Action at a Distance: when running test suites, global state mutated in one test can cause a subsequent or parallel test to fail unexpectedly. Break the static dependency using manual or Guice dependency injection. NOTE: When we say “Singleton” or “JVM Singleton” in this document, we mean the classic Gang of Four singleton.

(We say that this singleton enforces its own “singletonness” though a static instance field). An “application singleton” on the other hand is an object which has a single instance in our application, but which does not enforce its own “singletonness.” Why this is a Flaw Global State Dirties your Design Global State enables Spooky Action at a Distance. Static Methods are Death to Testability. By Miško Hevery Recently many of you, after reading Guide to Testability, wrote to telling me there is nothing wrong with static methods.

After all what can be easier to test than Math.abs()! And Math.abs() is static method! If abs() was on instance method, one would have to instantiate the object first, and that may prove to be a problem. The basic issue with static methods is they are procedural code. Here is another way of thinking about it. Lets do a mental exercise. We have already covered that global state is bad and how it makes your application hard to understand. Sometimes a static methods is a factory for other objects. “So leaf methods are ok to be static but other methods should not be?” Breaking the Law of Demeter is Like Looking for a Needle in the Haystack. July 18th, 2008 · 20 Comments · by Miško Hevery Every time I see Law of Demeter violation I imagine a haystack where the code is desperately trying to locate the needle. class Mechanic { Engine engine; Mechanic(Context context) { this.engine = context.getEngine(); } } The Mechanic does not care for the Context.

You can tell because Mechanic does not store the reference to Context. Most applications tend to have some sort of Context object which is the kitchen sink and which can get you just about any other object in the system aka the service locator.If you want to reuse this code at a different project, the compiler will not only need Mechanic and Engine but also the Context. But here is the real killer! Every time I have to write a test I have to create a graph of objects (the haystack) which no one really needs or cares for, and into this haystack I have to carefully place the needles (the real object of interests) so that the code under test can go and look for them.

. – Miško Hevery. Procedural Language Eliminated GOTOs; OO Eliminated IFs. August 14th, 2008 · 7 Comments · by Miško Hevery Procedural languages allowed us to remove GOTOs in our code. I would like to think that OO languages allow us to remove IFs (conditionals). I know you can’t remove of all the IFs, but it is interesting just how many IFs you can remove in an application. You can’t remove these IFs: Comparing relative sizes (>, < operators)Comparing primitives Recently I came across a very interesting and clever way to get rid of IFs when doing lazy initialization.

For extra credit you can do thread safe initializer as well class abstract ThreadSafeLazyInitializer implements Getter { private Getter getter = new Getter() { public synchronize T get() { return synchronizedGetter.get(); } }; private Getter synchornizedGetter = new Getter() { public T get() { final T value = initialize(); gettter = new Getter(){ T get() { return value; } } synchronizedGetter = gettter; } }; protected abstract T initialize(); public T get() { return getter.get(); } }

How to think about OO. Everyone seems to think that they are writing OO after all they are using OO languages such as Java, Python or Ruby. But if you exam the code it is often procedural in nature. Static Methods Static methods are procedural in nature and they have no place in OO world. I can already hear the screams, so let me explain why, but first we need to agree that global variables and state is evil.

If you agree with previous statement than for a static method to do something interesting it needs to have some arguments, otherwise it will always return a constant. This means that for a static method to do something interesting it needs to have arguments. But most justifications for static methods argue that they are “utility methods”. In the end I am sometimes (handful of times per year) forced to write static methods due to limitation of the language. Instance Methods So you got rid of all of your static methods but your codes still is procedural.

The problem here is the method may as well be static! How To Think About OO. We Recommend These Resources Everyone seems to think that they are writing OO after all they are using OO languages such as Java, Python or Ruby. But if you exam the code it is often procedural in nature. Static Methods Static methods are procedural in nature and they have no place in OO world.

This means that for a static method to do something interesting it needs to have arguments. But most justifications for static methods argue that they are “utility methods”. In the end I am sometimes (handful of times per year) forced to write static methods due to limitation of the language. Instance Methods So you got rid of all of your static methods but your codes still is procedural. The problem here is the method may as well be static! The funny thing about the getter methods is that it usually means that the code where the data is processed is outside of the class which has the data. Now this begs the question: should the User know about the Ldap? Should User have a field reference to Ldap? Falsehoods Programmers Believe About Names: MicroISV on a Shoestring. [This post has been translated into Japanese by one of our readers: 和訳もあります。] John Graham-Cumming wrote an article today complaining about how a computer system he was working with described his last name as having invalid characters.

It of course does not, because anything someone tells you is their name is — by definition — an appropriate identifier for them. John was understandably vexed about this situation, and he has every right to be, because names are central to our identities, virtually by definition. I have lived in Japan for several years, programming in a professional capacity, and I have broken many systems by the simple expedient of being introduced into them.

(Most people call me Patrick McKenzie, but I’ll acknowledge as correct any of six different “full” names, any many systems I deal with will accept precisely none of them.) So, as a public service, I’m going to list assumptions your systems probably make about names. This list is by no means exhaustive. About Patrick. Thai personal names - James Clark's Random Thoughts. There's an election coming up in Thailand on December 23rd and the streets are lined with election posters. As a bit of an i18n geek, I find it interesting that the posters almost all make the candidates' first names at least twice as big as their last names. If you're also an i18n geek, your reaction might well be: "it must be because Thais write their family name first, followed by their given name".

But you would be wrong. Thais have a given name and a family name; the given name is written first, and the family name last. The correct explanation that given names play a role in Thai culture that is similar to the role that family names play in many Western cultures. The polite way to address somebody is with an honorific followed by their given name. (I have to say that this has led me to question what I perceive to be the i18n orthodoxy that it's more i18n-ly correct to talk of given name/family name than first name/last name. ‘Real’ names online, part 2 : defining ‘real’ - A Modern Hypatia. Before we get into the more interesting meat of the topic (which will follow next week), I want to go into a digression about the problem of ‘real names’. First problem: What does a ‘real name’ look like? We like to think that we know them when we see them. But really, we don’t.

Some names look perfectly reasonable, but might not be real. (People with ‘Smith’ as a last name, and a common first name sometimes have this problem in reverse.) There’s a great post by Patrick, a programmer, talking about the problems simply designing a system to handle names – of all types – appropriately that goes into far more depth. So, when we’re saying ‘use a real name’, what we’re actually saying is ‘use a name that other people recognise as ‘real’. Second problem: Is that name actually a unique identifier? I have a very common first name (Jennifer) and a much less common last name (at least in the US: it’s much more common in Ireland, parts of England, and Australia). These days, if you yell “Hey, Jen!” Background (‘real’ names online : part 1) « A Modern Hypatia. I’ve been watching the conversations about the new RealID additions on the Blizzard forums with some interest, because they tie into a much larger conversation about online interactions and anonymity and pseudonymity.

So, in the next week or so, a few posts about first, some background, and then some specific concerns and considerations around the use of real-world identifying names online. Why does this matter on a librarian’s blog? Well, first, because I use the ‘Net, and I’m fascinated by how other people use it, and about how to help give people tools to make informed choices for their use of it. But also because I think this is one of the major freedom of information issues of at least the next decade: how do we balance a desire for sincere conversation, with meaning and history and in the context of a particular community, with the reality that some people will abuse, harass, intimidate, or otherwise seek to harm others. To start with, some history Are these things common? Personal names around the world. Background People who create web forms, databases, or ontologies are often unaware how different people’s names can be in other countries. They build their forms or databases in a way that assumes too much on the part of foreign users.

This article will first introduce you to some of the different styles used for personal names, and then some of the possible implications for handling those on the Web. This article doesn't provide all the answers – the best answer will vary according to the needs of the application, and in most cases, it may be difficult to find a 'perfect' solution. It attempts to mostly sensitize you to some of the key issues by way of an introduction. The examples and advice shown relate mostly to Web forms and databases. Scenarios There are a couple of key scenarios to consider. You are designing a form in a single language (let’s assume English) that people from around the world will be filling in.

Examples of differences Given name and patronymic Multiple family names . Comment les noms diffèrent à travers le monde ? Le W3C se penche sur les implications pour les formulaires et bases de données Web. Mise à jour de Gordon Fowler Le simple fait de demander un nom et un prénom dans un formulaire web peut paraître trivial. Mais à bien y réfléchir, cela ne l'est pas. C'est en tout cas le point de vue du W3C qui vient de publier une page de conseils. Le point central est de rappeler que la notion de « patronyme » varie avec les cultures et les pays. Un développeurs ayant travaillé sur le système de réservation des JO de Pékin rappelait par exemple que demander son nom à un utilisateur en Chine était moins pertinent qu'en Europe. D'après Wikipedia, trois noms (Nguyen, Tran, Le) sont portés par 60% de la population Vietnamienne.

A l'opposé, la France est un des pays au plus grand nombre de noms de famille. Autre point sensible, demander deux noms (de famille et prénom) peut paraître très étrange dans certaines régions du monde. Bref, demander une identité exige de se poser certaines questions auxquelles beaucoup ne penseraient pas au premier abord. « Personal names around the world » Et vous ?