The method that will be called only within the class, still the method should be static? - static-methods

I understand the benefits of using the static method, invoking functionality without the instance of the class and hence saves memory.
But what about if the method will be called only within the class? still, is there any benefit using the static method?
Class Test {
sayHelloWorld() {
print "Hello" + getWorld()
}
// this method never will be called out side of the class
// IDE say 'this method can be static'
private getWorld() {
return "world"
}
}

Your concern as a programmer in 2017 should not be about saving memory, but more about placing your abstractions in the right place. If you are using an Object-oriented language, using static methods is a smell of bad design IMHO. It allows C-style programming with global variables and functions, and make the code generally less testable.

Related

Are static methods close to pure methods?

Going by the requirements of pure method(a method which has no side effects on outside world), I have found most of the times static methods meeting this requirement. We can't access instance variables in static method, so it greatly reduces chances of side effects. Then mostly we use static methods to do some computations based on input values and just return new value...inputs are rarely mutated.
So can it be said that static methods are good enough replacement of pure methods.
No. Just being static does not make a function pure.
In purely functional programming the outcome of the function should depend only on their arguments, regardless of global state. Static functions can easily access and modify global state.
Any useful pure function must return a value. Static functions can and often are declared to be void, which makes no sense for a pure function.
Pure functions should produce the same result for the same input each time. Any static function using a static counter could break that rule.
In Java , for example, streams objects are functional in nature. Their functions, such as filter() , are not static, but maintain the immutability of the stream data by producing a new stream instead of modifying the original stream object.
That being said, its easier for static functions to have no side effects, since they have 1 less thing to worry about modifying - their own instance state. Instance functions need to refrain from modifying both their own instance state, and global static state.

Accessing an array without static references in another class (OOP)

I'm new to object-oriented-programming, and I have set a strict goal for myself for my current project which is not using static variables. In the process I will try to learn about OOP.
I'm using the Haxe language and it's one of the best languages I've ever seen.
I know a bit about C pointers, and that pointers only store the address of a variable so its pretty much the same variable, just taking up less space (especially for large variables).
Now back to the present, I want to have pointer references to an array of objects of one class because
I want these objects to interact with each other,
and I don't want to have any static references,
and I don't want to have every object holding a copy of that array.
How should I go along accessing this array?
Or is there another OOP design pattern or something?
Please correct me if I got something wrong.
There are many questions in this brief.
You can just pass along a context along all your variables, it will be passed by pointer
class Context{
var level:Level=null;
var enemies:Array<Enemy>=[];
}
class Enemy{
var ctx:Context;
function new(ctx){ this.ctx=ctx; }
}
class Main{
static function main(){
new Game(new Context());
}
}
and in game, pass along the context to everyone :
new Enemy(ctx);
etc...
Frankly it is often easier to use static for contexts, like
class Context{
static var level:Level;
}
But that's up to you :)
As a side note, all non primitives are pointers to structure (ex arrays) just like java.

Which of these functions is more testable in C?

I write code in C. I have been striving to write more testable code but I am a little
confused on deciding between writing pure functions that are really good for testing
but require smaller functions and hurt readability in my opinion and writing functions
that do modify some internal state.
For example (all state variables are declared static and hence are "private" to my module):
Which of this is more testable in your opinion:
int outer_API_bar()
{
// Modify internal state
internal_foo()
}
int internal_foo()
{
// Do stuff
if (internal_state_variable)
{
// Do some more stuff
internal_state_variable = false;
}
}
OR
int outer_API_bar()
{
// Modify internal state
internal_foo(internal_state_variable)
// This could be another function if repeated many
// times in the module
if (internal_state_variable)
{
internal_state_variable = false;
}
}
int internal_foo(bool arg)
{
// Do stuff
if (arg)
{
// Do some more stuff
}
}
Although second implementation is more testable wrt to internal_foo as it has no sideeffects but it makes bar uglier and requires smaller functions that make it hard for the reader to even follow small snippets as he has to constantly shift attention to different functions.
Which one do you think is better ? Compare this to writing OOPS code, the private functions most of the time use internal state and are not pure. Testing is done by setting up internal state on a mock object instance and testing the private function. I am getting a little confused on whether to use or whether to pass in internal state to private functions for the sake of "testability"
Whenever writing automated tests, ideally we want to focus on testing the specification of that unit of code, not the implementation (otherwise we create fragile tests that will break whenever we modify the implementation). Therefore, what happens internally in the object should not be of concern to the test.
For this example, I would look to build a test that:
Executes the test by calling outer_API_bar.
Asserts that the correct behavior of the call using other publicly accessible functions and/or state (there must be some way of doing this, as if the only side effect of calling outer_API_bar was internal to this unit of code, then calling this function could not impact your wider application in any way, and essentially be useless).
This way, you are able to keep the fact that you use functions like internal_foo, and variables like internal_state_variable as implementation details, which you can freely change when refactoring your code (i.e. to make it more readable) without having to change your tests.
NOTE: This suggestion is based on my own personal preference for only testing public functions, and not private ones. You will find much debate on this topic where some people pose good arguments for testing private functions being a valid thing to do.
To answer your question very specifically pure functions are waaaaay more 'testable' than any other kind of abstraction. The more pure functions you can include, the more testable your code would be. As you rightly mention, this can come at the cost of readability, and I am sure there are other trade offs to consider. My suggestion would be to aim for more pure functions and look for other techniques that would allow you to compensate on the readability side of things.
Both snippets are testable via mocks. The second one, however, has the advantage that you can also check the argument of internal_foo(bool arg) for an expected value of true or false when the mock for internal_foo() is invoked. In my opinion, that would make for a more meaningful test.
Depending on the rest of the code that we don't know, testing without mocks may be more difficult.

Supporting multiple instances of a plugin DLL with global data

Context: I converted a legacy standalone engine into a plugin component for a composition tool. Technically, this means that I compiled the engine code base to a C DLL which I invoke from a .NET wrapper using P/Invoke; the wrapper implements an interface defined by the composition tool. This works quite well, but now I receive the request to load multiple instances of the engine, for different projects. Since the engine keeps the project data in a set of global variables, and since the DLL with the engine code base is loaded only once, loading multiple projects means that the project data is overwritten.
I can see a number of solutions, but they all have some disadvantages:
You can create multiple DLLs with the same code, which are seen as different DLLs by Windows, so their code is not shared. Probably this already works if you have multiple copies of the engine DLL with different names. However, the engine is invoked from the wrapper using DllImport attributes and I think the name of the engine DLL needs to be known when compiling the wrapper. Obviously, if I have to compile different versions of the wrapper for each project, this is quite cumbersome.
The engine could run as a separate process. This means that the wrapper would launch a separate process for the engine when it loads a project, and it would use some form of IPC to communicate with this process. While this is a relatively clean solution, it requires some effort to get working, I don't now which IPC technology would be best to set-up this kind of construction. There may also be a significant overhead of the communication: the engine needs to frequently exchange arrays of floating-point numbers.
The engine could be adapted to support multiple projects. This means that the global variables should be put into a project structure, and every reference to the globals should be converted to a corresponding reference that is relative to a particular project. There are about 20-30 global variables, but as you can imagine, these global variables are referenced from all over the code base, so this conversion would need to be done in some automatic manner. A related problem is that you should be able to reference the "current" project structure in all places, but passing this along as an extra argument in each and every function signature is also cumbersome. Does there exist a technique (in C) to consider the current call stack and find the nearest enclosing instance of a relevant data value there?
Can the stackoverflow community give some advice on these (or other) solutions?
Put the whole darn thing inside a C++ class, then references to variables will automatically find the instance variable.
You can make a global pointer to the active instance. This should probably be thread-local (see __declspec(thread)).
Add extern "C" wrapper functions that delegate to the corresponding member function on the active instance. Provide functions to create new instance, teardown existing instance, and set the active instance.
OpenGL uses this paradigm to great effect (see wglMakeCurrent), finding its state data without actually having to pass a state pointer to every function.
Although I received a lot of answers that suggested to go for solution 3, and although I agree it's a better solution conceptually, I think there was no way to realize that solution practically and reliably under my constraints.
Instead, what I actually implemented was a variation of solution #1. Although the DLL name in DLLImport needs to be a compile-time constant, this question explains how to do it dynamically.
If my code before looked like this:
using System.Runtime.InteropServices;
class DotNetAccess {
[DllImport("mylib.dll", EntryPoint="GetVersion")]
private static extern int _getVersion();
public int GetVersion()
{
return _getVersion();
//May include error handling
}
}
It now looks like this:
using System.IO;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Assembly = System.Reflection.Assembly;
class DotNetAccess: IDisposable {
[DllImport("kernel32.dll", EntryPoint="LoadLibrary", SetLastError=true)]
private static extern IntPtr _loadLibrary(string name);
[DllImport("kernel32.dll", EntryPoint = "FreeLibrary", SetLastError = true)]
private static extern bool _freeLibrary(IntPtr hModule);
[DllImport("kernel32.dll", EntryPoint="GetProcAddress", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)]
private static extern IntPtr _getProcAddress(IntPtr hModule, string name);
private static IntPtr LoadLibrary(string name)
{
IntPtr dllHandle = _loadLibrary(name);
if (dllHandle == IntPtr.Zero)
throw new Win32Exception();
return dllHandle;
}
private static void FreeLibrary(IntPtr hModule)
{
if (!_freeLibrary(hModule))
throw new Win32Exception();
}
private static D GetProcEntryDelegate<D>(IntPtr hModule, string name)
where D: class
{
IntPtr addr = _getProcAddress(hModule, name);
if (addr == IntPtr.Zero)
throw new Win32Exception();
return Marshal.GetDelegateForFunctionPointer(addr, typeof(D)) as D;
}
private string dllPath;
private IntPtr dllHandle;
public DotNetAccess()
{
string dllDir = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location);
string origDllPath = Path.Combine(dllDir, "mylib.dll");
if (!File.Exists(origDllPath))
throw new Exception("MyLib DLL not found");
string myDllPath = Path.Combine(dllDir, String.Format("mylib-{0}.dll", GetHashCode()));
File.Copy(origDllPath, myDllPath);
dllPath = myDllPath;
dllHandle = LoadLibrary(dllPath);
_getVersion = GetProcEntryDelegate<_getVersionDelegate>(dllHandle, "GetVersion");
}
public void Dispose()
{
if (dllHandle != IntPtr.Zero)
{
FreeLibrary(dllHandle);
dllHandle = IntPtr.Zero;
}
if (dllPath != null)
{
File.Delete(dllPath);
dllPath = null;
}
}
private delegate int _getVersionDelegate();
private readonly _getVersionDelegate _getVersion;
public int GetVersion()
{
return _getVersion();
//May include error handling
}
}
Phew.
This may seem extremely complex if you see the two versions next to each other, but once you've set up the infrastructure, it is a very systematic change. And more importantly, it localizes the modification in my DotNetAccess layer, which means that I don't have to do modifications scattered all over a very large code base that is not my own.
In my opinion, solution 3 is the way to go.
The disadvantage that you have to touch every call to the DLL should apply to the other solutions, too... without the lack of scalability and uglyness of the multiple-DLL approach and the unnecessary overhead of IPC.
Solution 3 IS the way to go.
Imagine, that current object oriented programming languages work similar to your 3rd solution, but only implicitly pass the pointer to the structure that contains the data of "this".
Passing around "some kind of context thing" is not cumbersome, but it is just how things work! ;-)
Use approach #3. Since the code is in C, an easy way to deal with the globals that are spread everywhere is to define a macro for each global that has the same name as the global variable, but the macro expands to something like getSession()->theGlobal where getSession() returns a pinter to a "session-specific" structure that holds all the data for your globals. getSession() would fish the right data structure out of a global map of data structures somehow, perhaps using thread-local storage, or based on process ID, etc.
Actually solution 3 is easier than it sounds. All other solutions are kind of patch and will break with time.
Create a .net class which will encapsulate all access to the legacy code. Make it IDisposable.
Change all the global variables to reside in a class named 'Context'
Have all the C++ interfaces get the context object and pass it around as the first argument. This is probably the longest stage and you can avoid it using the "thread-local-storage" method suggested by someone else, but I would vote against that solution: if your library has any working threads which it runs, the "thread-local-storage" solution will break. Just add the context object where it is needed.
Use the context object to access all global data.
Have the context object created from .net ctor (by p/invoking a new create_context function) and deleted by the .net Dispose() method.
Enjoy.
Some thoughts on suggested solution #2 (and a bit on #1 and #3).
Some sort of IPC layer might introduce lagging. It depends on the actual engine how bad that is. If the engine is a rendering engine and it is called, say, 60 times a second the overhead might be too much. But, if not, a named pipe might be quick enough and easy to create using WCF.
Are you entirely sure you will need EXACTLY the same engine multiple times or are you in danger of changing requirements that might lead to a scenario that forces your toward loading multiple versions at the same time? If so, option #2 might be a better way than option #3 as it would allow this easier.
If the IPC layer is not slowing things down too much, this architecture might allow you to distribute the engines over other PC's. This might enable you to use more hardware than you previously planned for. You could even think about hosting the engine in the Azure cloud.

What is significance of static keyword in Java and in C++?

What is the importance of Static keyword in Java and in C++ and how it's functionality differ in both programming languages ?
Maybe this link will give you a better idea: http://www.pp.rhul.ac.uk/~george/PH2150/html/node48.html
It has a visual diagram that may make it easier to understand.
There are 2 meanings for static. The first if you have a static variable, this means there is only 1 instance of this variable. It works pretty much the same in all programming languages with the keyword.
A static function is a function that can be called, even if the class it resides in is not instantiated. Static functions are necessary in C# and Java because you cant declare functions in these languages which have no encompassing class.
in C++, you can declare functions in the global namespace. In this language, static functions are used to denote that a function belongs to the class, but you dont have to instantiate the class to use the function. You could use a static function to access private variables of the class. Also note that in C++, static functions have a known memory address, so you can use function pointers to point to them without instantiating the class.
For Java, Understanding Instance and Class Members is a good place to start.
For C++, Microsoft has a reference on the static keyword.
There are many readily available programming language resources that will help you understand what the static keyword means. The above are two of them that I found with a quick Google search.
Use static for fields and methods that can only have one instance. That means they are not relevant to instances of a class, but to the class itself. For example the main thread (public static void main).
It works the same way in both languages. I assume you know what's object-oriented programming, and what's the difference between classes and objects/instances. So, if you mark a method or variable as "static", it operates on a class level, not instance level. All objects/instances share the same value of the "static" variable.

Resources