I am trying to understand if there could be any issues with Predicate defined at class level in multithreaded application. ? We have defined such predicates in our services and using them up different methods of same class. Currently we have not seen any issue but I am curious to understand our class level Predicate object is going to function. will there be any inconsistency in the behaviour?
eg:
class SomeClass{
Predicate<String> check = (value) -> value.contains("SomeString");
// remaning impl. of the class.
}
The predicate in your example is categorically thread-safe. It is calling a method on an intrinsicly thread-safe (and immutable) object.
This does not generalize to all predicates though. For example
Predicate<StringBuilder> check = (value) -> value.indexOf("SomeString") >= 0;
is not thread-safe. Another thread could mutate the contents of the StringBuilder argument while this predicate is checking it. The predicate could also be vulnerable to memory model related inconsistencies.
(The StringBuilder class is not thread-safe; see javadoc.)
It is not clear what you mean by "class level". Your example shows a predicate declared as a regular field, not a static (class level) field.
With a variable declared as a (mutable) instance field, it is difficult to reason about the thread-safety of the field in isolation. This can be solved by declaring the field as final.
Related
Assuming that I want that following Value Object contains always capitalized String value. Is it eligible to do it like this with toUpperCase() in constructor?
class CapitalizedId(value: String) {
val value: String = value.toUpperCase()
// getters
// equals and hashCode
}
In general, I do not see a problem of performing such a simple transformation in a value object's constructor. There should of course be no surprises for the user of a constructor but as the name CapitalizedId already tells you that whatever will be created will be capitalized there is no surprise, from my point of view. I also perform validity checks in constructors to ensure business invariants are adhered.
If you are worried to not perform operations in a constructor or if the operations and validations become too complex you can always provide factory methods instead (or in Kotlin using companion, I guess, not a Kotlin expert) containing all the heavy lifting (think of LocalDateTime.of()) and validation logic and use it somehow like this:
CapitalizedId.of("abc5464g");
Note: when implementing a factory method the constructor should be made private in such cases
Is it eligible to do it like this with toUpperCase() in constructor?
Yes, in the sense that what you end up with is still an expression of the ValueObject pattern.
It's not consistent with the idea that initializers should initialize, and not also include other responsibilities. See Misko Hevery 2008.
Will this specific implementation be an expensive mistake? Probably not
When using Kryo, it's generally recommended that you register the classes you intend to serialize so the class name doesn't need to be included in the serialized data.
But in a class hierarchy, the actual implementation class may not be obvious. For example, if I have a Spark dataset that contains Vector objects, those objects' concrete class may be either DenseVector or SparseVector.
When I register the classes with Kryo, should I:
Register the class according to the dataset's declared type (Vector)
Register the concrete classes (DenseVector and SparseVector)
All of the above, just in case?
Bonus question: if the Vector appears as a field in a tuple or case class, would you also need to register the product (Tuple2[Vector, Int] for example)?
Answer to main question
The answer is... no 2 :) In other words:
you need to register the concrete classes only, and
you need to register every single concrete class that you may encounter1.
Unfortunately, I have no documentation reference to back this up right now (I know it from experience).
1 There is a special case, though, when you can register only an abstract class for the purposes of serialization/deserialization (not for Kryo.copy() though). This case is when:
your serialization is the same for all subclasses, and
during deserialization, you can decide which subclass to return based on the data.
Look at the ImmutableListSerializer by Martin Grotzke. In the registerSerializers method, he registers only ImmutableList class for the purposes of serialization/deserialization because:
serialization is the same, and
during deserialization, ImmutableList.copyOf() takes care of returning the proper subclass.
Answer to bonus question
If the Vector appears in a tuple or case class, you need to register the appropriate class (e.g. Tuple2).
Note that generic types do not matter here as long as you serialize using Kryo.writeClassAndObject (e.g. ImmutableListSerializer extends Serializer<ImmutableList<Object>>).
I'm checking out Sharp Architecture's code. So far it's cool, but I'm having problems getting my head around how to implement DDD value objects in the framework (doesn't seem to be anything mentioning this in the code). I'm assuming the base Entity class and Repository base are to be used for entities only. Any ideas on how to implement value objects in the framework?
In Sharp Arch there is a class ValueObject in namespace SharpArch.Domain.DomainModel. This object inherits from BaseObject and overrides the == and != operators and the Equals() and GetHashCode() methods. The method overrides just calls the BaseObject versions of those two methods which in turn uses GetTypeSpecificSignatureProperties() method to get the properties to use in the equality comparison.
Bottom line is that Entity's equality is determined by
Reference equality
Same type?
Id's are the same
Comparison of all properties decorated with the [DomainSignature] attribute
For ValueObjects, the BaseObject's Equals method is used
Reference equality
Same type?
Compare all public properties
This is a little bit simplified, I suggest you get the latest code from github and read through the code in the mentioned 3 classes yourself.
Edit: Regarding persistence, this SO question might help. Other than that, refer to the official NH and Fluent NH documentation
Value objects are simple objects that don't require a base class. (The only reason entities have base classes is to provide equality based on the identity). Implementing a value object just means creating a class to represent a value from your domain. A lot of times value objects should be immutable and provide equality comparison methods to determine equality to other value objects of the same type. Take a look here.
I am currently reading an existing code in MS Visual C++ 6.0. I notice a code pattern where they cast object into a structure.
There is a CMemory object.
CMemory a;
MY_STRUCTURE_A* a = (MY_STRUCTURE_A*)(void *)a;
MY_STRUCTURE_B* a = (MY_STRUCTURE_B*)(void *)a;
I checked the Custom memory class and it really is a class object. It does have a = operator defined but I do not think that would allow it to be reinterpreted to a structure. Why is this being done. How is an object type being cast to different objects?
Any idea why this is being done? I know there is a reinterpret_cast and I am guessing that this technique of casting to void pointer to a structure pointer is similar. But I am not sure if it is the same. Is this pattern safe casting a class object to a struct?
Note: the CMemory is just an arbritary name of the object used. It is not part of the MFC class.
Added based on Necrolis' comment.
The CMemory and it has only 3 members declared in the following order (1) char pointer, (2) int specifying the allocated memory of (1), and (3) a previous and next pointer to other instance of CMemory. It also has a lot of member method. From what I understand, even if I directly cast a class to a structure. The class would start should start with the first member variable which is the char pointer.
class CMemory {
public:
CAMemory();
... Other methods
private:
char *m_pMemory;
int m_memorySize;
... Other field
}
Going by the name of the class and the casting, CMemory is more than likely a generic memory block tag (for a GC, arbitrary hash table etc), and to access the memory its tagging requires a cast. Of course this is a "best guess", it means nothing without seeing the full code for CMemory.
Is this safe, totally not, its not only UB, but there is no check (at least in your example) as to whether the object you casting to is the object represented by the memory layout. Also, with this being C++, they should be avoiding C casts (as you have noted. the double cast is in fact to get around compiler errors/warnings, which is always the worst way to solve them).
What is the difference between association and dependency? Can you give code examples?
What is the relationship between class A and B?
class A
{
B *b;
void f ()
{
b = new B ();
b->f();
delete b;
}
}
The short answer is: how any specific source language construct should be represented in UML is not strictly defined. This would be part of a standardized UML profile for the language in question, but these are sadly few and far between. Long answer follows.
In your example, I'm afraid I would have to say "neither", just to be difficult. A has a member variable of type B, so the relationship is actually an aggregation or a composition... Or a directed association. In UML, a directed association with a named target role is semantically equivalent to an attribute with the corresponding name.
As a rule of thumb, it's an aggregation if b gets initialized in A's constructor; it's a composition if it also gets destroyed in B's destructor (shared lifecycle). If neither applies, it's an attribute / directed association.
If b was not a member variable in A, and the local variable b was not operatoed on (no methods were called on it), then I would represent that as a dependency: A needs B, but it doesn't have an attribute of that type.
But f() actually calls a method defined in B. This to me makes the correct relationship a <<use>>, which is a more specialized form of dependency.
Finally, an (undirected) association is the weakest form of link between two classes, and for that very reason I tend not to use them when describing source constructs. When I do, I usually use them when there are no direct source code relationships, but the two classes are still somehow related. An example of this might be a situation where the two are responsible for different parts of the same larger algorithm, but a third class uses them both.
It may be useful to see this question I asked: does an association imply a dependency in UML
My understanding is:
Association
public class SchoolClass{
/** This field, of type Bar, represents an association, a conceptual link
* between SchoolClass and Student. (Yes, this should probably be
* a List<Student>, but the array notation is clearer for the explanation)
*/
private Student[] students;
}
Dependency
public class SchoolClass{
private Timetable classTimetable;
public void generateTimetable(){
/*
* Here, SchoolClass depends on TimetableGenerator to function,
* but this doesn't represent a conceptual relationship. It's more of
* a logical implementation detail.
*/
TimetableGenerator timetableGen = new TimetableGenerator();
/*
* Timetable, however, is an association, as it is a conceptual
* relationship that describes some aspect of the data that the
* class holds (Remember OOP101? Objects consist of data and operations
* upon that data, associations are UMLs way or representing that data)
*/
classTimetable = timetableGen.generateTimetable();
}
}
If you want to see the difference at the "code level", in an association between A and B, the implementation of A (or B or both depending on cardinalities, navigability,...) in an OO lang would include an attribute of type B.
Instead in a dependency, A would probably have a method where one of the parameters is of type B. So A and B are not linked but changing B would affect the dependant class A since maybe the way the A method manipulates the object B is no longer valid (e.g. B has changed the signature of a method and this induces a compile error in the class A)
Get it from Wiki: Dependency is a weaker form of relationship which indicates that one class depends on another because it uses it at some point of time. One class depends on another if the latter is a parameter variable or local variable of a method of the former. This is different from an association, where an attribute of the former is an instance of the latter.
So I think the case here is association, if B is a parameter variable or local variable of a method of the A, then they are dependency.
A dependency really is very loosely defined. So there would be no code representation.
Wiki: A dependency is a semantic relationship where a change to the influent or independent modeling element may affect the semantics of the dependent modeling element.[1]
From the OMG Spec: A dependency is a relationship that signifies that a single or a set of model elements requires other model elements for their specification or implementation. This means that the complete semantics of the depending elements is either semantically or structurally dependent on the definition of the supplier element(s).