• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

I just want to be static: is that so wrong?

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok, the odds that this reference to a 1980 or 90's SNL skit by Jon Lovitz doing his impression of Harvey Fierstien will be completely lost on 90% of the readers of this now and certainly will be COMPLETELY obscure in another 5 to 10 years are pretty high.... but I thought it might garner a laugh or two.

As for the serious nature of the question:
I started getting formal programming training at the dawn of the OO revolution in the mid-80s. At that time I was a zealot that thought everything should be an object. You should always be instantiating an object and storing it's state and calling it's methods, etc. etc. etc..

Recently though, particularly as I start doing more Web application programming, I think I begin to see that just because you have a hammer the world is NOT a nail. (honestly, at my age I figured that out a LONG time ago... but just to make a point...)

I just did a slightly bigger than trivial web application that had a traditional MVC design with a SQL back end, Servlet/JSP controller and Javascript JQuery view.... and I decided to do EVERYTHING as STATIC methods. I create a lot of different classes. Basically a class for each C.R.U.D. function required for each "Entity Type" in my system. So for example there's a GetCustomer class. There's a UpdateCustomer class, there's a DeleteCustomer class, there's a FindCustomer class etc. etc. (debated doing an Entity_CRUD class with methods for each thing... but found code management and things was actually EASIER of they were each separate files all together. This way, each could also be a seperate Servlet performing a designated function. also it allowed me to get one whole FILE working, tested, validated, etc. and then move on to the next). Each of these classes have sets of static methods that perform the functions that basically match the class names, with different possible paramaters, for example, one method might take a CUSTOMER OBJECT as a parameter, another might take a JSON string. One might take a Servlet Context parameter and retrieve a data source object from a pool in the context and another might take a Datasource Parameter directly, etc..

In all cases, the classes have STRICTLY static methods and no class level variables of any kind. All the methods use strictly the parameters passed to them and/or the local variables declared in them. So, as my possibly naive understanding of Java would interpret this, all my methods basically operate completely on the stack within single threads so I don't "think" there's any chance of side effects or parallel processing issues.

As I understand it, this means that each of my methods do their things when their asked without needing to know about or be able to interfere with anything else that's going on anywhere, then everything about them goes away as it all gets popped off the stack.

This all seemed to be quite consistent and compatible with the stateless nature of standard Web application processing, and just generally seemed "neat and tidy" to me.

After implementing this solution for a web app, I started taking the same approach for a lot of other "little programs" that I have been writing that do things like analyze directory structures and the files in them to extract information about program source code or to do file manipulations (basically the kinds of stuff Unix and linux focus traditionally write BIN and BASH scripts for).

All this has worked out so well for me that I'm become a real fan of "ALL STATIC, ALL THE TIME" programming for a lot of scenarios (obviously this is an over statement.... I'd didn't just get a new hammer, I understand the value of a "tool chest" with lots of tools, but boy, an awful lot of place... static seems to work better than non static for me these days).

BUT.... Every where I look in the internet and in a lot of books, I find warnings, cautions and even out right condemnations of the use of STATIC as something at least less than desirable or professional and frequently as evil as.... I don't know what.

So....
Is there some big piece of the puzzle that I'm missing? Are Statics' Really evil? Am I completely nuts for thinking that actually TRYING to make some programs or systems of programs completely static is REALLY DUMB?

Just curious what real experts with LOTs of years of Java programming might think about this.

Thanks.
 
Ranch Hand
Posts: 426
Eclipse IDE Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Using static is a lazy way of coding. If you need to persist some variables, you should think about Singleton pattern. If you depend on static, your code will not always be thread-safe or performant.
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why aren't they tread safe as long as now class level variables are being used?
Persist some variable? If you're talking about the SQL back end? If so, that stuff is still effectively "stateless", you read a record to be displayed to the user... you send updates to the records in the database... but I'm not storing data that's then references with in a continuing processing or anything that needs to be "persisted?

What's the performance hit over Singleton? Is it that each time the JVM has to reload the entire class code, as apposed to "spinning up" an instance once, then just queuing up requests to it by other processes? Or is there some other reason it causes performance problems?

As for "lazy", the fact is I sometimes have to work pretty hard to make sure I write static code that works everywhere I need it to, doesn't require an excessive amounts of parameters, CAN'T have nay side effects, etc.. So, if I'm being lazy... them I'm REALLY stupid because I sometimes have to work hard to be that lazy.

Thanks for the feedback. I'm looking forward to learning more about all this.
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oh, I just remembered one other reason I "thought" static was a particularly good idea in the Servlet world... I was thinking about scenarios where, for load balancing or something, there might be multiple instances of the Java Application server running... in that scenario, I didn't see a good way to implement the "singleton" pattern since it would require a whole extra layer of architecture to try to implement a "singleton" where there are multiple JVMs, running on multiple servers that by default don't know anything about each other... So, in this scenario, my logic was that if everything is Static and I've done all the work necessary to make sure they work "correctly" as static methods, then it "should" be completely safe for these methods to be called from anywhere any time... they "can't" step on each other.... or at least that was my interpretation of the situation.

As I said.... I'm LOOKING FOR the errors in my ways so please don't misinterpret my response as being "defensive".... I find vigorous debate the best way to get to the truth and that's want I'm really looking for here. Show me where I'm wrong... please.
 
Roger Sterling
Ranch Hand
Posts: 426
Eclipse IDE Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Oy vey - all for good debate. And you are right, we will both learn a lot !

In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program.. So if you think about more modern ways to persist variables throughout the lifetime of a long-running program (for example an Enterprise Service Bus never exits), there are several ways to accomplish this. Like any choice in software development, there may be twelve ways to do something and the developer's choice is the only way that matters.

The Singleton pattern ( http://en.wikipedia.org/wiki/Singleton_pattern ) is a great tool to use to do different things, one of them to track tallies of various things, for example MXBeans throughout the lifetime of a long running program. What good are static variables if you cannot read them on-the-fly ?
 
Bartender
Posts: 2407
36
Scala Python Oracle Postgres Database Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, I leave the "static or not" discussion to people who know a lot more about Java than I do (which is most people!). But it kind of sounds like you are heading towards seeing many of your methods as functions, e.g. to avoid issues around mutable state and concurrency. Maybe it's time to explore functional programming with a language like Scala as an alternative? That way you can build pure functional code where you want, and still have stateful objects when you need them. Just a thought.
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hum.... OK, looks like I have misunderstanding the static thing...
So... what does that mean for static methods of a class where an instance of the class never gets instantiated?
So... the class should load into memory the first time a call is made to either instantiate it or a call is made to one of it's static methods....
Then, that loaded code (and any static variables in the class if any) will stay loaded for the life of the "program".... Hum... so if my class implements a Servelet... then... what's the "program" who's life it persists through? Is it the Web App? Is it the Request? Is it just the duration of the call to the given method?

So... if I assume methods are functionally "variables", the static methods exist for the life of the program... So... what happens to the local variables in the methods? are they functionally static variables themselves? If there are two calls to a single static method at the same time on different threads.... is there just one set of local variables between the two calls and subsequently a HUGE possibility for concurrency problems? Or do instances of all the local variables get created and pushed onto the static when the methods are called so each call, on each thread has it's own variables?

IF, the static class gets loaded once the first time it is referenced.... AND IF method local variables and parameters are all created and pushed onto the static separately for each unique call to a given method....
then I think that's really the ideal situation (so obviously I've got something wrong here) because I only take the performance hit once to load the class, but I still get complete isolation of the code execution.

By design, I do NOT want any of these static methods to effect anything for which I care about the state of the data after the method execution EXCEPT in the case where the method either passes something back as a return OR I intentionally passed a reference to an object in that was intended to be modified by the method. So, IF there's any statefullness needed, it's all dealt with OUTSIDE of and effectively independent of the class the method is part of.
 
Sheriff
Posts: 67754
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was coming here to post pretty much what Chris posted: you are using a circular saw to plane boards. If you want to write functional programming, use a functional language. You are using the wrong tools.
 
Roger Sterling
Ranch Hand
Posts: 426
Eclipse IDE Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is very possible I'm not hearing what you say because we have no example.

If you ask me to maintain a static variable in one of my programs, I could have a counter. Every time a message comes in, I increment the counter. The problem is : simply declaring that as static does not enforce thread safety. I could have five messages come in and after all five hit the counter, the counter could erroneously read 2 if no mutual exclusion mechanism is enforced.

Or take the bank account withdrawal example. If my balance is $200 and I post two withdrawals each for $180, I will have the wrong result if both withdrawal posts happen at the same time before either can deduct their transaction.


Again I ask you : if you cannot on-the-fly read the values from outside the program , whats the point of making them long-living ?
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I definitely hear what Chris and Bear are saying... I did recognize that I'm basically writing procedural code and "forcing" Java to behave like a procedural language.
Guess I always have to fight the system. In the early 90's I was using pointers to a "this" variable and lots of pointers to functions in C structures because my colleague at the time insisted on NOT using a C++ compiler but I wanted to write OO code, so I had to do it the hard way.

Anyway, I don't know Scala and I'm getting too old to learn new languages. Also, there are times when the standard design models for Java DO work for what I want to do.

SO... to extend the tool analogy, I own a table saw... I don't own a Chop saw... there's lots of times that the table saw is EXACTLY the right tool and there frequently times when a chops saw would be SO much better, BUT I can get the job of the chop saw down with my table saw much of the time.

I definitely appreciate the recommendation that maybe another language would to the things I'm trying to better. But what I'm looking for right now is any reasons I it is just completely wrong that I should try to use Java the way I have. I'm looking for the "Oh CRAP! I didn't realize THAT was going to happen!" kind of thing, because all the other discussions I've seen "imply" that there is or are such major pitfalls to using statics with Java but I've not seen any clearly definitive examples/explanations of what those actually are.

(This is fun :-) Thanks to all for participating! Gotta love the internet... I'd have to search pretty darn hard to find people knowledgeable enough and interested enough to have this kind of discussion any other way!)
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Chris...
Is Scala my holy grail!
I just scanned the first few paragraphs from (http://www.scala-lang.org/what-is-scala.html)!
WOW! Sounds like the kind of thing I've been looking for recently. And It's Java compatible. It looks VERY interesting. I'll have to try to do some reading on that.

Do you happen to know if there's support for in the NetBeans IDE? I can't deny the productivity benefits of a GOOD IDE support for a language with immediate error detection, code complete, refactoring support.... If I can't find an environment that has all that for a language these days, I have that much more trouble justifying a switch to a given language.

 
Roger Sterling
Ranch Hand
Posts: 426
Eclipse IDE Fedora Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
http://scala-ide.org/

Scala for Eclipse.

NetBeans IDE should have been based on Eclipse, but unfortunately is not.

 
chris webster
Bartender
Posts: 2407
36
Scala Python Oracle Postgres Database Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tom Malia wrote:Chris...
Is Scala my holy grail!


Dunno, but it sounds like functional programming could offer you a lot of what you seem to be looking for, and Scala is an interesting compromise between OO and FP. Scala In Action may be a good place to start learning Scala.

Scala has its critics - sometimes with good reason (it often seems like it's basically a type system with a language bolted on, and it's moving fast so there have been version compatibility issues) - but it is being used by big companies to do serious real-world computing (LinkedIn, Twitter etc) around big data - there are some nice libraries for Hadoop and Spark for example. It's also been adopted by real-world companies with regular human IT teams (i.e. not just the Vulcan gurus who inhabit the big tech giants) e.g. the UK Guardian newspaper switched the application behind their websites from Java to Scala a couple of years ago and seems to be a keen cheerleader for Scala based on that experience. The Scala Play! framework for web applications may interest you, although it's not fully Java EE compatible.

If Scala isn't right for you, there are other functional programming languages on the JVM e.g. Clojure (Lisp for Javaland), although the learning curve may feel more challenging at the outset. It's worth finding out more about what functional programming is all about e.g. there's some stuff on our FP forum that may help. Just as with OO, you'll find it much easier if you have some idea of what the mental model is supposed to be before you start hacking out code. Check out Neal Ford's talk on Functional Thinking for a quick introduction to why FP may be the Next Big Thing.

As Roger says, the Scala IDE is Eclipse-based and seems to be the most current of the IDE plugins for Scala, but you can code Scala with Netbeans and people also like IntelliJ for a lot of languages, presumably including Scala. IDEs are all fairly similar, so I wouldn't worry too much about learning a new IDE: learning FP and Scala is going to be more of a challenge.

But in a good way...
 
Rancher
Posts: 2759
32
Eclipse IDE Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, it sounds like functional programming is what you need... however there are some things that you want to keep in mind, even when you go functional. There's no point in using OOP or functional languages if you don;t understand why OOP/functional programming was built. It's going to be hard for me to not sound preachy in this post, so please take the rest of this post in the spirit of goodwill that it is being offerred.

The main reason you don;t want to do everything static all the time is because
a) you lose the buildy-blockiness


A big reason why OOP was a big leap over procedural languages is because of it's buildy-blockiness. You think of components as Lego pieces.. and you build the ability to piece them together. If one piece needs to change, you throw the piece away and put it in another without touching the piece that doesn't need to change. You literally cannot do that with static functionas/procedural languages. Why we use OOP is because we know we are going to be constantly changing the programs we write.. and we want them to be easy to change, not just work right.

After all, if you had a guarantee that you never had to touch your code again.. why would you even use static functions? Just frigging put everything in your Servlet.process method.. right? That's how I did it when I programmed in Basic on mah ZX Spectrum. Just write the whole program in a single main method. Worked for me!! The program works.. Me and my brother made clones of 2 screens of Mario Bros. Didn't even need to use for loops. GOTOs everywhere. The whole reason why we went from GOTO loops to for and while loops is because they help us avoid spaghetti GoTOs which helps us maintain the program. The whole reason we go from that to building procedures is to make it easy to maintain the program. Yes, may people don;t understand this and end up doing OOP the wrong way.

It;s a series of lessons that people have learnt over the year that has led to OOP. The people who came up with OOP were tired of the headaches caused by having to change and maintain procedural code. And yes, we are continuing the same spirit forward as we move into a functional world.

Think what would happen if Java classes themselves weren't built as building blocks . Let's say Java was ALL STATIC ALL THE TIME. And it had a static method for reading from a file and a static method for reading from the network. Now, you wrote this neat little program that reads a file from the disk parses it and cures cancer. Tommorrow, someone comes to you and tells you.. hey I got this file on a server, download it and cure cancer.. and you tell them no.. can;t cure your cancer until you send me the file. How effed up is that?

b) there is no way to mock the function

Again, this goes toward the buildy-blockiness of OOP. You need to be able to test. and when you are thinking of building blocks, you need to be able to test building blocks on their own.. except that some building blocks inherently need other blocks. Let's say you were testing your service layer.. well your service layer needs a data access layer to work. So, how do you test it in isolation. Well you replace the data access layer with a mock data access layer and test the service layer in isolation

c) there is no way to proxy the function, which means you cannot use aspects
I won;t delve into this in too much detail because it;s a huge subject. I encourage you to look at AOP and what advantages it gives. Primarily, it allows you to separate boiler plate code from "real" code, which again helps maintainability. Aspects will be impossible without proxying.. and proxying would be impossible with static functions

Yes, so again, probably fuctional programming is what suits your style. However, even if you do adopt functional programming, you stilol need to remember the lessons that people have learnt which led to OOP.. and similar lessons that have led to functional programming. You need to make sure that
a) you don;t lose buildy-blockiness nature of your application
Functional languages essentially make each function a building block. So, when you design your functions you need to make the easily replaceable. Make your functions self-contained. make them so that multiple functions don;t go trampling over each other. Make them do one thing and do it well. Tight cohesion.. low coupling

b) you need to make sure you test your code in isolation
the function as a variable nature of functional programming helps you there too. You could plugin mock functions into other functions.. and you can test your functions in isolation. However, you need to be thinking about testing when you build your functions as you are building it. You cannot have testing be something you do after you are done programming.

c) you need to make sure you seperate concerns.

Let's say you have 2 functions; one that saves widgets and another that saves thingamajigs.. do you do this (all pseudo code here



or do you do this



Which one is easier to maintain and read?
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
OK, I'm learning a lot. Definitely going to be doing some more reading about functional programming theory.

The other thing I'm hearing is lots of discussion about pros and cons of particular programming paradigms and design philosophies.

What I've still not seen or heard in this discussion is any glaring problem with using a lot of "static" methods in java programming.

Fun food for thought so far and also so far no reason for me to freak out that programs I've written recently may be some kind of ticking time bombs waiting to bite me in the but.

So... far.... so good.
 
Marshal
Posts: 5950
407
IntelliJ IDE Python TypeScript Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jayesh touched on this, but I'm interested to hear how you went about writing Unit Tests for you statics only application.

For example, how did you test in isolation a 'function' that had side effects? By that I mean a static method that calls on to another / multiple static method(s). Taken to the extreme, how did you write tests for your front end API that would not require you to have the whole stack present? Database and test data and all?
 
Tom Malia
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Tim,
The project that first prompted this experiment in statics for me, as I said, was not "completely" trivial.... but it was darn close. No one was paying me for it. It was not going to have a very long life at all (needed to work for about a week), only effected at most a couple hundred people in a very minor way....
So.... "unit testing?!" "we don't need no unit testing?!"

However, since each of my functions did one thing and one thing only and didn't rely on anything outside of their local variables and/or the parameters passed in, I was able to test each of them completely independent of any other part of the over all project. So that "blockiness" that was discussed earlier worked out quite well for me.... testing each function was really easy. Once that's done, making sure they played well together when I stacked them was relatively trivial as well.

returning to the tool analogy, my current thinking is that my "staticy" approach, which as others have so pointed out is REALLY a "functional" approach, seems to be a great fit in specific situations. One such situation I believe is problem domains that by nature tend to be stateless.

I've seem the "it's not mockable" argument quite a bit around the web.... I get that. It seems to me that the significance of this argument against static would depend a lot on how completely and efficiently you can test a static function in isolation. Seems to me that, if you can guarantee that a function does what it's defined to do and will always do what it's designed to do, then when, where and why would I ever need to "mock" it in a larger system?

I would say though that, so far this issue with not being able to easily "swap out" statics for something completely trivial without touching the code that actually calls it (If this is "not" the basic idea behind "mocking", I apologies.) for testing purposes is the only fundamental flaw I'm seeing/hearing with "static".

 
author
Posts: 23959
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Tom Malia wrote:
The project that first prompted this experiment in statics for me, as I said, was not "completely" trivial.... but it was darn close. No one was paying me for it. It was not going to have a very long life at all (needed to work for about a week), only effected at most a couple hundred people in a very minor way....
So.... "unit testing?!" "we don't need no unit testing?!"



I actually don't have much of an issue with this argument. It is a "throwaway" program. It will serve a temporary purpose, and that's it. As such, you can do whatever you like. Heck, you can even argue that if you didn't even mention it, then no one would even notice it.

On the other hand, what is wrong with following "best practices" in regards to coding -- even if those practices are only best for larger programs, that are worked on by many developers, and goes through the rigors of release engineering.

It may take a few minutes longer, and with enough experience (and muscle memory) doesn't it only take seconds longer?

Henry
 
reply
    Bookmark Topic Watch Topic
  • New Topic