A good clear principle for any software engineer and developer is that any class, method or function that you create and use should only have the bare minimum number of necessary arguments passed into it to correctly operate and not know more about the system than it should. Recently I have been doing some merge reviews and too many times I have seen the below case from both junior and (surprisingly) senior engineers:
... Object object = getObject(); Date objectDate = getObjectDate(object); ... private Date getObjectDate(Object object) { ObjectReader objectReader = new ObjectReader(object.getId()); return objectReader.getDate(); } ...
As soon as I see the above I leave a comment on the merge request, something along the lines of “Why does the getObjectDate(Object) method need to take the entire object instance?“. This then forces the one who submitted the merge request to stop and think what is being done, and should it be refactored in someway.
In this case, the method only uses the object’s id to build a reader and get the date from the object. The actual object is not being used at all. Instead of passing the entire object into the method the id should only be passed in. There is less overhead. We should be seeing something like below:
... Object object = getObject(); Date objectDate = getObjectDate(object.getId()); ... private Date getObjectDate(String objectId) { ObjectReader objectReader = new ObjectReader(objectId); return objectReader.getDate(); } ...
By only passing the bare minimum to the methods or classes then you are ensuring that your system does not know more than it needs to. By enforcing this rule, IMO you are ensuring that the system is:
- Cleaner – you know exactly what is being used and for what purpose.
- Safer – you are ensuring that only what you want to be manipulated can be manipulated and where.
- Modular – there are clearer separations between what needs to be done with what and where.
So when you are creating new classes or methods then consider what you are using as your arguments, what the method needs to do, and what exactly you need to pass in. Taking the time to logically structure your code and think through what is necessary for the method to do its job will save you massive headaches in the future. Short term pain, for long term gain 🙂