(Mis)Understanding Smalltalk and TDD - testing

I'm trying to learn Smalltalk by doing, so I'm getting a grip on the syntax and style by buiding a simple "Matrix" class.
First of all, I'd be grateful if linked to a good Smalltak tutorial (although this is totally optional), preferably one that doesn't involve using the GUIs (I'd rather type my .sts than fish around the hierarchy explorer to put the methods in their place).
Then, on TDD: For this project I'm calling gst-sunit -f matrix.st -f matrix-test.st BaseMatrixTests, and there's bound to be a better way than that. Is there?
And finally, on asserts: I'm trying to write a method and put asserts within, eg.:
Matrix>>multiplyBy: anotherMatrix [
[ self isNotEmpty ] assert.
"Do Multiplication"
[ result dimensions = (self height)#(anotherMatrix width) ] assert.
]
How can I do that kind of asserts?
Edit: Questions marked explicitly.

Okay, several pieces here.
First, I agree with markusQ, although I completely sympathize: I'd rather be able to write my code in EMACS directly. Bt one of the things about Smalltalk is that it really is very unforgiving of people who don't want to do things the Smalltalk Way. In this case, the Smalltalk Way is to use the browsers.
Second, part of the reason that this is the Smalltalk Way is that Smalltalk is, in a lot of ways, not like other languages. There is really, for all practical purposes, no way to make a "separate" Smalltalk executable: all you can do is make an image of Smalltalk with some relatively small fragments of your own code added in. When you write code using an external editor, as with the syntax you show, you're literally just hand typing an import/export format that is somewhat easier to hand type than XML. But only somewhat.
The moral is, do it the Smalltalk way, with the browsers.
There are some fairly good tutorials for Smalltalk about. I usually use Squeak, so the ones I've seen are using Squeak, as here.
On TDD, you're in luck because Smalltalk was the first place to get xUnit. For Smalltalk, it's called SUnit, and there's a good tutorial here.
You're using assertions there in what appears to be basically a "design by contract" approach. There has been work done on adding design by contract to Smalltalk, as here. For simple assertions, you can add code as in this SO question.
assert: aBlock
"Throw an assertion error if aBlock does not evaluates to true."
aBlock value
ifFalse: [AssertionFailure signal: 'Assertion failed']

I hate to say it ('cause you clearly indicated you don't want to hear it), but get into the IDE. Trying to get your head around smalltalk without using the IDE is like going to Paris and eating at McDonalds. Sure, you're in Paris, but you aren't really exposing yourself to what it's all about.
The key thing about smalltalk is that it's all objects. All the way down (integers and characters are objects) and all the way up (classes, methods, the browsers, the IDE itself) are all objects. If you insist on fighting it you'll have about as much luck as someone wanting to learn how to write C by dragging and dropping things.

If you downloaded Cincom Smalltalk Non-Commercial, there are a number of online tutorials. Start here:
http://www.cincomsmalltalk.com/userblogs/cincom/blogView?content=tutorials
If you downloaded Squeak, start here:
http://wiki.squeak.org/squeak/792
And yes, you really do need to use the IDE to work effectively with Smalltalk.
On testing, load SUnit. In Cincom Smalltalk, it's a loadable component; I've covered loading (and using) it in the video tutorials linked above. I'm not entirely sure how to load it for Squeak, or whether it's part of the base there, but it's certainly available for it.

Other than a request for a tutorial, I don't see a question here. Could you clarify what it is you want to know?
A good list of resources for a beginner can be found in this question: https://stackoverflow.com/questions/481976/is-there-a-dive-into-smalltalk-book

So, about asserts, Squeak Smalltalk already brings Object>>assert:
So, I suppose you can do:
self assert: self isNotEmpty.
self assert: result dimensions equal: (self height)#(anotherMatrix width)
If you are using GNU smalltalk, this might answer how to do assertions there: Smalltalk and Assertions
Niko

Regarding asserts, please look at the other question recently posted.
Regarding TDD, yes, calling gst-sunit -f matrix.st -f matrix-test.st BaseMatrixTests is sort of the best way. Everything else just builds on that, for example these could be thee alternatives:
make all TestCase subclasses for your package inherit from a phony subclass so that you can say AllMatrixTests* on gst-sunit's command line (when you add more tests).
file in matrix.st from matrix-test.st, thus eliminating one -f option.
create a Makefile and package.xml file to create a .star file for your package, as described here. Then you can do just gst-sunit -pMatrix.

It has been suggested above to add #assert: to Object, but rather I'd add #assert to BlockClosure (or whatever [] class is in GNU Smalltalk).
assert
this value ifFalse: [AssertionFailure signal: 'Assertion failed']
and thus use as in
[ value notNil ] assert.
[ value > 0 ] assert.
[ list isEmpty not ] assert.
etcetera.

http://stores.lulu.com/store.php?fAcctID=2748699 (Also you will find the link to download the pdf)

I'd rather type my .sts than fish around the hierarchy explorer to put the methods in their place).
You say this now and I felt the same way until I invested some time into learning how to use these tools.
And I say this as a current user of Vim and former user of Emacs. I really have become quite productive using the class browser and other tools in Pharo now that I've learned the ropes.
That being said, if you really want to go your own way, GNU Smalltalk is the right choice for you.
I would like to point out at this point though that at least Pharo has a Matrix class which you can use for inspiration. Squeak should, too. Perhaps you will learn how useful the class browser is examining Matrix. ;)

Smalltalk Primer is an introduction to The Essentials of Message-Oriented Programming with Smalltalk

Related

How do I use such a line in Kotlin?

I use Python, but I don't know how it works in Kotlin. This is an example
example => exec("""print("hello")""") output => hello
exec("""print("hello")""") output => hello
Kotlin supports JSR-223. You can use the jvm scripting engine to eval kts files.
val engine = ScriptEngineManager().getEngineByExtension("kts")
engine.eval("""print("hello")""")
You need JSR-223 library dependency. Refer to example
implementation("org.jetbrains.kotlin:kotlin-scripting-jsr223:$kotlinVersion")
Short answer: this isn't practical in Kotlin.
Technically, there may be ways, but they're likely to be far more trouble than they're worth; you're far better looking for a different approach to your problem.
Unlike a dynamic (‘scripting’) language like Python, Kotlin is statically-compiled. In the case of Kotlin/JVM, you run the Kotlin compiler to generate .class files with Java bytecode, which is then run by a JVM.
So if you really need to convert a string into code and run it, you'd have to find a way to ensure that a Kotlin compiler is available on the platform where your code is running (which it often won't be; compiled bytecode can run on any platform with a JVM, and most of those won't have Kotlin installed too). You'd then have to find a way to run the compiler; this will probably mean writing your source code out to a file, starting up the compiler program as a separate process (as I don't think there's an API for calling it directly), and checking the results. Then you'd have find the resulting bytecode and load into the JVM, which will probably mean setting up a separate classloader instance.
All of which is likely to be slow, fragile, and very awkward.
(See these previous questions which cover some of the same ground.)
(The details will be different for Kotlin/JS and Kotlin/Native, but I think the principles are roughly the same.)
In general, each computer language has its own approach, its own mind-set and ways of doing things, and it's best to try to understand that and accept that patterns and techniques from one language don't always translate well into another. (In the Olden Days™, it used to be said that a determined programmer could write FORTRAN programs in any language — but only in satire.)
Perhaps if you could explain why you want to do this, and what sort of problem you're trying to solve (probably as a separate question), we might be able to suggest more natural solutions in Kotlin.

How to use the method compile in smalltalk and what parameters can I call it with

I'm trying to add additional functionality to the already defined method "compile" in smalltalk.
here is the code I wrote:
compile: code notifying: requestor trailer: bytes ifFail: failBlock
self log:(self substring: code delimiter: $?).
super compile: code notifying: requestor trailer: bytes ifFail: failBlock.
as you can see compile has 4 parameters, I only know what to give the first parameter when calling the method compile (which is the code as a string).
whatever functionality I added isn't relevant, I'm not able to run any tests for my method because I dont know what to give the last 3 parameters.
So my question here is how can i call my method with the right set of parameters.
This is where I got stuck while writing a test for it:
co := ContractObject new.
code := 'rate: aRate
"?This is the Compiler Comment. Log me?"
hourlyRate := aRate. '.
co compile: code. "3 parameters missing here"
Since you mentioned this is a homework assignment, I will not deprive you of discovering the joys of a live, dynamic system like Smalltalk ;) The best tutor is your image itself. For many messages (including the one in question), there are helpful examples right under your finger tips that can give you clues about how to send them.
To find these real world examples, you "Browse Senders" of the message in question and see how these clients handle the parameters you're confused about. In Squeak (you didn't say which dialect and Pharo doesn't have that message), I see two senders in particular that show how to handle those parameters.
If you don't know how to "browse senders", there are many great references to teach you. For me, "Pharo By Example" is my go-to reference for basic "how do I" questions like yours (or "Squeak By Example" if you're using Squeak). This "fishing pole", if you will, will provide you with faster answers, and more understanding, then begging for fish on SO ;)
n.b. When asking Smalltalk questions, please tag the dialect (e.g. Pharo, Squeak, Amber) because not all dialects have the same set of messages (e.g. Pharo does not have the message you asked about)

How to create documentation for instance variable and methods in Xcode?

I'd like to be able to Alt-Click an instance variable (or a method) as part of the program i created and read what it's purpose is.
The fact that Xcode is telling me the class variable is declared at - is nice but not enough. In this case i'd like to see custom text i typed to describe what an asset really is. Additionally type of the ivar would also be useful to know.
How can this be done? In this case, i wonder what exactly did i mean by assets
I specifically wonder if this information can be viewed from inside Xcode, similar to how Eclipse shows JavaDoc content.
You would need to create a documentation set for your project and install it in Xcode. appledoc can help you with this. This is a command-line tool that can generate documentation in Apple's style from specially formatted comments in your headers. You can also integrate this into your build process with a run script build phase, so that documentation is always up-to-date.
For small projects, it's usually not worth the effort though and you're probably better off just adding comments to your header files and jumping there with Cmd-click (Ctrl+Cmd+left-arrow to go back to where you came from).
You'll probably want to take a look at Apple's documentation on Documentation Sets as well as their article on generating doc sets using Doxygen. The latter is based on Xcode 3.x, so how relevant it is is somewhat questionable, but it'd be a good idea to take a look nonetheless.
That said, if you decide to use Doxygen (alternatives like HeaderDoc can be used for documentation, but I'm not sure what's available to you as far as creating doc sets goes), it looks like the main point is you'll want to throw GENERATE_DOCSET=YES into your Doxyfile (or whatever you decide to call it). After that, you'd just throw the results into ~/Library/Developer/Shared/Documentation/DocSets (according to Doxygen's documentation). I don't know whether this works in Xcode 4.x - it's worth a shot though, and it'd be nice to hear back on it.
Note: most of this was based on this answer by Barry Wark. Figure credit is due there, since I wouldn't have bothered looking into this were it not for his answer.

How to encourage positive developer behavior with an IDE?

The goal of IDEs is increase productivity. They do a great job at that. Refactoring, navigation, inline documentation, auto completion help increase productivity immensely.
But: Every tool is a weapon. The very same IDE helps to produce chunk code. Some IDE features are an invitation to produce bad code: code generation, code formatting tools, refactoring tools.
IDE overuse tends to isolate developers from the necessary details. It is a good thing that you can start working but at some point in your career you have to be able to figure out how to start a process. You can ignore this detail for some time, in the end they are important to write a working product (vs. bolted together stuff that works 90% of the time).
How do you encourage positive behavior of other developers working with an IDE? This is a question as old as copy and paste.
To get the right impression: developers have to have the maximum freedom to mobilize their maximum creativity and motivation. They may use IDEs and all the related tools as they see fit. Nobody should impose draconian measures on them. I don't want to demotivate and force someone to do something. Good behavior has to be encouraged. It has to itch little a bit if you do the wrong thing. In the same line as the SO "accept rate" metric (and reputation). You can ignore it but life is better if you follow the rules.
(The solution should work in a given setting. You can ignore reviews, changing the staffing or more education as potential solutions.)
Train your IDE, instead of being trained by it.
Set up code formatting the way you (or your team) wants it. Heck, even disable it in cases where it makes sense. I've never seen an IDE align something like this with a sensible combination of tabs and spaces (where \t is obviously the tab character):
{
\tcout << "Hello "
\t << (some + long + expression +
\t to_produce_the_word(world))
\t << endl;
}
In languages like Java, you cannot avoid boilerplate. The best option you have is to check generated code, ensuring that it is the same as what you'd have written by hand. Modify it as necessary. Configure your IDE to generate the exact code that you need, if possible. Eclipse is pretty good at this.
Know what's going on under the hood.
Know that your IDE is actually invoking the compiler. Have some insight into the flags that it passes. Be able to invoke the compiler from the command line.
Know about the runtime system. Be aware of the flags that are used or needed to launch your program. Be able to launch the program from a command line.
I think before anyone uses a RAD tool of any type they should be able to write the application from scratch (scratch being wiring together the framework components) in notepad potentially on a computer that is 10 years older than current technology :P. Not knowing the ins and outs of a paradigm/framework leads to bad code from novice developers who only learn things at a mile high view of the platforms they develop for. Perhaps they should do this in a few technologies -- i.e., GTK programming is completely different to MVC which is then also different to SWING and .NET.
I think the end result should be a developer that thinks of the finer details of a problem before they jump to thinking of how they will write an interface to it in a specific RAD environment.
its an open ended question, but...
We have a Eclipse format file that everyone shares, so that we all format the code in the same manor. (Except the one lone InteliJ guy we have).
Everyone shares a dictionary file. It helps to remove all the red lines from the code. Making it look cleaner and more readable.
I run EMMA over the code to find out who isn't testing their code, and then moan at them.
The main problems we face is that most of the team don't know all the features/power of the IDE (eclipse). The didn't know about CTRL + O (twice), or auto code gen. All I can do as a 'hot key wizard' is keep sharing my knowledge with them to help them become more productive.
I look forward to the day when my problem is that they auto gen as much as possible.
Rather than me finding bugs where the wrong value is returned from a getter method due to a typo.
Attempt development (at least occasionally) using only a text editor and launching the compilation, testing, etc. from the command line.
Typing the commands will get tedious very quickly so create scripts or (even better) learn rake, ant, msbuild.
If the IDE does code generation for you and that code generation is really important (such as generating classes from xsd or proxy classes from wsdl), try to find out how to run the code generation from the command line - then hook the code generation into a build (so you'll never be tempted to edit the generated code).
The idea of autoformatting code is great but it usually just turns your code into a mess. If you have less code, minor formatting inconsistencies are just not a big deal.
Adding code quality tools into your build - style checks, class and method sizes, complexity, code duplication, test coverage, etc (complexian, simian, flog, flay, ndepend, ncover, etc.) will discourage IDE generated code.

How would one go about testing an interpreter or a compiler?

I've been experimenting with creating an interpreter for Brainfuck, and while quite simple to make and get up and running, part of me wants to be able to run tests against it. I can't seem to fathom how many tests one might have to write to test all the possible instruction combinations to ensure that the implementation is proper.
Obviously, with Brainfuck, the instruction set is small, but I can't help but think that as more instructions are added, your test code would grow exponentially. More so than your typical tests at any rate.
Now, I'm about as newbie as you can get in terms of writing compilers and interpreters, so my assumptions could very well be way off base.
Basically, where do you even begin with testing on something like this?
Testing a compiler is a little different from testing some other kinds of apps, because it's OK for the compiler to produce different assembly-code versions of a program as long as they all do the right thing. However, if you're just testing an interpreter, it's pretty much the same as any other text-based application. Here is a Unix-centric view:
You will want to build up a regression test suite. Each test should have
Source code you will interpret, say test001.bf
Standard input to the program you will interpret, say test001.0
What you expect the interpreter to produce on standard output, say test001.1
What you expect the interpreter to produce on standard error, say test001.2 (you care about standard error because you want to test your interpreter's error messages)
You will need a "run test" script that does something like the following
function fail {
echo "Unexpected differences on $1:"
diff $2 $3
exit 1
}
for testname
do
tmp1=$(tempfile)
tmp2=$(tempfile)
brainfuck $testname.bf < $testname.0 > $tmp1 2> $tmp2
[ cmp -s $testname.1 $tmp1 ] || fail "stdout" $testname.1 $tmp1
[ cmp -s $testname.2 $tmp2 ] || fail "stderr" $testname.2 $tmp2
done
You will find it helpful to have a "create test" script that does something like
brainfuck $testname.bf < $testname.0 > $testname.1 2> $testname.2
You run this only when you're totally confident that the interpreter works for that case.
You keep your test suite under source control.
It's convenient to embellish your test script so you can leave out files that are expected to be empty.
Any time anything changes, you re-run all the tests. You probably also re-run them all nightly via a cron job.
Finally, you want to add enough tests to get good test coverage of your compiler's source code. The quality of coverage tools varies widely, but GNU Gcov is an adequate coverage tool.
Good luck with your interpreter! If you want to see a lovingly crafted but not very well documented testing infrastructure, go look at the test2 directory for the Quick C-- compiler.
I don't think there's anything 'special' about testing a compiler; in a sense it's almost easier than testing some programs, since a compiler has such a basic high-level summary - you hand in source, it gives you back (possibly) compiled code and (possibly) a set of diagnostic messages.
Like any complex software entity, there will be many code paths, but since it's all very data-oriented (text in, text and bytes out) it's straightforward to author tests.
I’ve written an article on compiler testing, the original conclusion of which (slightly toned down for publication) was: It’s morally wrong to reinvent the wheel. Unless you already know all about the preexisting solutions and have a very good reason for ignoring them, you should start by looking at the tools that already exist. The easiest place to start is Gnu C Torture, but bear in mind that it’s based on Deja Gnu, which has, shall we say, issues. (It took me six attempts even to get the maintainer to allow a critical bug report about the Hello World example onto the mailing list.)
I’ll immodestly suggest that you look at the following as a starting place for tools to investigate:
Software: Practice and Experience April 2007. (Payware, not available to the general public---free preprint at http://pobox.com/~flash/Practical_Testing_of_C99.pdf.
http://en.wikipedia.org/wiki/Compiler_correctness#Testing (Largely written by me.)
Compiler testing bibliography (Please let me know of any updates I’ve missed.)
In the case of brainfuck, I think testing it should be done with brainfuck scripts. I would test the following, though:
1: Are all the cells initialized to 0
2: What happens when you decrement the data pointer when it's currently pointing to the first cell? Does it wrap? Does it point to invalid memory?
3: What happens when you increment the data pointer when it's pointing at the last cell? Does it wrap? Does it point to invalid memory
4: Does output function correctly
5: Does input function correctly
6: Does the [ ] stuff work correctly
7: What happens when you increment a byte more than 255 times, does it wrap to 0 properly, or is it incorrectly treated as an integer or other value.
More tests are possible too, but this is probably where i'd start. I wrote a BF compiler a few years ago, and that had a few extra tests. Particularly I tested the [ ] stuff heavily, by having a lot of code inside the block, since an early version of my code generator had issues there (on x86 using a jxx I had issues when the block produced more than 128 bytes or so of code, resulting in invalid x86 asm).
You can test with some already written apps.
The secret is to:
Separate the concerns
Observe the law of Demeter
Inject your dependencies
Well, software that is hard to test is a sign that the developer wrote it like it's 1985. Sorry to say that, but utilizing the three principles I presented here, even line numbered BASIC would be unit testable (it IS possible to inject dependencies into BASIC, because you can do "goto variable".