Are static classes and methods bad? Global variables frowned upon? - class

I have an application that has database connectivity and although there are obviously objects that correspond to data in my database, I find that all my data processing methods could be static as there is no real need for an instance of the object as my classes simply operate on the data and spit something out, no need to store anything outside the method's scope. If I can make a method or class static should I?
Also I use a utility singleton class for common (single instance) "global data". I want to have a good design, but are these frowned upon?
Let me give you an example of what I'm doing. I load some data from my database using a static method to place it into a global varaiable in my Singleton class (a list of a custom object)
So my singleton class has something like
List<MyCustomObject> SomeList
and my static class has
static void LoadData()
foreach(data in database something or other)
singletonClass.SomeList.Add()
So the code above might load in some records from the database into SomeList, where each item in SomeList is of type MyCustomObject, which contains a single record of information.
Is this good implementation? Is this how you would code it?
Then in my presentation layer I would make calls to another static class of methods to get data from the singleton class in to a format required.
It doesn't feel very OOPey. But I can't really think how to do it another way you do it.

Allow me to direct you toward an excellent article on this topic: Singletons are Pathological Liars.
The problem is that the need to call your LoadData() function isn't self-evident. Compare your situation to that described in the article and I think you'll see some parallels.

Statics and singletons are frowned upon somewhat. But only the same way as starting a sentence with “but” — bad when overused, but sometimes it's what works best.
In your example, why have separate classes, one a singleton and one static? A singleton is in many ways equivalent to a class with only static data and methods. If you already have a singleton, I'd say you should add the methods to load the data to it rather than to a separate class. A class with static methods would be more appropriate if, say, you have utility code common to all of your stored data types.
(Also, I wouldn't worry too much about what's OOPey and what's not. Overengineering in the blind service of OOP principles can be a serious problem, speaking as someone who's had to wade through the Eclipse code base …)

Singletons is one but static is another very big one.
OOP or not, static variables have many drawbacks but little coding convenience.
Can't determine exact allocation time, life span
Can't work well in multi-threaded
Future problem to program expansion
...

Related

In Swift OOP design, how do I arrange a commonly-used class?

I am new to Swift and OOP. For example, I have a class that manages the system-wide configurations.
class system_conf {
init()
getValue1()
getValue2()
...
setValue1()
setValue2()
...
reloadValues()
activateX()
activeteY()
...
}
This class should have only one instance and many other classes will use it. What's the recommended way for this case?
Should I pass around this instance?
Should I consider to use Singleton?
Should I use static functions directly?
Should I create a global instance, so every other class can access it directly?
or?
It seems your class is a configuration class. If you intend to pass it to a bunch of classes, you should wonder if you need to write unit tests for them.
If so, assuming you are either using a singleton or static methods or a global var, take a moment to think about how you would mock this configuration class for each of your tests. It's not easy, is it?
If your class is a kind of mediator, a global var or static methods are fine (or any other alternative you suggested). However, in your case, it would be better to pass your object in any initializer/constructor of each class using it. Then, testing would definitely be easier. Also, passing it via an interface is even better: you can mock it super easily (mock up libraries mostly work with interfaces only).
So there is no unique answer to your question. It is just a matter of compromises and scaling. If your app is small, any of the method you listed above is perfectly fine. However, if you app tends to get bigger, a proxy solution would be better for maintainability and testability.
If you fancy reading, you should glance at this article from Misko Hevery, especially this chapter.

Any reason not use use a singleton "variable" in Swift?

For Sept 2015, here's exactly how you make a singleton in Swift:
public class Model
{
static let shared = Model()
// ( for ocd friends ... private init() {} )
func test()->Double { print("yo") }
}
then elsewhere...
blah blah
Model.shared.test()
No problem.
However. I add this little thing...
public let model = Model.shared
public class Model
{
static let shared = Model()
func test()->Double { print("yo") }
}
then, you can simply do the following project-wide:
blah blah
model.test()
Conventional idiom:
You see Model.shared.blah() everywhere in the code.
"My" idiom:
You see model.blah() everywhere in the code.
So, this results in everything looking pretty!
This then, is a "macro-like" idiom.
The only purpose of which is to make the code look pretty.
Simplifying appearances of ImportantSystem.SharedImportantSystem down to importantSystem. throughout the project.
Can anyone see any problems with this idiom?
Problems may be technical, stylistic, or any other category, so long as they are really deep.
As a random example, here's an "article in singletons in Swift" that happens to also suggest the idea: https://theswiftdev.com/swift-singleton-design-pattern/
Functionally, these are very similar, but I'd advise using the Model.shared syntax because that makes it absolutely clear, wherever you use it, that you're dealing with a singleton, whereas if you just have that model global floating out there, it's not clear what you're dealing with.
Also, with globals (esp with simple name like "model"), you risk of having some future class that has similarly named variables and accidentally reference the wrong one.
For a discussion about the general considerations regarding globals v singletons v other patterns, see Global Variables Are Bad which, despite the fairly leading title, presents a sober discussion, has some interesting links and presents alternatives.
By the way, for your "OCD friends" (within which I guess I must count myself, because I think it's best practice), not only would declare init to be private, but you'd probably declare the whole class to be final, to avoid subclassing (at which point it becomes ambiguous to what shared references).
There are a few things to look out for when using this approach:
The global variable
A global variable in itself is no big deal, but if you have quite some global variables, you might have trouble with autocompletion, because it will always suggest these global variables.
Another problem with global variables is that you could have another module in your application (written by you or otherwise) define the same global variable. This causes problems when using these 2 modules together. This can be solved by using a prefix, like the initials of your app.
Using global variables is generally considered bad practice.
The singleton pattern
A singleton is helpful when working with a controller, or a repository. It is once created, and it creates everything it depends on. There can be only one controller, and it opens only one connection to the database. This avoids a lot of trouble when working with resources or variables that need to be accessed from throughout your app.
There are downsides however, such as testability. When a class uses a singleton, that class' behaviour is now impacted by the singletons behaviour.
Another possible issue is thread safety. When accessing a singleton from different threads without locking, problems may arise that are difficult to debug.
Summary
You should watch out when defining global variables and working with singletons. With the appropriate care, not many problems should arise.
I can't see a single downside to this approach:
You can use different variables for different parts of the program (-> No namespace cramming if you don't like this I guess)
It's short, pretty, easy to use and makes sense when you read it. Model.shared.test() doesn't really make sense if you think about it, you just want to call test, why would I need to call shared when I just need a function.
It uses Swift's lazy global namespace: The class gets allocated and initialized when you use it the first time; if you never use it, it doesn't even get alloced/inited.
In general, setting aside the exact idiom under discussion, regarding the use of singletons:
Recall that, of course, instead of using static var shared = Model() as a kind of macro to a singleton, as suggested in this Q, you can just define let model = Model() which simply creates a normal global (unrelated to singletons).
With Swift singletons, there has been discussion that arguably you want to add a private init() {} to your class, so that it only gets initialized once (noting that init could still be called in the same file).
Of course in general, when considering use of a singleton, if you don't really need a state and the class instance itself, you can simply use static functions/properties instead. It's a common mistake to use a singleton (for say "calculation-like" functions) where all that is needed is a static method.

In Objective-C, what's the advantage of having a singleton over a class method?

As above, but careful, I'm only interested in Objective-C context, so there is no point in pointing out the advantages of a singleton over a static methods.
I would say nothing. Singletons are often considered bad practice and this applies to Obejctive-C as well. One thing that might make singletons a better solution than class methods is that singletons are proper instances that can access instance variables, so if one needs the class to store data in ivars, singletons can be a solution. (But well, even implementing singletons often requires using static global or local variables - so strictly speaking, you can't really avoid them entirely, at most you can reduce their number to one.)
One significant advantage is class methods in Objective-C can't hold onto any data (unless declared as static within the method). Whereas with a singleton, you have access to all of the data of the single-instance

Why doesn't Scala have static members inside a class?

I know you can define them indirectly achieve something similar with companion objects but I am wondering why as a language design were statics dropped out of class definitions.
The O in OO stands for "Object", not class. Being object-oriented is all about the objects, or the instances (if you prefer)
Statics don't belong to an object, they can't be inherited, they don't take part in polymorphism. Simply put, statics aren't object-oriented.
Scala, on the other hand, is object oriented. Far more so than Java, which tried particularly hard to behave like C++, in order to attract developers from that language.
They are a hack, invented by C++, which was seeking to bridge the worlds of procedural and OO programming, and which needed to be backwardly compatible with C. It also admitted primitives for similar reasons.
Scala drops statics, and primitives, because they're a relic from a time when ex-procedural developers needed to be placated. These things have no place in any well-designed language that wishes to describe itself as object-oriented.
Concerning why it's important to by truly OO, I'm going to shamelessly copy and paste this snippet from Bill Venners on the mailing list:
The way I look at it, though, is that singleton objects allow you to
do the static things where they are needed in a very concise way, but
also benefit from inheritance when you need to. One example is it is
easier to test the static parts of your program, because you can make
traits that model those parts and use the traits everywhere. Then in
the production program use a singleton object implementations of those
traits, but in tests use mock instances.
Couldn't have put it better myself!
So if you want to create just one of something, then both statics and singletons can do the job. But if you want that one thing to inherit behaviour from somewhere, then statics won't help you.
In my experience, you tend to use that ability far more than you'd have originally thought, especially after you've used Scala for a while.
I also posted this question on scala users google group and Bill Venners one of the authors of "Programming in scala" reply had some insights.
Take a look at this: https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/6vZJgi42TIMJ and https://groups.google.com/d/msg/scala-user/5jZZrJADbsc/oTrLFtwGjpEJ
Here is an excerpt:
I think one
goal was simply to be simpler, by having every value be an object,
every operation a method call. Java's statics and primitives are
special cases, which makes the language more "complicated" in some
sense.
But another big one I think is to have something you can map Java's
statics to in Scala (because Scala needed some construct that mapped
to Java's statics for interop), but that benefits from OO
inheritance/polymorphism. Singleton objects are real objects. They can
extend a superclass or mix in traits and be passed around as such, yet
they are also "static" in nature. That turns out to be very handy in
practice.
Also take a look at this interview with Martin Odersky (scroll down to Object-oriented innovations in Scala section) http://www.artima.com/scalazine/articles/goals_of_scala.html
Here is an excerpt:
First, we wanted to be a pure object-oriented language, where every value is an object, every operation is a method call, and every variable is a member of some object. So we didn't want statics, but we needed something to replace them, so we created the construct of singleton objects. But even singleton objects are still global structures. So the challenge was to use them as little as possible, because when you have a global structure you can't change it anymore. You can't instantiate it. It's very hard to test. It's very hard to modify it in any way.
To Summarize:
From a functional programming perspective static members are generally considered bad (see this post by Gilad Bracha - the father of java generics. It mainly has to do with side effects because of global state). But scala had to find a way to be interoperable with Java (so it had to support statics) and to minimize (although not totally avoid) global states that is created because of statics, scala decided to isolate them into companion objects.
Companion objects also have the benefit of being extensible, ie. take advantage of inheritance and mixin composition (separate from emulating static functionality for interop).
These are the things that pop into my head when I think about how statics could complicate things:
1) Inheritance as well as polymorphism would require special rules. Here is an example:
// This is Java
public class A {
public static int f() {
return 10;
}
}
public class B extends A {
public static int f() {
return 5;
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.f());
B b = new B();
System.out.println(b.f());
A ba = new B();
System.out.println(ba.f());
}
}
If you are 100% sure about what gets printed out, good for you. The rest of us can safely rely on mighty tools like #Override annotation, which is of course optional and the friendly "The static method f() from the type A should be accessed in a static way" warning. This leads us to
2) The "static way" of accessing stuff is a further special rule, which complicates things.
3) Static members cannot be abstract. I guess you can't have everything, right?
And again, these are just things which came to my mind after I gave the matter some thought for a couple of minutes. I bet there are a bunch of other reasons, why statics just don't fit into the OO paradigm.
It's true, static member don't exists, BUT, it's possible to associate a singleton object to each class:
class MyClass {
}
object MyClass {
}
to obtain similar results
Object oriented programming is all about objects and its states(Not touching state full and stateless objects in Java). I’m trying to stress “Static does not belong to objects”. Static fields cannot be used to represent a state of an object so it’s rational to pull off from objects.

Pseudo-multiple-inheritance with extension methods on interfaces in C#?

Similar question but not quite the same thing
I was thinking that with extension methods in the same namespace as the interface you could get a similar effect to multiple inheritance in that you don't need to have duplicate code implementing the same interface the same way in 10 different classes.
What are some of the downsides of doing this? I think the pros are pretty obvious, it's the cons that usually come back to bite you later on.
One of the cons I see is that the extension methods can't be virtual, so you need to be sure that you actually do want them implemented the same way for every instance.
The problem that I see with building interface capability via extension methods is that you are no longer actually implementing the interface and so can't use the object as the interface type.
Say I have a method that takes an object of type IBar. If I implement the IBar interface on class Foo via extension methods, then Foo doesn't derive from IBar and can't be used interchangeably with it (Liskov Substitution principle). Sure, I get the behavior that I want added to Foo, but I lose the most important aspect of creating interfaces in the first place -- being able to define an abstract contract that can be implemented in a variety of ways by various classes so that dependent classes need not know about concrete implementations.
If I needed multiple inheritance (and so far I've lived without it) badly enough, I think I'd use composition instead to minimize the amount of code duplication.
A decent way to think about this is that instance methods are something done by the object, while extension methods are something done to the object. I am fairly certain the Framework Design Guidelines say you should implement an instance method whenever possible.
An interface declares "I care about using this functionality, but not how it is accomplished." That leaves implementers the freedom to choose the how. It decouples the intent, a public API, from the mechanism, a class with concrete code.
As this is the main benefit of interfaces, implementing them entirely as extension methods seems to defeat their purpose. Even IEnumerable<T> has an instance method.
Edit: Also, objects are meant to act on the data they contain. Extension methods can only see an object's public API (as they are just static methods); you would have to expose all of an object's state to make it work (an OO no-no).