GIGO: words unreadable aloud
Mishrogo Weedapeval
 

 

  Monday 28 June 2004
Chapter 5, Exercise 10

This isn't really a solution for this exercise. Scala doesn't offer package access, so it's harder to implement the connections manager to enforce the limit on the number of connections that a client can make. I wrote this version where you can limit the connections as long as your client only uses the getConnection method, but it does not prevent a malicious or impolite client from using the Connection constructor directly. I suspect that there's a simple way to do this with a trait or a mix-in or even a generic class, but I didn't come up with it yet. More thought is required here...

// c5x10_connections.scala -- implements the connections class
//  and its manager, all in the connections package.
package connections;
object ConnectionManager {
    val MAX_CONNECTIONS = 20;
    var conn_nr = 0;
    class Connection {
        def this ( ci : Int ) = { this(); i= ci; }
        var i : Int = _;
    }
    def getConnection : Connection = {
        if (conn_nr >= MAX_CONNECTIONS) {
            null;
        } else {
            conn_nr = conn_nr +1;
            new Connection( conn_nr );
        }
    }
}

And here is a sample client. You'll have to find my W class from a previous posting:

// c5x10_client.scala
package x;
import connections._;
object c5x10_client {
    def main ( args: Array[String] ) = {
        var nr = 0;
        var c = ConnectionManager.getConnection;
        while (null != c) {
            W.rn( "Got Connexn " + nr + ";  its i is " + c.i );
            nr= nr+1;
            c = ConnectionManager.getConnection;
        }
        W.rn( "Problem is, I can make another:" );
        c = new ConnectionManager.Connection( 999 );
        if (c != null) W.rn( "See?  Its i is " + c.i );
    }
}

Here's the output (abridged):

Got Connexn 0;  its i is 1
Got Connexn 1;  its i is 2
Got Connexn 2;  its i is 3
 . . . dot dot dot . . .
Got Connexn 17;  its i is 18
Got Connexn 18;  its i is 19
Got Connexn 19;  its i is 20
Problem is, I can make another:
See?  Its i is 999

11:28:53 PM   comment/     


Click here to visit the Radio UserLand website. Click to see the XML version of this web page. © Copyright 2007 Doug Landauer .
Last update: 07/2/6; 12:40:48 .
Click here to send an email to the editor of this weblog.

June 2004
Sun Mon Tue Wed Thu Fri Sat
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30      
May   Jul

Previous/Next