Usually when some one ask a simple question when you will make variable or function as static, a simple answer comes to mind
Static fields will not be serialised.
In above example a developer can say i can't make it better performance unless you tell me what these functions are doing(... lines), but that's incorrect you can make it performant without knowing about what goes inside it.
When a function is made static as a developer you have made sure that binding will be done at compile time, but that's not 100% true either. It will depend on the caller.
What happens if you make doSomethingMore function as static
If you just make this function as static and no other change, you have done good job but you left the important part. You need to make sure when you call this function from doSomething it should be called like this
ClassWithStaticFunction.doSomethingMore();
- Variables : when i want to make single instance of that variable shared across all objects of this class. Good answer :)
- Functions : When i want to access a function of class without creating its object. Good answer :)
- Currently not talking about classes
Static fields will not be serialised.
Check Following code
Class ClassWithStaticFunction{ public void doSomething(){ ... doSomethingMore(); ... } private void doSomethingMore(){ ... ... } }
In above example a developer can say i can't make it better performance unless you tell me what these functions are doing(... lines), but that's incorrect you can make it performant without knowing about what goes inside it.
When a function is made static as a developer you have made sure that binding will be done at compile time, but that's not 100% true either. It will depend on the caller.
What happens if you make doSomethingMore function as static
If you just make this function as static and no other change, you have done good job but you left the important part. You need to make sure when you call this function from doSomething it should be called like this
ClassWithStaticFunction.doSomethingMore();
It is really a helpful blog to find some different source to add my knowledge.
ReplyDeleteSwitch to NBN