What do you mean by stateless in static method? - static-methods

Static method should not contain a state. What does 'state' means here ?
I have read that static method do not need to be instantiated, and do not use instance variables. So when can I use static methods? I have read that static methods are bad? Should I include it when coding?

State means storing some information, static methods are loaded when a class is loaded so there is no need of instance to call the static methods, you can call this methods using name of class, it's depend on condition when to use static methods. you can use static methods as single component of product just pass your parameters and get your work done.

As an answer here's an example:
public class SomeUtilityClass {
private static boolean state = false;
public static void callMeTwiceImBad() throws Exception {
if (state) {
throw new Exception("I remember my state from previous call!");
}
state = true;
}
public static int sum(int a, int b) {
return a + b;
}
}
By themselves they are neither bad nor good, they are just static.

Related

when assign static variable in a class, would that procedure run everytime we initialize new class?

I have the class
class CongNhan
{
public static decimal pr1= LoadFromDB(query1);
public static decimal pr2= LoadFromDB(query2);
public static int pr3= LoadFromBD(query3);
private string name;
public CongNhan()
{
name = "";
}
public CongNhan(string Name)
{
name = Name;
}
}
The question is how many times does 3 assigns to the static variables run. And if we new Class like: new CongNhan(), will it call three first assigns.
Because the static variables get value from Database so knowing how many times is it called is so much important to optimize and make it run faster.
Thank you!
AFAIK, static members of a class are initialized when app-domain with the class gets loaded into memory. So the three fields pr1, pr2, pr3 will be initialized once every time app-domain gets loaded. If you new up the class using new CongNhan(), those static fields will not be initialized again.

How to define an array in hadoop partitioner

I am new in hadoop and mapreduce programming and don't know what should i do. I want to define an array of int in hadoop partitioner. i want to feel in this array in main function and use its content in partitioner. I have tried to use IntWritable and array of it but none of them didn't work . I tried to use IntArrayWritable but again it didn't work. I will be pleased if some one help me. Thank you so much
public static IntWritable h = new IntWritable[1];
public static void main(String[] args) throws Exception {
h[0] = new IntWritable(1);
}
public static class CaderPartitioner extends Partitioner <Text,IntWritable> {
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
if you have limited number of values, you can do in the below way.
set the values on the configuration object like below in main method.
Configuration conf = new Configuration();
conf.setInt("key1", value1);
conf.setInt("key2", value2);
Then implement the Configurable interface for your Partitioner class and get the configuration object, then key/values from it inside your Partitioner
public class testPartitioner extends Partitioner<Text, IntWritable> implements Configurable{
Configuration config = null;
#Override
public int getPartition(Text arg0, IntWritable arg1, int arg2) {
//get your values based on the keys in the partitioner
int value = getConf().getInt("key");
//do stuff on value
return 0;
}
#Override
public Configuration getConf() {
// TODO Auto-generated method stub
return this.config;
}
#Override
public void setConf(Configuration configuration) {
this.config = configuration;
}
}
supporting link
https://cornercases.wordpress.com/2011/05/06/an-example-configurable-partitioner/
note if you have huge number of values in a file then better to find a way to get cache files from job object in Partitioner
Here's a refactored version of the partitioner. The main changes are:
Removed the main() which isnt needed, initialization should be done in the constructor
Removed static from the class and member variables
public class CaderPartitioner extends Partitioner<Text,IntWritable> {
private IntWritable[] h;
public CaderPartitioner() {
h = new IntWritable[1];
h[0] = new IntWritable(1);
}
#Override
public int getPartition(Text key, IntWritable value, int numReduceTasks) {
return h[0].get();
}
}
Notes:
h doesn't need to be a Writable, unless you have additional logic not included in the question.
It isn't clear what the h[] is for, are you going to configure it? In which case the partitioner will probably need to implement Configurable so you can use a Configurable object to set the array up in some way.

Interlocked.Increment not working with my Get variable name

I have WPF application and my work method play my files in different threads
This is my Global variable that update my UI:
public static int _totalFilesSent;
Now because i am implement INotifyPropertyChanged in my model i have also this:
public static int TotalFilesSent
{
get { return _totalFilesSent; }
set
{
_totalFilesSent = value;
OnStaticlPropertyChanged("TotalFilesSent");
}
}
(i didn't add the event function because this is not relevant here).
So every time i am update my Global variable this way:
Interlocked.Increment(ref _totalFilesSent );
Now because i need to update my UI with my INotifyPropertyChanged event i need to use TotalFilesSent instead of _totalFilesSent but in this way i got this compilation error:
A property, indexer or dynamic member access may not be passed as an
out or ref parameter.
What does it mean and how can i solved it ?
You may easily raise the StaticPropertyChanged event after calling Interlocked.Increment:
private static int _totalFilesSent;
public static int TotalFilesSent
{
get { return _totalFilesSent; }
}
public static void IncrementTotalFilesSent()
{
Interlocked.Increment(ref _totalFilesSent);
OnStaticPropertyChanged("TotalFilesSent");
}

Is it bad to set up singletons such that all methods are static methods?

I frequently setup singleton classes that are intended to be used by other programmers and I find that I'm not sure if there is a preferred way to setup access to methods in those classes. The two ways I've thought to do it are:
public class MyClass {
private static MyClass instance;
public static void DoStuff( ) {
instance.DoStuffInstance( );
}
private void DoStuffInstance( ) {
// Stuff happens here...
}
}
where the usage is: MyClass.DoStuff( );
or something more like this:
public class MyClass {
public static MyClass instance;
public void DoStuff( ) {
// Stuff happens here...
}
}
where the usage is: MyClass.instance.DoStuff( );
Personally, I tend to prefer the first option. I find that having MyClass.instance all over the place is both ugly and unintuitive to remember for less experienced programmers.
Is there any good reason to prefer one of these over the other? Opinions are fine. Just curious what others think.
I've never seen a Singleton implemented this way. A typical setup might be something like this:
public class MyClass {
private static final MyClass instance = null;
// Private to ensure that no other instances can be allocated.
private MyClass() {}
// Not thread safe!
public static MyClass getInstance() {
if( instance == null ) {
instance = new MyClass();
}
return instance;
}
public void DoStuff( ) {
// Stuff happens here...
}
}
This way all of the calls will be similar to instance.DoStuff(); and you will only need to define one method per "operation", rather than needing a static method and then the actual "instance" method that your first approach uses.
Also, the way you have it set up, it looks like you can call those static methods before the instance is actually initialized, which is a problem.

How to share an Array between all Classes in an application?

I want to share an Array which all classes can "get" and "change" data inside that array. Something like a Global array or Multi Access array. How this is possible with ActionScript 3.0 ?
There are a couple of ways to solve this. One is to use a global variable (as suggested in unkiwii's answer) but that's not a very common approach in ActionScript. More common approaches are:
Class variable (static variable)
Create a class called DataModel or similar, and define an array variable on that class as static:
public class DataModel {
public static var myArray : Array = [];
}
You can then access this from any part in your application using DataModel.myArray. This is rarely a great solution because (like global variables) there is no way for one part of your application to know when the content of the array is modified by another part of the application. This means that even if your data entry GUI adds an object to the array, your data list GUI will not know to show the new data, unless you implement some other way of telling it to redraw.
Singleton wrapping array
Another way is to create a class called ArraySingleton, which wraps the actual array and provides access methods to it, and an instance of which can be accessed using the very common singleton pattern of keeping the single instance in a static variable.
public class ArraySingleton {
private var _array : Array;
private static var _instance : ArraySingleton;
public static function get INSTANCE() : ArraySingleton {
if (!_instance)
_instance = new ArraySingleton();
return _instance;
}
public function ArraySingleton() {
_array = [];
}
public function get length() : uint {
return _array.length;
}
public function push(object : *) : void {
_array.push(object);
}
public function itemAt(idx : uint) : * {
return _array[idx];
}
}
This class wraps an array, and a single instance can be accessed through ArraySingleton.INSTANCE. This means that you can do:
var arr : ArraySingleton = ArraySingleton.INSTANCE;
arr.push('a');
arr.push('b');
trace(arr.length); // traces '2'
trace(arr.itemAt(0)); // trace 'a'
The great benefit of this is that you can dispatch events when items are added or when the array is modified in any other way, so that all parts of your application can be notified of such changes. You will likely want to expand on the example above by implementing more array-like interfaces, like pop(), shift(), unshift() et c.
Dependency injection
A common pattern in large-scale application development is called dependency injection, and basically means that by marking your class in some way (AS3 meta-data is often used) you can signal that the framework should "inject" a reference into that class. That way, the class doesn't need to care about where the reference is coming from, but the framework will make sure that it's there.
A very popular DI framework for AS3 is Robotlegs.
NOTE: I discourage the use of Global Variables!
But here is your answer
You can go to your default package and create a file with the same name of your global variable and set the global variable public:
//File: GlobalArray.as
package {
public var GlobalArray:Array = [];
}
And that's it! You have a global variable. You can acces from your code (from anywhere) like this:
function DoSomething() {
GlobalArray.push(new Object());
GlobalArray.pop();
for each (var object:* in GlobalArray) {
//...
}
}
As this question was linked recently I would add something also. I was proposed to use singleton ages ago and resigned on using it as soon as I realized how namespaces and references work and that having everything based on global variables is bad idea.
Aternative
Note this is just a showcase and I do not advice you to use such approach all over the place.
As for alternative to singleton you could have:
public class Global {
public static const myArray:Alternative = new Alternative();
}
and use it almost like singleton:
var ga:Alternative = Global.myArray;
ga.e.addEventListener(GDataEvent.NEW_DATA, onNewData);
ga.e.addEventListener(GDataEvent.DATA_CHANGE, onDataChange);
ga.push(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "ten");
trace(ga[5]); // 5
And your Alternative.as would look similar to singleton one:
package adnss.projects.tchqs
{
import flash.utils.Proxy;
import flash.utils.flash_proxy;
public class Alternative extends Proxy
{
private var _data:Array = [];
private var _events:AltEventDisp = new AltEventDisp();
private var _dispatching:Boolean = false;
public var blockCircularChange:Boolean = true;
public function Alternative() {}
override flash_proxy function getProperty(id:*):* {var i:int = id;
return _data[i += (i < 0) ? _data.length : 0];
//return _data[id]; //version without anal item access - var i:int could be removed.
}
override flash_proxy function setProperty(id:*, value:*):void { var i:int = id;
if (_dispatching) { throw new Error("You cannot set data while DATA_CHANGE event is dipatching"); return; }
i += (i < 0) ? _data.length : 0;
if (i > 9 ) { throw new Error ("You can override only first 10 items without using push."); return;}
_data[i] = value;
if (blockCircularChange) _dispatching = true;
_events.dispatchEvent(new GDataEvent(GDataEvent.DATA_CHANGE, i));
_dispatching = false;
}
public function push(...rest) {
var c:uint = -_data.length + _data.push.apply(null, rest);
_events.dispatchEvent(new GDataEvent(GDataEvent.NEW_DATA, _data.length - c, c));
}
public function get length():uint { return _data.length; }
public function get e():AltEventDisp { return _events; }
public function toString():String { return String(_data); }
}
}
import flash.events.EventDispatcher;
/**
* Dispatched after data at existing index is replaced.
* #eventType adnss.projects.tchqs.GDataEvent
*/
[Event(name = "dataChange", type = "adnss.projects.tchqs.GDataEvent")]
/**
* Dispatched after new data is pushed intwo array.
* #eventType adnss.projects.tchqs.GDataEvent
*/
[Event(name = "newData", type = "adnss.projects.tchqs.GDataEvent")]
class AltEventDisp extends EventDispatcher { }
The only difference form Singleton is that you can actually have multiple instances of this class so you can reuse it like this:
public class Global {
public static const myArray:Alternative = new Alternative();
public static const myArray2:Alternative = new Alternative();
}
to have two separated global arrays or even us it as instance variable at the same time.
Note
Wrapping array like this an using methods like myArray.get(x) or myArray[x] is obviously slower than accessing raw array (see all additional steps we are taking at setProperty).
public static const staticArray:Array = [1,2,3];
On the other hand you don't have any control over this. And the content of the array can be changed form anywhere.
Caution about events
I would have to add that if you want to involve events in accessing data that way you should be careful. As with every sharp blade it's easy to get cut.
For example consider what happens when you do this this:
private function onDataChange(e:GDataEvent):void {
trace("dataChanged at:", e.id, "to", Global.myArray[e.id]);
Global.myArray[e.id]++;
trace("new onDataChange is called before function exits");
}
The function is called after data in array was changed and inside that function you changing the data again. Basically it's similar to doing something like this:
function f(x:Number) {
f(++x);
}
You can see what happens in such case if you toggle myArray.blockCircularChange. Sometimes you would intentionally want to have such recursion but it is likely that you will do it "by accident". Unfortunately flash will suddenly stop such events dispatching without even telling you why and this could be confusing.
Download full example here
Why using global variables is bad in most scenarios?
I guess there is many info about that all over the internet but to be complete I will add simple example.
Consider you have in your app some view where you display some text, or graphics, or most likely game content. Say you have chess game. Mayby you have separated logic and graphics in two classes but you want both to operate on the same pawns. So you create your Global.pawns variable and use that in both Grahpics and Logic class.
Everything is randy-dandy and works flawlessly. Now You come with the great idea - add option for user to play two matches at once or even more. All you have to do is to create another instance of your match... right?
Well you are doomed at this point because, every single instance of your class will use the same Global.pawns array. You not only have this variable global but also you have limited yourself to use only single instance of each class that use this variable :/
So before you use any global variables, just think twice if the thing you want to store in it is really global and universal across your entire app.

Resources