Should all the static methods be synchronised? - oop

I will explain the two use-cases here:
Static method which uses an object and perform some operations and returns the same object:
// Lets assume here SomeObject contains a function putInt which store a HashMap.
public static SomeObject createIntEvent(SomeObject objectName,
final String eventName,
final int value){
objectName.putInt(eventName, value);
return objectName;
}
Static method which creates an object and perform some operations and returns the created Object:
// Lets assume here SomeObject contains a function putInt which store a HashMap.
public static SomeObject createIntEvent(final String eventName,
final int value){
SomeObject objectName = new SomeObject();
objectName.putInt(eventName, value);
return objectName;
}
For the above two examples, For Case 2 we should have createIntEvent as a synchronized method because we are creating a new object and if it is not thread safe it could cause unwanted problems. But for the case 1, I wasn't certain if the same logic applies.
Can someone please explain why the first Case should or shouldn't be synchronized?
I tried creating a sample program to do the same thing, didn't face any issue. But was wondering if there is some Design pattern which advocates this.
Thank you for your time.

Related

Execute a method when object is changed (OOP)

I'm learning OOP and trying to write a simple program that will execute some method every time when a specific varible will change.
I have two classes:
public class SomeClass {
private OtherClass object;
public OtherClass getObject() {
return this.object;
}
public void setObject(OtherClass object) {
objectChanged();
this.object = object;
}
private void objectChanged() {
System.out.println("Object has changed");
}
}
public class OtherClass {
private int value = 5;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
}
The variable objectChanged should be called every time when variable "object" is changed. My first naive idea was to put the method call inside of set function. But what if you change the object after you set it? Like this:
SomeClass someObject = new SomeClass();
OtherClass otherObject = new OtherClass();
someObject.setObject(otherObject); //"Object has changed"
otherObject.setValue(10); //nothing happens yet
I need someObject to realize that object stored inside of it changed its value to 10, but how do i do it? Is it even possible in OOP?
It looks to be reasonable, but one should consider many things. This is why there is no automatic way to do it in general. It is not part of the OOP paradigm as such. If this would be some automatic behavior, it would cause huge overhead as it is not often needed to observe changes this way. But you can, of course, implement your way depending on your concrete requirements.
There are at least two approaches.
In MVVM (like WPF) there is an INotifyPropertyChanged interface (let's call it a pattern) you can use to trigger a notification yourself, mutch like you did with SomeClass. However when you are nesting objects, you need to wire up that mechanism.to cascade: you should do the same with OtherClass and also connect the actual instances to bubble up changes.
See: https://rehansaeed.com/tag/design-patterns/
An other option is the Observable pattern. Each time the object changes state, you emit an instance - the current instance. However, you should care to emit unmutable objects. At least by using an interface that makes it read-only. But you still need to wire up the object tree to react to the changes of nested objects.
If your platform supports reflection, and you create a proper toolset, you could make this wiring up quite simple. But again: this is not strictly related to the paradigm.

Kotlin object, an implementation vs instance

In Objects in Kotlin: Create safe singletons in one line of code (KAD 27) Antonio Leiva states:
In fact, an object is just a data type with a single implementation.
I would expect to see the term instance rather than implementation used here. Is there some nuance that I am missing?
Sure it does have a single instance after all, but I believe what they meant to say is that whatever you write in an object is final and you can not override it. Even if you make it open(for argument purpose), you can not make an anonymous object out of it since the anonymous class can't be used on a SingleTon instance.
So " data type with a single implementation" means, whatever you write is the final implementation. An instance is, after all, a result of some implementation.
For reference, I am adding a decompiled code of object declaration.
public final class Test {
#NotNull
private static final String testMember = "Test";
public static final Test INSTANCE;
#NotNull
public final String getTestMember() {
return testMember;
}
private Test() {
}
static {
Test var0 = new Test();
INSTANCE = var0;
testMember = "Test";
}
}

Do "return success" methods violate the single responsibility principle?

public class FooList {
public boolean add(Foo item) {
int index = indexOf(item.getKey());
if (index == -1) {
list.add(item);
}
return index == -1;
}
}
Since this adds an item and returns a success value, does it violate the single-responsibility principle? If so, does it matter?
An alternative would be to throw an exception:
public class FooList {
public boolean add(Foo item) throws FooAlreadyExistsException {
int index = indexOf(item.getKey());
if (index == -1) {
list.add(item);
} else {
throw new FooAlreadyExistsException();
}
}
}
But would this, too, violate the single-responsiblity principle? It seems that the method has two tasks: if the item doesn't exist, add it; else, throw an exception.
Bonus question: Do methods that can return null violate the single-responsibility principle? Here's an example:
public class FooList {
public Foo getFoo(String key) {
int index = indexOf(key);
return (index == -1) ? null : list.get(index);
}
}
Is returning either a Foo or null, depending on the situation, "doing two things"?
How about this:
public class MyVector{
private int[] data;
private int count;
public void add(int value){
data[count]=value;
++count;
}
}
add does two things - it updates data and increments count. According to the single responsibility rule I should have split it into two functions:
public void MyVector{
private int[] data;
private int count;
public void add(int value){
data[count]=value;
}
public void inc(){
++count;
}
}
which - obviously - breaks the very foundation of OOP. I want data and count to change together - that's kind of the whole point of bundling them together in a class!
You won't get very far if you apply the rule of single responsibility like this. If every method can only do one thing, then the entire program can only do one thing, and when the definition of one thing is like the one used in the above example you're program can't do anything interesting.
The thing is - that's not how the single responsibility rule works:
You shouldn't strive to write methods that can't be defined in a way that specifies more than one thing. Instead, you should write method that can be meaningfully and sufficiently defined in a way that specifies one only thing that they do.
You shouldn't define one thing based on implementation - you should define it based on the abstraction of the class that hosts the method.
This will be a bit controversial: You should be more strict regarding side-effects and less strict regarding return values. The reasoning is that it's easier for the user of your methods to ignore return values than to ignore side-effects.
Exceptions should never be counted as "the method is doing another thing". They are not part of the description of what the method does - they are exception to that, that only happens if something goes wrong. That's the whole point of exceptions.
Now, let's take a look at your method. The implementation is three things: checking for existence, adding the item, and returning the success result. But if you look at the abstraction, you can define it as adding an item if it doesn't exists - and that's one thing!
Yes, it also returns something, but return values can easily be ignored so I wouldn't count it as "another thing". Users of the method will use it for adding items, so they can ignore the return values if they don't need it. If it was the other way around, and they were using your method to check for existence of items, they wouldn't be able to ignore the side-effect of adding the item and that would be bad. Very bad. But since the "additional thing" is the return value(or exception) and not the side-effect - there's no problem with your method.
The most important design rule is to not blindly follow design rules.

What is this: Object holding static list of same objects BUT casted to interface?

I encountered the situation mentioned in the topic now more than once and now I want to ask in here for
other opinions, hints, explanations, why someone should/would/ do things like this:
There is an object of class A, which implements the interface I_1o
This object has a static member, a collection, typed by interface I_1.
The class A has an interface-implemented method, which is called get_instance ( key-params ).
It looks inside the collection for a specified object fitting the key params and returns the
relevant object.
Is there a name for this (design pattern, whatever), a reason, a "best practice" explanation, why this seems to be a singleton but on the other hand it is not, just recursive object holding?
If no one understands, what I mean, just let me know, I will try to clarify it then.
This sounds an awful lot like an Object Pool design pattern. Documentation here.
This looks something like this:
public class Pool
{
private static int MAX_ELEMS = 10;
private static List<Object> instances;
private static void initialise()
{
if(instances == null) {
instances = new ArrayList<Object>();
// Initialise all the objects in the list.
}
}
public static Object getInstance(String key)
{
for(Object instance : instances) {
if(instance.equals(key)) { // Just an example
return instance;
}
}
}
}
The reason for this design pattern is to avoid the expensive re-instanciation of objects. If you have a load of, for example, Server connection objects, and you want to limit the amount of connections to the server, then you implement a pattern like this. It will mean that no more than MAX_ELEMS objects exist at one time, and it also means that they are not created during use of the program; they are built during some loading period in the program.
This looks like a Registry or IdentityMap.

Can a class return an object of itself

Can a class return an object of itself.
In my example I have a class called "Change" which represents a change to the system, and I am wondering if it is in anyway against design principles to return an object of type Change or an ArrayList which is populated with all the recent Change objects.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
In C#, an example might be:
public class Change
{
public int ChangeID { get; set; }
private Change(int changeId)
{
ChangeID = changeId;
LoadFromDatabase();
}
private void LoadFromDatabase()
{
// TODO Perform Database load here.
}
public static Change GetChange(int changeId)
{
return new Change(changeId);
}
}
Yes it can. In fact, that's exactly what a singleton class does. The first time you call its class-level getInstance() method, it constructs an instance of itself and returns that. Then subsequent calls to getInstance() return the already-constructed instance.
Your particular case could use a similar method but you need some way of deciding the list of recent changes. As such it will need to maintain its own list of such changes. You could do this with a static array or list of the changes. Just be certain that the underlying information in the list doesn't disappear - this could happen in C++ (for example) if you maintained pointers to the objects and those objects were freed by your clients.
Less of an issue in an automatic garbage collection environment like Java since the object wouldn't disappear whilst there was still a reference to it.
However, you don't have to use this method. My preference with what you describe would be to have two clases, changelist and change. When you create an instance of the change class, pass a changelist object (null if you don't want it associated with a changelist) with the constructor and add the change to that list before returning it.
Alternatively, have a changelist method which creates a change itself and returns it, remembering the change for its own purposes.
Then you can query the changelist to get recent changes (however you define recent). That would be more flexible since it allows multiple lists.
You could even go overboard and allow a change to be associated with multiple changelists if so desired.
Another reason to return this is so that you can do function chaining:
class foo
{
private int x;
public foo()
{
this.x = 0;
}
public foo Add(int a)
{
this.x += a;
return this;
}
public foo Subtract(int a)
{
this.x -= a;
return this;
}
public int Value
{
get { return this.x; }
}
public static void Main()
{
foo f = new foo();
f.Add(10).Add(20).Subtract(1);
System.Console.WriteLine(f.Value);
}
}
$ ./foo.exe
29
There's a time and a place to do function chaining, and it's not "anytime and everywhere." But, LINQ is a good example of a place that hugely benefits from function chaining.
A class will often return an instance of itself from what is sometimes called a "factory" method. In Java or C++ (etc) this would usually be a public static method, e.g. you would call it directly on the class rather than on an instance of a class.
In your case, in Java, it might look something like this:
List<Change> changes = Change.getRecentChanges();
This assumes that the Change class itself knows how to track changes itself, rather than that job being the responsibility of some other object in the system.
A class can also return an instance of itself in the singleton pattern, where you want to ensure that only one instance of a class exists in the world:
Foo foo = Foo.getInstance();
The fluent interface methods work on the principal of returning an instance of itself, e.g.
StringBuilder sb = new StringBuilder("123");
sb.Append("456").Append("789");
You need to think about what you're trying to model. In your case, I would have a ChangeList class that contains one or more Change objects.
On the other hand, if you were modeling a hierarchical structure where a class can reference other instances of the class, then what you're doing makes sense. E.g. a tree node, which can contain other tree nodes.
Another common scenario is having the class implement a static method which returns an instance of it. That should be used when creating a new instance of the class.
I don't know of any design rule that says that's bad. So if in your model a single change can be composed of multiple changes go for it.