Use Class Variables As Constants In Scala - syntax

I'm working to learn Scala--coming from a C++ background. I am trying
to write a small class for a task tracking app I'm hacking together to
help me to learn how to code Scala.
This seems as if it should be simple but for some reason it's eluding me:
package com.catenacci.tts
class Task(val ID:Int, val Description:String) {
val EmptyID = 0
val EmptyDescription = "No Description"
def this() = this(EmptyID,EmptyDescription)
def this(ID:Int)={
this(ID,EmptyDescription)
}
def this(Description:String)={
this(EmptyID,Description)
}
}
I'm trying to provide three constructors: Task(ID, Description),
Task(ID), Task(Description). In the latter 2 cases I want to
initialize the values to constant values if one of the values isn't
provided by the caller. And I want to be able to check this outside
of the class for unit testing purposes. So I figured putting in two
public vals would allow me to check from outside of the class to make
sure that my state is what I expect.
However, for some reason this code will not compile. I get the following error:
error: not found: value EmptyID
and
error: not found: value EmptyDescription
So what am I missing? I'm working through "Programming in Scala" so
if there's a simple answer to this question, please give me page
numbers. I don't mind reading but going by the code on page 60 and
page 62, I can't see why this code is failing.
I'm guessing it has something to do with the fact that these are
constructor methods and that possibly the two vals are not initialized
until the end of the constructors. If that's the case is there some
way to get the effect I'm looking for?

You can define the constants in a companion object:
object Task {
val EmptyID = 0
val EmptyDescription = "No Description"
}
And then reference them as Task.EmptyID and Task.EmptyDescription.
I think Scala 2.8 has support for default values.

See Germán for the answer. This happens because a constructor is technically part of the static scope. In other words, the constructor cannot access any instance members because the instance hasn't been created yet. Any "class members" are actually instance members, which is why the code in the question does not work. Germán's answer fixes this by moving the two relevant values into the companion object, which effectively makes them static members of the Task class (not really, but you can think of it that way).

In "Programming in Scala", see section 6.7 where the chaining of constructor calls is explained. The primary constructor is described as "the single point of entry of a class".

Related

What is the relation in (class diagrams) between those 3 classes?

I have the code as follow :
class Synchronization
def initialize
end
def perform
detect_outdated_documents
update_documents
end
private
attr_reader :documents
def detect_outdated_documents
#documents = DetectOutdatedDocument.new.perform
end
def update_documents
UpdateOutdatedDocument.new(documents).perform
end
#documents is an array of Hashes I return from a method in DetectOutdatedDocument.
I then use this array of Hash to initialize the UpdateOutdatedDocument class and run the perform method.
Is something like this correct?
Or should I use associations or something else?
Ruby to UML mapping
I'm not a Ruby expert, but what I understand from your snippet given its syntax is:
There's a Ruby class Synchronization: That's one UML class
The Ruby class has 4 methods initialize, perform, detect_outdated_documents, and update_documents, the two last being private. These would be 4 UML operations.
initialize is the constructor, and since it's empty, you have not mentioned it in your UML class diagram, and that's ok.
The Ruby class has 1 instance variable #documents. In UML, that would be a property, or a role of an association end.
The Ruby class has a getter created with attr_reader. But since it is in a private section, its visibility should be -. This other answer explains how to work with getters and setters elegantly and accurately in UML (big thanks to #engineersmnky for the explanations on getters in Ruby, and for having corrected my initial misunderstanding in this regard)
I understand that SomeClass.new creates in Ruby a new object of class SomeClass.
Ruby and dynamic typing in UML
UML class diagrams are based on well-defined types/classes. You would normally indicate associations, aggregations and compositions only with known classes with whom there’s for sure a stable relation. Ruby is dynamically typed, and all what is known for sure about an instance variable is that it's of type Object, the highest generalization possible in Ruby.
Moreover, Ruby methods return the value of the latest statement/expression in its execution path. If you did not care about a return value of an object, you'd just mark it as being Object (Thanks engineersmnky for the explanation).
Additional remarks:
There is no void type in UML (see also this SO question). An UML operation that does not return anything, would just be an operation with no return type indicated.
Keep also in mind that the use of types that do not belong to the UML standard (such as Array, Hash, Object, ...) would suppose the use of a language specific UML profile.
Based on all this, and considering that an array is also an Object, your code would lead to a very simple UML diagram, with 3 classes, that are all specializations of Object, and a one-to-many association between Synchronization and Object, with the role #documents at the Object end.
Is it all what we can hope for?
The very general class diagram, may perhaps match very well the implementation. But it might not accurately represent the design.
It's your right to model in UML a design independently of the implementation. Hence, if the types of instance variables are known by design (e.g. you want it to be of some type and make sure via the initialization and the API design that the type will be enforced), you may well show this in your diagram even if it deviates from the code:
You have done some manual type inferencing to deduce the return type of the UML operations. Since all Ruby methods return something, we'd expect for all Ruby methods at least an Object return type. But it would be ok for you not to indicate any return type (the UML equivalent to void) to express taht the return value is not important.
You also have done some type inference for the instance variable (UML property): you clarify that the only value it can take is the value return by DetectOutdatedDocument.new.perform.
Your diagram indicates that the class is related to an unspecified number of DetectOutdatedDocument objects, and we guess it's becaus of the possible values of #documents. And the property is indicated as an array of objects. It's very misleading to have both on the diagram. So I recommend to remove the document property. Instead, prefer a document role at the association end on the side of DetectOutdatedDocument. This would greatly clarify for the non-Ruby-native readers why there is a second class on the diagram. :-) (It took me a while)
Now you should not use the black diamond for composition. Because documents has a public reader; so other objects could also be assigned to the same documents. Since Ruby seems to have reference semantic for objects, the copy would then refer to the same objects. That's shared aggregation (white diamond) at best. And since UML has not defined very well the aggregation semantic, you could even show a simple association.
A last remark: from the code you show, we cannot confirm that there is an aggregation between UpdateOutdatedDocument and DetectOutdatedDocument. If you are sure there is such a relationship, you may keep it. But if it's only based on the snippet you showed us, remove the aggregation relation. You could at best show a usage dependency. But normally in UML you would not show such a dependency if it is about the body of a method, since the operation could be implemented very differently without being obliged to have this dependency.
There is no relation, UML or otherwise, in the posted code. In fact, at first glance it might seem like a Synchronization has-many #documents, but the variable and its contents are never defined, initialized, or assigned.
If this is a homework assignment, you probably need to ask your instructor what the objective is, and what the correct answer should be. If it's a real-world project, you haven't done the following:
defined the collaborator objects like Document
initialized #documents in a way that's accessible to the Synchronization class
allowed your class method to accept any dependency injections
Without at least one of the items listed, your UML diagram doesn't really fit the posted code.

How to check where a who calls this method?

I have a custom method in an ABAP class.
I used the 'Where used' tool to show where the class is called from but, as it turns out, it's called from somewhere else I didn't expect.
So what's the best way of showing a complete list of everything that calls the method?
Due to the wonders of object-oriented programming, an instance of a class can hide behind a reference to one of its base classes or interfaces it implements. For example:
DATA foo TYPE REF TO z_my_interface.
CREATE OBJECT foo TYPE z_my_class.
" lots of more code
foo->bar( ).
You can not find this reference to z_my_class->foo with its "Where Used" list, because at that code location foo could also be a reference to an instance of any other class which implements z_my_interface. But you might be able to find this if you don't just look at the where-used list of the method but at the where-used list of the whole class or the interface / base class which declares the method.
And then there are evil dynamic programming tricks like this which determine methods and classes at runtime:
DATA foo TYPE REF TO object.
CONSTANTS: classname TYPE string VALUE 'Z_MY_CLASS',
methodname TYPE string VALUE 'BAR'.
CREATE OBJECT foo TYPE (classname).
CALL METHOD foo->(methodname).
There is no chance to find this with the where-used tool. But if the class- and/or method name does actually appear in the code (it might not, for example if they are read from a customizing table) then you can use the report RS_ABAP_SOURCE_SCAN. This handy little tool allows you to select a set of ABAP programs and search for strings (and even regular expressions) within their sourcecodes.
However, if you know the method gets called when you do something specific as a user and just want to know where, then it can be easier to just set a debugger breakpoint in the method, run into it and check the call stack.
Sorted using the code_scanner transaction.

Is There a Standard Syntax for Mocha's (BDD) Describe, and if so What is the Logic Behind It?

If you look at the examples on the official Mocha page, you'll see that they use the following describe syntax (for their BDD mode):
describe('Array', function() {
describe('#indexOf()', function () {
However, I can't seem to find anything (on the Mocha site or elsewhere) explaining why the second describe should be #indexOf() and not #indexOf or just indexOf. #indexOf seems to be a pretty common format (I've seen it in OSS code), but I've never seen anyone add parenthesis before. Then again, the Mocha people certainly know a lot more about testing than I do, so I've got to figure they use that syntax for a reason.
So, my question is, can anyone point me towards a resource that either:
is a "source of truth" (eg. somewhere on the Mocha site, or on some major testing site) saying that ____ is the default convention for describe (I realize this might not even be a JS source at all, since I know a lot of this stuff originated in RSpec)
describes the practical benefits of adopting this syntax
And if you could provide one of each (or one that does both) that'd be even better. Alternatively I'd also love a direct answer (ie. not a link to a resource), if its possible to just explain it directly.
Basically I just want to understand where this syntax came from and why I should use it (with both "because smart person ____ said so" and "because of practical reason ____" being legitimate answers).
I don't have an authoritative source regarding this. The #indexOf() is not special as far as Mocha is concerned. It treats it as it would treat any other text.
The only similar syntax I've ever encountered is JSDoc's syntax for referring to parts of a class. The #name syntax is used to refer to members that are used on instances of a class. In the JSDoc 3 syntax Array#indexOf is a meaningful expression which refers to the indexOf method used on an Array instance. Note how I do not have the parentheses though. I don't recall ever using parentheses in JSDoc 3.
The [documentation](MyConstructor#instanceMember
MyConstructor.staticMember
MyConstructor~innerMember) gives an example of instance, static and inner functions:
/** #constructor */
Person = function() {
this.say = function() {
return "I'm an instance.";
}
function say() {
return "I'm inner.";
}
}
Person.say = function() {
return "I'm static.";
}
var p = new Person();
p.say(); // I'm an instance.
Person.say(); // I'm static.
// there is no way to directly access the inner function from here
And shows how you would refer to them in JSDoc 3 documentation:
Person#say // the instance method named "say."
Person.say // the static method named "say."
Person~say // the inner method named "say."
JSDoc 3 reused this syntax (with one modification for inner methods) from JSDoc 2, which, as far as I can tell, predates Mocha.

ruby: check if two variables are the same instance

I have a class Issue in which each class has a key field. Because keys are meant to be unique, I overrode the comparison operator such that two Issue objects are compared based on key like so:
def ==(other_issue)
other_issue.key == #key
end
However, I am dealing with a case in which two there may be two variables referring to the same instance of an Issue, and thus a comparison by key would not distinguish between them. Is there any way I could check if the two variables refer to the same place?
According to the source, the Object#equal? method should do what you're trying to do:
// From object.c
rb_obj_equal(VALUE obj1, VALUE obj2)
{
if (obj1 == obj2) return Qtrue;
return Qfalse;
}
So the ruby code you would write is:
obj1.equal?(obj2)
No, not really. And that is Good Thing™.
A basic tenet of object-orientation is that one object can simulate another object. If you could tell whether or not two objects are the same object ("Reference Equality"), then you could tell apart the simulation from the real thing, thus breaking object-orientation … which, for an object-oriented language like Ruby is not so good.
The default implementation of Object#equal? does indeed check for reference equality, but, just like every other method in Ruby, it can be overridden in subclasses or monkey-patched, so there is no way to guarantee that it will actually check for reference equality. And that is how it should be.

BDD/TDD: can dependencies be a behavior?

I've been told not to use implementation details. A dependency seems like an implementation detail. However I could phrase it also as a behavior.
Example: A LinkList depends on a storage engine to store its links (eg LinkStorageInterface). The constructor needs to be passed an instance of an implemented LinkStorageInterface to do its job.
I can't say 'shouldUseLinkStorage'. But maybe I can say 'shouldStoreLinksInStorage'.
What is correct to 'test' in this case? Should I test that it stores links in a store (behavior) or don't test this at all?
The dependency itself is not an expected behavior, but the actions called on the dependency most certainly are. You should test the stuff you (the caller) know about, and avoid testing the stuff that requires you to have intimate knowledge of the inner workings of the SUT.
Expanding your example a little, lets imagine that our LinkStorageInterface has the following definition (Pseudo-Code):
Interface LinkStorageInterface
void WriteListToPersistentMedium(LinkList list)
End Interface
Now, since you (the caller) are providing the concrete implementation for that interface it is perfectly reasonable for you to test that WriteListToPersistentMedium() gets called when you invoke the Save() method on your LinkList.
A test might look like this, again using pseudo-code:
void ShouldSaveLinkListToPersistentMedium()
define da = new MockLinkListStorage()
define list = new LinkList(da)
list.Save()
Assert.Method(da.WriteListToPersistentMedium).WasCalledWith(list)
end method
You have tested expected behavior without testing implementation specific details of either your SUT, or your mock. What you want to avoid testing (mostly) are things like:
Order in which methods were called
Making a method, or property public just so you can check it
Anything that does not directly involve the expected behavior you are testing
Again, a dependency is something that you as the consumer of the class are providing, so you expect it to be used. Otherwise there is no point in having that dependency in the first place.
LinkStorageInterface is not an implementation detail - its name suggests an interface to to an engine. In which case the name shouldUseLinkStorage has more value than shouldStoreLinksInStorage.
That's my 2 pennies worth!

Resources