Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should my classes restrict developers from doing wrong things with them?

I am trying to understand where good contracts end and paranoia starts. Really, I just have no idea what good developer should care about and what shall he leave out :)

Let's say I have a class that holds value(s), like java.lang.Integer. Its instances are aggregated by other objects (MappedObjects), (one-to-many or many-to-many), and often used inside MappedObjects' methods. For performance reasons, I also track these relationships in TreeMap (guava MultiMap, doesn't matter) in addition, to be able to get fast iterations over MappedObjects bound to some range of Integer keys. So, to keep system in consistent state, I should modify MappedObject.bind(Integer integer) method to update my Map like:

class MappedObject {
    public void bind (Integer integer) {
        MegaMap.getInstance().remove(fInteger, this);
        fInteger = integer;
        MegaMap.getInstance().add(fInteger, this);
    }

    ...

    private Integer fInteger;
}

I could just make abstract MappedObject class with this final method, forcing other to inherit from it, but it is rude. If I will define MappedObject as interface with method bind() and provide skeletal implementation -- other developer might later just forget to include it in object and implement method by himself without Map updating.

like image 578
0andvoid Avatar asked Nov 29 '11 12:11

0andvoid


2 Answers

Yes, you should force people to do the right thing with your code. A great example of letting people do the wrong thing is the servlet method init( ServletConfig config ) that expected you would store the servlet config yourself but, obviously, a lot of people forgot to store the config and when running their servlets just failed to work.

When defining APIs, you should always follow the open-closed principle, your class should be open for extension and closed for modification. If your class has to work like this, you should only open extension points where they make sense, all the other functionality should not be available for modification, as it could lead to implementation issues in the future.

like image 136
Maurício Linhares Avatar answered Oct 21 '22 13:10

Maurício Linhares


Try to focus on functionality first and leave all unnecessary things behind. Btw you can't prohibit reflection so don't worry too much on misuse. On the other hand your API should be clear and straightforward so users will have clear idea, what they should and what they shouldn't do with it.

like image 1
dhblah Avatar answered Oct 21 '22 13:10

dhblah