The Fact/Intention Gap 39
The other day, I was browsing some code with a team and we came across a cluster of static methods. I looked at them and asked whether they were used someplace else without an object reference. I could’ve done a find references in the IDE, but one of the team members had the answer: “No, they’re just used here.”
“Okay, so why are they static?”, I asked.
“Well, the IDE pointed out that they don’t refer to any instance data, so I made them static.”
Technically, there’s nothing wrong with that. I do the same thing sometimes. I make a method static to document its independence of instance data. But, this scenario highlights something important about static and a few other keywords: their uses can be seen as statements of fact or statements of intention. Static can be read as “Hey, this function doesn’t use any instance data, and you should know that.” Or, it can be read as “I am making this static so that it can be used easily anyplace without an instance.” When you’re trying to read a pile of unfamiliar code, it’s nice to know whether you can count on one meaning or the other.
I don’t think I’ve ever heard anyone articulate this directly, but there’s a tendency in a lot of best practice literature to close the gap between fact and intention. Joshua Bloch’s advice to use make fields final whenever you can in Java is a good example. The traditional advice to make methods private whenever they are not used outside of a class is another.
Part of me feels that closing the gap is a good practice but the fact is, there are holes in it. If you are developing a library or a framework, you do have to write code that may not reflect the facts of your code, but rather will reflect the facts of your code and the code that people write to use it or extend it. Beyond that, it might be overly conservative to reduce visibility of things that aren’t used beyond a particular scope. For instance, imagine a method that is used only by other methods of a class. We understand the invariant of the class and we see that the method could be public. We could make it private now, but that means that anyone who wants to make it public later would have to do some re-analysis to arrive at the answer that we have right now.
The Fact/Intention Gap is a very real thing. Whether we know it or not, we confront it every time we try to understand unfamiliar code. I think there’s only one way to solve it, and that’s to try to separate fact from intention in our languages and tooling. Imagine what it would be like if your IDE gave you a visual indicator for all methods which didn’t use instance data. If it did, you could use static on methods only when you want to indicate that the intention is to use them without an instance.
It seems that IDE developers are moving in this direction. I wonder if any language designers will follow suit.
Great post, Michael.
Personally, I’m a huge static hater. Mostly because of the difficulties they bring with dependencies. I much prefer class-methods a la Ruby, which are instance methods of a different object (the class).
I like the view that static’s signify a lack of reliance on fields. While I’m not a huge fan of mixing data and behavior in my classes, I can see the point there.
Nice post.
All too often I get caught up with the semantics of the syntax and not how my use of the syntax might be interpreted by later developers. Is my use a statement of fact or a statement of intent?
You’re post has given me some food for thought.
Justin
I run across this problem a lot. However, I am a static lover! The thing about making a method static is it clearly states “the logic of this function is self contained” Not only is this self contained, it removes a dependency on the instance of the object. Now, I agree that the inability to override the method is annoying, and wish there was a clean way to avoid that, but compare that to just what the instance object dependency that is NOT USED can mean.
1) you might need a connection to a database to create the object
2) you might need a invoke the gui system to call the function (anything on a object that extends jpanel)
3) you might need a very complicated system to be created (anything on an object in the eclipse editor)
4) you might need it figure out which constructor to use (any object that doesn’t have a default constructor)
Also as to intention, static function state the cleanest intention of what the parameters are. take the follow example:
findFirstDifference()
int findFirstDifference(String first, String second)
the second is much clearer on what the parameters are and what the outcome is. In ‘clean code’ bob martin says “the ideal function has zero parameters” but I disagree. I believe the ideal function has only the parameters it actually needs.
when you say findFirstDifference() you really mean findFirstDifference(this) and it is rare that you actually need all the member variables in your object.
When I see a lot of static methods, my first question is whether or not there’s another class in there just crying to be free. Maybe there should really be a singleton instance of that embedded class. Moving back to an instance restores the option of subclassing and overriding later to change behavior.
That’s not always the case, though. For example, most large applications end up with a “StringHelper” class that provides service methods for strings that you wish were on String itself.
“We understand the invariant of the class and we see that the method could be public. We could make it private now, but that means that anyone who wants to make it public later would have to do some re-analysis to arrive at the answer that we have right now.”
Sure, but on the other side of the coin, once it is public not only must all future implementations implement it (or I have to rework all the clients), but it must also maintain that invariant.
It isn’t overly conservative; rather, it is just a tradeoff.
Every now and then I’m annoyed when I try to extend a Java program, but some of the classes which I need to access are package-private. Sometimes even most of the classes in a package are package-private. Then I end up creating wrapper classes (in the same package or using reflection) just for accessing some of the public or package-private methods in those classes.
resharper tells you when a method doesn’t refer to instance data, and prompts you to make it static :)
Great post. Now I have a name for the thing I deal with anyway.
In case of “intentionally static” methods I believe it shouldn’t be hard to do it in IntelliJ with @Static annotation and some inspection which checks that annotation is used correctly.
Going a bit off topic, I think it may also be interesting to hightlight instance methods calls to see points where object state is used; sometimes I add temporary static modifier to do it.
ah ha
so
MTS Converter can help you to convert mts files easily and quickly, and it is very easy to use. if you are in need, you can download it and experience by yourself.
Main Features of MTS Converter
Convert PDF files with high quality – transfer, backup, copy, import and export PDF files For many Apple users, to have a multi-performance support tool is a great thing. But even if you have all the iPad, iPhone, iPhone Touch of multi-tools, you will certainly encounter a lot of trouble. For example, some people may be using your iPad, but do not know how to use it to read e-books, some people will want to convert PDF to ePub , or transfer ePub files from your computer to the iPad, But do not know what tools to use, how to do it, some people still want to burn, copy, backup ePub files, but do not know how to enable them to maintain a high quality, something like this is really too much.
But after you finish reading this article, you will not worry about these things, then you will know how to go for your iPad, iPhone, iPod Touch use professional tools to meet some of you common and uncommon problems. Now I will recommend you the best tools and the best way to do these things. You can use the powerful iPad Mate to rip your DVD, movie, music, and audio files to iPad, backup ePub files for your iPad and export ePub files from iPad, convert PDF files to ePub for you to watch eBooks like a PDF to ePub Converter . Also you can use the best iPad Manager for ePub to transfer your ePub files from your iPad and PC without losing them.
PowerPoint en PDF Convertisseur possède encore plusieurs fonctions, par exemple : fusionner des documents en un seul, ajouter des filigranes, adjuster la résolution ou la taille du fichier, protéger les documents PDF par mot de passe, etc et sa fonction de sécurité ne vous inquiète pas.En un mot, avec PowerPoint en PDF Convertisseur votre travail sera plus facile ! Télécharger gratuitement PowerPoint en PDF Convertisseur et expérimenter ce logiciel.
Crown Holder Jeanslaunched as a diffusion line in 1981. Internationally renowned and oozing with quality and style, Cheap Crown Holder Jeans takes contemporary fashion to another level.From elegant and glamorous backless ball dresses to casual basics, Crown Holders Jeans dominates the world of designer fashion for the modern man.Mens Diesel Jeans is an Italian design company known best for its clothing which is aimed mainly to the adult market, especially the jeans. The new season Cheap Diesel Jeansare definitely the must buy pair of jeans this year. They incorporate a Straight cut design which are very casual and would compliment a smooth shirt and a pair of your favourite shoes tremendously well.Dolce Gabbana Jeans can be categorized under designer or casual wears and people of all age are overtly crazy about them. Color, texture, cut or wash- everything blends enormously well with the new-age fashion trend as well as the comfort quotient of a working man or woman. Teenagers and youngsters too can die for the Dolce And Gabbana MensJeans.
Well, the IDE pointed out that they don’t refer to any instance data, so I made them static
Is white iphone 4 available right now? Cuz my friend told me he just got the white iphone 4 panel. But i haven’s seen it sold in my area. What’s wrong?
Personally, I’m a huge static hater. Mostly because of the difficulties they bring with dependencies. I much prefer class-methods a la Ruby, which are instance methods of a different object (the class).accounting services
We are the professional jeans manufacturer, jeans supplier, jeans factory, custom jeans.
fitness dvds
Thanks so much …
internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.
The other day, I was browsing some code with a team and we came across a cluster of static methods. I looked at them and asked whether they were used someplace else without an object reference. I could’ve done a find references in the IDE, but one of the team members had the answer: “No, they’re just used here.”
Mr Coates coach purses is the longest U.S. market popular with one of the most successful leather brand. Mr Coates coach purses store represents the most admirable American fashion innovative style and traditional skills . Mr Coates coach bags have durable quality and exquisite technology, Conspicuous Coach Heels in the female consumers have good reputation. Welcome to our shop Elegant Coach Purses
I attempted these beats by dr dre studio out in several genres thinking about which i listen to an eclectic mix Beats By Dr Dre. a washing cloth as well as the manual. Do not purchase any beats by dr dre solo purple products inside the internet unless you’re getting from an Authorized internet DealerBeats By Dre Just Solo. We are reliable provide good beats by dr dre pro black by reduced price.
I harmonise with your conclusions and will thirstily look forward to your coming updates. Just saying thanks will not just be sufficient, for the wonderful clarity in your writing. too
will not just be sufficient, for the wonderful clarity in your writing. toobeats by dre sale cheap beats by dre
Thank you for the wonderful article! I want to buy the Maggie Sottero dress. Many brides-to-be around me find it difficult to buy a Sottero Midgley dress. I think they will be very happy when they read your article.
This information is very interesting, I really enjoyed, thanks for sharing!
Wonderful Legal Assistant Job Description posts are display is visible in Director of Operations Job Description this blog that to using the great technology Accounting Job Description is visible in this blog Graphic Designer Job Description I am glad to see this info and providing the amazing info is display in this blog that to utilize the different services in this blog
Adidas predator cleats
Peep toe shoes used to be popular, now it regress popular again. Too heavy and dramatic square toe shoes may be nightmare for many people, but open a mouth in front, the effect will be greatly different. For women, it is a very good transition. It is very trendy, but unlike pointed toe shoe so eye-catching. In this year, a pair of delicate Christian Louboutin Peep Toe Pumps will be a good choice.
Christian Louboutin Madame Butterfly 150 Suede Pumps Red
Technical details of Christian Louboutin Madame Butterfly 150 Suede Pump Red:
Fashion, delicate, luxurious Christian louboutins shoes on sale, one of its series is Christian Louboutin Peep Toe Pumps, is urbanism collocation. This Christian louboutins shoes design makes people new and refreshing. Red soles shoes is personality, your charm will be wonderful performance.
Adidas predator cleats
with a 25 W you can listen to your favourite songs without any problem.
We need try to understand what it is and use it. that’s right, it is good to backup them.
This article is GREAT it can be EXCELLENT JOB and what a great tool!
I’ll bookmark your weblog and check again here frequently. I am quite sure I will learn many new stuff right here! Best of luck for the next!
drug forum Your blog is definitely worth a read if anyone comes across it. Im lucky I did because now Ive got a whole new view of this.
Es bueno ver esta información en tu mensaje, yo estaba buscando lo mismo, pero no había ningún recurso adecuado, gracias ahora tengo el enlace que yo estaba buscando para mi investigación.
This one is your one of the nice blog dude I like it very much so I want to keep in touch with your blogs therefore post more blogs and thank you dear for sharing with us such nice information.
Australia Beats By Dre Studio dr dre beats headphones beats studio beats pro beats solo hd pro headphones music Official store Monster Beats By Dre Pro
The Fact/Intention Gap 38 hoo,good article!!I like the post!91