Arrogance, humility and software development

23 01 2010

One’s true greatness is inversly proportional to behaving as if one were great, just as one’s true smallness is inversly proportioanl to behaving as if one were small. (Anonymous)

The more I learn, the more I realize I don’t know. (Albert Einstein)

You should have heard about how arrogant developers are terrible in communication with team members and client or you should have met an arrogant developer who never listens anyone else, thinks he knows everything and who is also very rude.

Once upon a time, you might have had at arrogant aggressive collages, who cover their frustrations with aggression, finding yourself in feeling of “never be part of anything which they are in”.

What is arrogance?

Arrogance is an offensive display of superiority and self-importance. It destroys professionalism by reducing the individual’s ability to think for himself or herself, making empathy for others difficult and removing the checks and balances of self-doubt.[1]

Arrogance is the reason for many failures. It could kill any company in any stage of its life. It could kill any work in any stage of its life. If you analyze the failures of the giants, you will see that most of their failure come form their arrogance.[2]

So why are people are arrogant? It is a mask hiding various types of states: It is a way to fill the inner emptiness with a big ego, actually, which makes them a slave of their own ego. Also, it is a way to cover up insecurity and frustration.

Personally, I don’t know anyone who likes arrogant people. They are not being more appriciated, not more admired, on the contrary, peoples dislike them.

I believe that it is one of the worst thing in business to have arrogants. They cause a tremedous amout of discord in the workplace. They ignore others and seperate themselves from others, and pull down the energy level of the people.

Lets consider developers’ arrogance, generally they cannot learn from others, they reject it. They even don’t listen others. They are very rude in discussions, which they make it go nowhere. So, in this situation, who is the looser? In the team, they hurt the team sprit. They are a kind of obstacle slowing down the team to reach the goal. To put it short, their damage is to both themselves and the team.

How to deal with arrogant

The belief of that you have to be arrogant in an arrogant world to survive is nothing but adding fuel to the fire. Considering it is more likely related with inner problems of the arrogant, responding with arrogance only makes you another arrogant, nothing more. It doesn’t help solving the problem with only exception that the arrogant may feel seeing himself in the mirror. But it is very hard to see it in negative response. Being cool and sedate or being confident in silence help more.

If you feel arrogant

When you feel arrogant,  here is the motto : Treat others as you would wish to be treated yourself. Think you’re just human, ordinary mortal human. Be sure , somewhere, there is a better professional than you, and also he/she is smarter and more genios than you.

Breaking of arrogance starts with seeing it, knowing it. The people around you and feeling of something is wrong with you somewhere inside you may be hints. Accepting and seeing the truth of that we are at the same level of importance as others is a cure for arrogance.

The feeling you have when you see the greatness of your work and your thought should not lead to arrogance, you should be thankful to have that gift, keeping in mind that it is given to you to use in benefit of humans.

If you look at life, you can also easily see every extraordinary thing given to the human is supposed to be used in benefit of others and if he uses it for himself, like arrogance, he pays a lot for it.So, even if you are gifted, there is no excuse for being arrogant.

Arrogants are knocked out sooner or later, without any exception. One day, they find themselves brought down to the floor. This is how it works. You can easily find many instance of this situtaiton in the history. A lot of giants vanished because of thier unwarranted arrogance.

Cofidence vs Arrogance

Confidence and arrogance are different. Arroagance goes beyond healty confidence. Confidence is being aware that you know something, whereas arrogance is being overly concerned with aware that you know something.

Humility

Humility, or being humble, is the defining characteristic of an unpretentious and modest person, someone who does not think that he or she is better or more important than others. Because the concept of humility addresses intrinsic self-worth, it is emphasized in the realm of religious practice and ethics where the notion is often made more precise and extensive.[3]

Dignity of the knowledge and wisdom requires humility, which is one of the greater virtues one of the most appreciated personal qualities.Its absence is a direct obstacle to comunication; and can generate enemies, so it’s a necessary social behavior and part of being professional.

Humility comes with being aware of your strenghts, weaknesses and abilities. This also gives you the ability to approach situations in a superior way. Extreme humility [4] is a nice example for it.

Humility is more useful in problem solving; you don’t trust your self blindly and fail and blame other people or other things for failure. To put in another way, you will find that you are much more open to opportunities to learn and improve the project you are working on.

And software development

Humble people are a lot more pleasant and easy to work with. They don’t make their superiority an issue, they don’t always know better, they listen and respect and value others’ ideas.

Arragont developers! You’re killing what you’ve done and your team’s work .You are not being more appriciated, not more admired, on the contrary, you are loosing them. Your ego keep you from being great developer. The more humble you are, the faster you’ll improve. So, why arogance?

Developers! Know your strenghts, your weeknesses, know what you know and what you don’t. Be open to communication, listen others, respect people. Be confident about yourself, but never ever be arrogant .Knowing yourself, your capabilities and inabilities leads you to a way for improving your skills.

Everybody can make mistakes, everybody can write code in poor quality, but the virtue is to admit it and learn from them.

Managers! Even you may be in a dazzling position, but it does not require to be arrogant. First of all, never ever be arrogant. And do not hire arrogant people. If you have any between your employees, give a bit time to them for recovering themselves from arrogance and also help them in doing that, if they still persists, get rid of them. Value confidence. Never forget your team is very important.

References

  1. Professionalism Initiative http://www.kumc.edu/som/professionalism.html
  2. Success, Arrogance, Rise and Fall http://eclipse.sys-con.com/node/43873
  3. Humility http://en.wikipedia.org/wiki/Humility
  4. Extreme Humility http://c2.com/cgi/wiki/wiki?ExtremeHumility




Verify details of argument passed to the mocked object

22 01 2010

Mockito,my favoritte mock library, introduced ArgumentCaptor with 1.8. ArgumentCaptor allows you to capture and store arguments passed the mocked methods.
The captured arguments are available with the methods like getValue and getValues.
So, the arguments can be easily verified by using standart JUnit assertions.


ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName())





Value Objects

27 12 2009

The value objects are simple but very useful objects. Value object, one of the powerful concept from DDD, is an object that describes a characteristic of a thing.

According Eric Evans,

“An object that represents a descriptive aspect of the domain with no conceptual identity is called a value object. Value objects are instantiated to represent elements of the design that we care about only for what they are, not who or which they are.” [Evans 2003]

Here a few characteristics of value object:

  • The key defining characteristic of a value object is that it has no identity. In other words, the intention of a value object is to represent a concept by it’s attributes only.
  • They should probably be immutable, once created they cannot be changed or altered.
  • They are not DTOs, not Java beans and not objects with public fields, they encapsulate data with some behavior. DTOs are bunch of data, which are not necessarily coherent, VOs contains high-chorent data with behavior. The purpose of DTOs is data transfer but the purpose of the VOs is domain representation.
  • They are mostly very simple objects.
  • They “swallow computational complexity”.
  • More extensible
  • More testable
  • Some examples of value objects are money, addresss, phone number, product code, email address, etc..





A Concise solution for hashCode() and equals() implementations

23 06 2009

Currently, I was working on improving code quality. Some of the violations were due to the code generated by eclipse for hashCode() and equals() methods in the domain model classes. I was thinking on writing a builder classes for these methods, later on I just came across the Apache Commons Lang builder classes. It was even better than I imagined:)

Actually, the Apache Commons org.apache.commons.lang.builder package contains builder classes to help implement methods like equals() , hashCode() , compareTo(), and toString().. They are implemented to follow rules from in Effective Java , by Joshua Bloch

Considering clarity, readability and maintainability of the code, they are very concise and consistent solution.

The EqualsBuilder
Here is the sample usage of EqualsBuilder from API docs.

public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof MyClass)) {
return false;
}
MyClass other= (MyClass) obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(field1, other.field1)
.append(field2, other.field2)
.append(field3, other.field3)
.isEquals();
}

It is good to be carefull with isEquals() method, it is a common mistake to use equals() of the EqualsBuilder instead of isEquals().

The HashCodeBuilder
Here is the sample usage of HashCodeBuilder:

public int hashCode() {
return new HashCodeBuilder().
append(field1).
append(field2).
append(field3).
toHashCode();
}

It is good to be careful again with toHashCode() method, it is a common mistake to use hashCode() of the HashCodeBuilder instead of toHashCode().

Alternatively, you can use the reflection-based static methods:

public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o);
}
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}

However, I think reflection implementations are not good for a real project: They are potentially much slower and it is very important for domain model, the fields icluded in these methods should be carefully and intentionally selected considering the implication on the model.





Optimistic Locking and Versioning in Hibernate

16 05 2009

What is optimistic locking?

Optimistic locking is a method used to prevent simultaneously access problem on the same entity for change, which does not lock on the database level, in order to maintain the correct data.

For example, if two user wants to update same entity in different transactions, when first one saves and then second one saves without getting updates from the first user’s change, who will be the winner?

Most of the web applications, like ours, has such cases: Two users retrieve and modify a data on the page, then first user saves the data a transcation and then second user modifies and saves the data in an another transacion. Here are 3 alternatives:
1. Last commit wins : Both updates are performed, the second user overwrites without seeing the first user changes and without any error message
2. First commit wins : (Optimistic Locking) The update is performed, but second user gets error message, requiring restart of the processes on the first users changes.

3. Merge conflicting update : The second user are prompted to merge changes.

Automatic Versioning

Hibernate provides automatic versioning for options 2 and 3, using a version field managed by hibernate.

Versioning with integer version

public class MyClass {
...
private int version;
...
}


<class name="MyClass">
<id ...>
<version name="version" column="VERSION" access="field">
...
</class>

Versioning with timestamp

public class MyClass {
...
private int lastModifyDataTime;
...
}


<class name="MyClass">
<id ...>
<timestamp name="lastModifyDataTime" column="LAST_MODIFIY_DATE_TIME" access="field">
...
</class>

Automatic versioning is handled by hibernate, you don’t need to update versions/timestamps.
Considering the example mentioned above, when second user saves, hibernate finds this user is working on the stale data and throws StaleObjectException.

You can catch this exception, and rethrow your own exception. By the way, if you’re using Hibernate with Spring, this exeception is wrapped with HibernateOptimisticLockingFailureException.

One more point, you should be aware of that hibernate ignores the versioning when getting object and updating fields and then version are in the same session.





User access to another schema in Oracle: Alternative to public synonyms

26 03 2009

Consider that there are 2 users in your database having their own schemas, but second user having less permission is required to work on the first schema. Possible solutions :

1 . To  create public/private synonyms

2. Use schema name in the queries.

3. Modify user session to point the first schema. Create a trigger on login.

CREATE OR REPLACE TRIGGER &app_user..APP_USER_LOGON AFTER LOGON ON &app_user..SCHEMA DECLARE

BEGIN

            EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA = '|| UPPER('&owner_user');

   EXCEPTION

     WHEN OTHERS THEN raise_application_error(-20001, 'Error: ' || SQLERRM );

END ;




Spring Security: Authenticate user on LDAP without manager/admin user

26 03 2009

In my previou post on spring security with LDAP, I had used a manager/admin user to authenticate a user.

You can use the following code to authenticate the user directly, without manager/admin user:

<ldap-server id="ldapServer" url="ldap://ldapserver:port"/>

  <beans:bean id="bindAuthenticator" class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
    <beans:constructor-arg ref="ldapServer" />
    <beans:property name="userDnPatterns">
      <beans:list>
        <beans:value>CN={0},ou=Users,dc=example,dc=com</beans:value>
      </beans:list>
    </beans:property>
  </beans:bean>




Spring Security : Use Ldap for authentication, and database for authorities

12 03 2009

If you need to use Ldap for authentication and database /repository for authorization with spring security, here is a sample:

LDAP authenticator configuration

<ldap-server id="appLdapServer" url="ldap://ldapserver:port/dc=example,dc=com" manager-dn="uid=admin,ou=system" manager-password="your-pwd" />

<beans:bean id="companyLdapAuthProvider" class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
  <custom-authentication-provider />
  <beans:constructor-arg>
    <beans:bean class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
      <beans:constructor-arg ref="appLdapServer"/>
      <beans:property name="userDnPatterns">
        <beans:list><beans:value>uid={0},ou=Users</beans:value></beans:list>
      </beans:property>
    </beans:bean>
  </beans:constructor-arg>
  <beans:constructor-arg>
    <beans:bean class="com.mycompany.web.security.MyAuthoritiesPopulator">
      <beans:constructor-arg ref="myUserServiceBean"/>
    </beans:bean>
  </beans:constructor-arg>
</beans:bean>

Authorities populator:

public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {

	private MyUserService userService;

    public MyAuthoritiesPopulator(MyUserService userService){
       this.userService = userService;
    }

	@Override
	public GrantedAuthority[] getGrantedAuthorities(DirContextOperations userData, String username) {
		Set userPerms = new HashSet();

        //get users permissions from service
		Set permissions = userService.getPermissions(username);

		for (MyPermission perm : permissions) {
				userPerms.add(new GrantedAuthorityImpl(perm.getName()));
		}
		return userPerms.toArray(new GrantedAuthority[userPerms.size()] );
	}
}




Return dynamic result from mock with Mockito

4 03 2009

Sometimes you need to stub a class only for a method and you may need to add some behavior to that stubbed mehod like get a value from a map and return it.
Instead of just returning an object for the stubbed method like:

when(mock.aMethod(anyString())).thenReturn("a static result");

you can return a dynamic result by using stubbing with callbacks feature of Mockito.

when(mock.aMethod(anyString())).thenAnswer(new Answer<MyObject>() {
     MyObject answer(InvocationOnMock invocation) {
         Object[] args = invocation.getArguments();         
         //you can do some stuff using args
         return ...;
     }
 });

In answer method you can access the mocked object itself :

Object mock = invocation.getMock();

By the way, this brings a bit complexity to your test. If you don’t really need it, do not use it. 
Don’t forget simplicity.





Hibernate inverse

9 07 2008

I have seen that many people have a confusion with Hibernate’s inverse keyword. Maybe, the term itself is a bit confusing.

The keyword “inverse” indicates which end of a relationship should be ignored. inverse=true means that this side is the inverse side, that is, this side is ignored. inverse=false means that this side is not inverse, that is, this side is the owner of the relationship.

Actually, to decide inverse value, you should think about what you want to do in parent-child relationship. If your parent class contains child list and child class has a reference to parent, and you want the parent to have the responsibility of the relation, i.e, save, delete, etc. operations, then you need to set  inverse=false at the child list property in the parent’s mapping file.