/    Sign up×
Community /Pin to ProfileBookmark

Staic vs Instance methods

I recently wrote a class that removes punctuation from sentences.
I was wondering if it was better to make the one method that it has a static or instance method.

Thanks in advance

to post a comment
Java

3 Comments(s)

Copy linkTweet thisAlerts:
@WaylanderNov 15.2005 — It depends really, when im working in a web app and I will often find the need for small tools like what you have mentioned.

I would suggest creating a single a static tool class with static methods that you pass variables to, that then process and return the same altered variable.

The problem you have when doing this is making the class itself thread safe, basically (Im pretty sure) that if that the class itself has no variables of its own it will be thread safe, you get problems when two processing threads try to write to the same variable at the same time, if its a class variable its global and the two threads are trying to write to the same memory address, but if they try to write to the "same" variable within the method its not actually the same variable because they exist within the processing stream itself or whatever, so define all needed variables within the method itself and you will be fine.
Copy linkTweet thisAlerts:
@OakNov 15.2005 — As Waylander said, if your program has multiple threads then instance variables will pose a problem. You can create thread safe code using various techniques such as Synchronized methods and variable but it sounds like that is beyond the scope of your issue so just make it a static call and ensure that all the variables that are altered in that call are within that method call, not the class itself.

Its pretty trivial in your situation but the static will make life easier, as you wont have to instantiate an instance of the class to make the call. ?
Copy linkTweet thisAlerts:
@JjavaJauthorNov 17.2005 — thanks everybody
×

Success!

Help @JjavaJ spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...