helper functions as static functions or procedural functions? - static-methods

i wonder if one should create a helper function in a class as a static function or just have it declared as a procedural function?
i tend to think that a static helper function is the right way to go cause then i can see what kind of helper function it is eg. Database::connect(), File::create().
what is best practice?

IMO it depends on what type of helper function it is. Statics / Singletons make things very difficult to test things in isolation, because they spread concrete dependencies around. So if the helper method is something I might want to fake out in a unit test (and your examples of creating files and connecting to databases definitely would fall in that category), then I would just create them as instance methods on a regular class. The user would instantiate the helper class as necessary to call the methods.
With that in place, it is easier to use Inversion of Control / Dependency Injection / Service Locator patterns to put fakes in when you want to test the code and you want to fake out database access, or filesystem access, etc.
This of course has the downside of there theoretically being multiple instances of the helper class, but this is not a real problem in most systems. The overhead of having these instances is minimal.
If the helper method was something very simple that I would never want to fake out for test, then I might consider using a static.

Singleton solves the confusion.
MyHelper.Instance.ExecuteMethod();
Instance will be a static property. Benefit is you get simple one line code in calling method and it reuses previously created instance which prevents overhead of instance creation on different memory locations and disposing them.

Related

GLib - difference between class_init and init class methods

I'm a newbie with glib and I'm still struggling to understand the difference between my_class_name_class_init() methods and my_class_name_init() methods.
I get that the latter is kinda equivalent to a C++ constructor and that goes per-instance of the object created but I don't quite understand the purpose of those my_class_name_class_init() methods. By reading the documentation I think class_init() methods are somewhat similar to a static constructor valid for all instances but I'm still not sure I got this right.
What's the purpose of class_init() methods?
class_init functions are executed once per class, before first instance is constructed - in that way they are similar to C# static constructors. In contrast, instance_init functions are called for every instance of object created and are responsible for initializing that instance.
Like static constructors, class_init are responsible for initializing any shared data all instances might need, but more importantly, in GObject they play vital role in setting up GObject object system. They are responsible for:
Setting up virtual function tables
Setting up GObject property system
Setting up signals

Deprecation of TableRegistry::get()

I'd like to ask what are your thought on deprecation of the TableRegistry::get() static call in CakePHP 3.6?
In my opinion it was not a good idea.
First of all, using LocatorAwareTrait is wrong on many levels. Most important, using traits in such way can break the Single Responsibility and Separation of Concerns principles. In addition some developers don't want to use traits as all because they thing that it breaks the object oriented design pattern. They prefer delegation.
I prefer to use delegation as well with combination of flyweight/singleton approach. I know that the delegation is encapsulated by the LocatorAwareTrait but the only problem is that it exposes the (get/set)TableLocator methods that can be used incorrectly.
In other words if i have following facade:
class Fruits {
use \Cake\ORM\Locator\LocatorAwareTrait;
public function getApples() { ... }
public function getOranges() { ... }
...
}
$fruits = new Fruits();
I don't want to be able to call $fruits->getTableLocator()->get('table') outside of the scope of Fruits.
The other thing you need to consider when you make such changes is the adaptation of the framework. Doing TableRegistry::getTableLocator()->get('table') every time i need to access the model is not the best thing if i have multiple modules in my application that move beyond simple layered architecture.
Having flyweight/singleton class like TableRegistry with property get to access desired model just makes the development more straight forward and life easier.
Ideally, i would just like to call TR::get('table'), although that breaks the Cake's coding standards. (I've created that wrapper for myself anyways to make my app bullet proof from any similar changes)
What are your thoughts?

Calling non static method in static context(main)

I know that non static methods cannot be referenced from some static context, you have to make an instance of the class and call the method on that instance, or , you can make the method static. I also know the reason why. But I cannot decide what is the best practice to do this? Making the method/variable static or using instance of the class to call the method/variable, and why?
Object oriented languages work best when you use objects. If its anything more than the most basic of applications, create a class to house the functionality and instantiate it. You'll just end up refactoring into classes later anyway.
The reason is that objects, instances, etc all describe varying degrees of scope, allowing you to create complex programs from an amalgamation of encapsulated, fairly simple functionalities

Global property for DB access rather than passing DB around everywhere? Advice anyone?

Globals are evil right? At least everything I read says so, because something might alter the state of the global at any point.
However, I've a DB object that's a bit of a tramp in regards class parameters. The property below is an instance of a wrapper class that automatically works in MS Access or SQL - hence why it's not EF or some other ORM.
Public Property db As New DBI.DBI(DBI.DBI.modeenum.access, String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0} ;Persist Security Info=True;Jet OLEDB:Database Password=""lkjhgfds8928""", GetRpcd("c:\cms")))
The code itself does have PostSharp for exception handling, so I'm thinking that I can conditionally handle oledb errors by logging them and re initialising the DB if it is Null.
Up till now, the solution has been to continually pass the db around as a parameter to every single class that needs it. Most of the data classes have a shared observablecollection that is built from structures that individually implement inotifyproperty changed. One of these is asynchronously built. The collection property checks if it's empty before firing off the private Async buildCollection sub.
Given that we don't use dependency injection (yet) as I need to learn it; is the Global property all that bad? Db is needed everywhere that data is pulled in or saved. The only places I don't need it at all is the View and its code behind.
It's not a customer facing project but it does need to be solid.
Any advice gratefully recieved!!
Passing the DB connection as a parameter into your classes IS using dependency injection, perhaps you just didn't recognize it as such. Hard coding the connection string in the callers is still code that is not free of dependencies, but at least your database accessors themselves are free of the dependency upon a global connection.
Globals aren't just evil because they change without notice - that's just one effect you see resulting from the bad design choice. They're evil because a design using them is brittle. Code that depends upon globals requires invisible stuff to be set correctly before calling it, and that leads to inter-dependencies between unrelated code. The invisible stuff becomes critically important stuff. Reading just the interface of a module that internally uses globals, how would I know that I have to call the SetupGlobalThing() method before calling it? What happens if I call IncrementGlobalThing() and DecrementGlobalThing() and MultiplyGlobalThing() in varying orders, depending on the function the user selects?
Instead, prefer stateless methods where you pass in all the stuff to be changed and used: IncrementThing(Integer thing) doesn't rely on hidden setup steps. It clearly does one thing: it increments the thing passed in.
It may help to think about it from a unit testing viewpoint. If you were to write a unit test to prove a specific module of code works, would you need to pass in a real database connection (hard*), or would you be able to pass in a fake database reference that meets your testing needs easily?
The best way to test your logic is to unit test it. The best way to test your class interfaces and method structure is to write unit tests that call them. If the class is hard to test, it's likely due to dependencies upon external things (globals, singletons, databases, inappropriate member variables, etc.)
The reason I called using a real database "hard" is that a unit test needs to be easy and fast to run. It shouldn't rely on slow or breakable or complex external things. Think about unit testing your software on the bus, with no network connection. Think about how much work it is to create a dummy database: you have to add users, you have to have the right version of schema in it, it has to be installed, it has to be filled with the right kind of testing data, you need network connectivity to it, all those things can make your testing unreliable. Instead, in a unit test you pass in a mock database, which simply returns values that exercise your code being tested.

Avoid Database Dependency For Unit Testing Without Mocking

I've got many objects with methods that require database access. We're looking to get into unit testing but are keen to avoid the use of mock objects if possible. I'm wondering if there is a way to refactor the Validate method shown below so that it wouldn't need db access. In the actual application there is usually a fair bit more going on but I think this simplified example should be enough.
We'll learn to use mock objects if we need to but it just seems like a lot of overhead, so I'm looking for alternatives.
public class Person
{
public string Name;
public string Validate()
{
if (PersonDA.NameExists(Name))
{
return "Name Already Used";
}
}
}
Personally I'd just go the mock object route. It's much more flexible and it sounds like you're wanting to go the route of putting test code in your actual object?
Regarless, extract the validation code into a PersonValidator object with a method for boolean isValid(Person). Then in the test code use a mock validator which just returns true or false based on the test case.
The Person class is hard to unit-test because it has a hidden, static dependency on database access code. You can break this coupling by introducing a dynamic collaboration between the Person and some new type of object that provides it with the information it needs to validate its state. In your unit tests of the Person you can test what happens when it is valid or invalid without hitting the database by passing the Person object "stub" implementations of it's collaborator.
You can test the real implementation, which hits the database, in a separate set of tests. Those tests will be slower but there should be fewer of them because they will be direct translations of accessor methods to database queries with no complex logic of their own.
You can call that "using mock objects" if you like but, because your current design means you only need to stub queries, not expect commands, a mock object framework is a too complicated tool for the job. Hand-written stubs will make test failures easier to diagnose.
Take a look at dbunit, it's especially set up to populate a small test database so you can use your real objects on a mock database during unit testing. Testing with it is far easier than developing mock objects, far safer than modifying your data access code, and far more thorough than either.
Why are you trying to avoid mocks exactly? If you are going to practice unit testing and you have data access code, its going to be easiest to get comfortable with the mock/stub/inject way of doing things.
If it's because you dont want to bring in a mocking framework you could code up some simple stubs as you need them.
Putting your data access code behind an interface will let to avoid the need for a database. Consider using dependency injection to insert the mock or stub data access code during your tests.
You should just set up a database that is used for the unit testing.
If you use mockups for all the data access, you wouldn't actually be testing much? :)

Resources