2

Possible Duplicates:
‘Friends’ equivalent for Java?
Is there a way to simulate the C++ ‘friend’ concept in Java?

In C++ there is a concept of a "friend", which has access to a class's private variables and functions. So if you have:

class Foo {
    friend class Bar;
private:
    int x;
}

then any instance of the class Bar can modify any Foo instance's x member, despite it being private, because Bar is a friend of Foo.

Now I have a situation in Java where this functionality would come in handy, but of course it doesn't exist in Java.

There are three classes: Database, Modifier, Viewer. The Database is just a collection of variables (like a struct). Modifier should be "friends" with Database; that is, it should be able to read and write its variables directly. But Viewer should only be able to read Database's variables.

How is this best implemented? Is there a good way to enforce Viewer's read-only access of Database?

4
  • Well, sort of, but I'm looking for a solution to my problem rather than an exact substitute for the "friend" keyword. Probably something using interfaces but I'm not sure yet. I'm hoping this won't get closed so that I can get a real answer to my question... :(
    – Ricket
    Jun 8, 2010 at 16:42
  • @Robert Harvey: and that was closed as a dupe for stackoverflow.com/questions/182278/…. Jun 8, 2010 at 16:46
  • 1
    ...which brings up good points about the design of the Java language and why friend was not included. But doesn't address my individual situation at all.
    – Ricket
    Jun 8, 2010 at 16:48
  • 1
    In my limited C++ experience, friend was most useful for things like operator overloading, which Java doesn't allow. I believe the exclusion of a friend-like feature from Java was appropriate. It would be used as a crutch and make things miserable for maintenance. I hate the public keyword (on fields) for the same reason. Misuse makes things unmaintainable. Jun 8, 2010 at 18:38

8 Answers 8

2

There are varying opinions on how pure you should be, but to me you shouldn't give anyone access to any fields. Use getters and setters.

If you need to segregate who can read and who can write, you can throw interfaces into the mix. Define an interface with just the getters and you can restrict your viewer to read only.

Robert Harvey added a comment that points to other options, like using a different access modifier for class or package level access.

2
  • Getters and setters implies an ORM layer. That wasn't mentioned.
    – duffymo
    Jun 8, 2010 at 17:11
  • 2
    @duffymo I'm not sure I follow that wrapping field access in methods implies ORM. Jun 8, 2010 at 17:28
1

I don't think this is a good way to implement such a thing.

You should have a data access layer that hides the database. It should expose CRUD operations.

Start with interfaces. Create a ReaderDao that only has finder methods. Then create a GenericDao that extends the ReaderDao and adds the save, insert, and delete methods.

Implementation classes should implement one interface or the other as needed.

Neither one needs to expose the fact that it's a relational database behind the scenes.

4
  • where is a relational database mentioned anywhere in the question?
    – user177800
    Jun 8, 2010 at 16:47
  • 1
    When I see somebody thinking about a Database class, I immediately envision a JDBC-based thing. Not so?
    – duffymo
    Jun 8, 2010 at 17:11
  • +1'd, but to be fair, a Database need not be anything more than a flat text file. Jun 8, 2010 at 18:40
  • @Jonathan - agreed. It could be Alan Turing behind the interface, typing in responses to incoming requests.
    – duffymo
    Jun 8, 2010 at 22:48
1

An inner class has access to all the private members of its container class. Make your getters public and your setters private, make Modifer an inner class of Database. Also make it only creatable from inside of Database through a Factory Method pattern. Probably needs to be a Singleton as well.

A package local class is about as close to a "friend" in C++. Make all your getters public, make your setters package local. Make Modifier be in the same package as Database. The first example is cleaner.

The other idiom is applicable is the Memento pattern.

1

Are you sure this is a good pattern? It directly circumvents encapsulation, one of the main tennets of OO design.

5
  • It maintains encapsulation, although with a bigger capsule. Jun 8, 2010 at 16:45
  • But I'm trying to design with a single responsibility per class... It seems to me that the Database has the responsibility of holding the data, the Viewer has the responsibility of presenting it to the user, and the Modifier has the responsibility of taking input and doing appropriate things to the Database. Maybe I'm thinking of it wrong?
    – Ricket
    Jun 8, 2010 at 16:45
  • @Ricket: Then design using composition. Pass objects around that contain the functionality you require. Jun 8, 2010 at 16:48
  • 1
    Your thinking is right. If you make database, modifier and view interfaces, then have implementations of database and modifier in the same package and use package private fields (or setters), or make the modiifer implementation an inner class of the database implementation. But equally well, have getters on the interface for the database fields, and have public setters on the implementation class.
    – mdma
    Jun 8, 2010 at 16:50
  • what you are calling "modifier" is usually called a "Controller" as in Model View Controller ( MVC ). Each class should be responsible for manipulating its own data. Data classes without methods, just as classes without data (all static methods), isn't very OO ( but of course there are exceptions).
    – user177800
    Jun 8, 2010 at 16:50
1

You could create a nested class.

Imagine you have the ViewClass like this:

class Viewer {
    Database db;
    Viewer( Database db ){
        this.db = db;
    }
    public void whatIsX(){
        System.out.println( db.x() );
    }
}

And define a modifier with a method to modify that database.

abstract class Modifier {
    public void manipulate();
}

You can create the Database with an nested class which have access to the private member, pretty much like friend.

class Database {
    private int x;
    class DatabaseModifier extends Modifier {
        public void manipulate(){
            x++;
        }
    }
    public int x(){
        return x;
    }
}

// To see if works:

class Main{
    public static void main( String [] args ) {
        Database database = new Database();
        Modifier modifier = database.new DatabaseModifier();
        Viewer  viewer = new Viewer( database );
        viewer.whatIsX();
        modifier.manipulate();
        viewer.whatIsX();
    }

}

You can also opt for a static inner class. It could be like this:

class Viewer {
    Database db;
    public Viewer( Database db ){
        this.db = db;
    }
    public void whatIsX(){
        System.out.println( db.x() );
    }
}
class Modifier {
    Database db;
    public Modifier( Database db ){
        this.db = db;
    }
    public void manipulate(){
        //db.x++; doesn't work because db.x is private 
    }
}
class Database {
    private int x;
    static class DatabaseModifier extends Modifier {
        public DatabaseModifier( Database db ){
            super(db);
        }
        @Override 
        public void manipulate(){
            db.x++;
        }
    }
    // public accessor to attribute X
    public int x(){// should be getX() 
        return x;
    }
}

class Main{
    public static void main( String [] args ) {
        Database database = new Database();
        Modifier modifier = new Database.DatabaseModifier( database );
        Viewer  viewer = new Viewer( database );
        viewer.whatIsX();
        modifier.manipulate();
        viewer.whatIsX();
    }

}
1

If you want this kind of access, create an interface to the class that encapsulates the methods you intend to allow only a select few to call. Then create a method where the class passes a private instance of the interface only if the requesting class meets whatever criteria you impose.

A simple example, written with tongue firmly in cheek:

public class Husband {

  private Spouse wife;

  private int cashInWallet;

  public Husband(Wife wife) {
    this.cashInWallet = 20;
    this.wife = wife;
  }

  public WalletAccess getWalletAccess(Object other) {
    if (other instanceof Wife) {
      return new WalletAccessImpl(this);
    }
    return null;
  }

  public interface WalletAccess {
    public int withdrawCash(int requested);
  }

  private WalletAccessImpl implements WalletAccess {

    private Husband hubby;

    private WalletAccessImpl(Husband hubby) {
      this.hubby = hubby;
    }

    public int withdrawCach(int requested) {
      if (this.hubby.wallet > requested) {
         this.hubby.wallet -= requested;
         return requested;
      } else {
         int allCash = this.hubby.wallet;
         this.hubby.wallet = 0;
         return allCash;
      }
  }

}

public class Wife {

  private Husband husband;

  public Wife(Husband husband) {
    this.husband = husband;
  }

  public void consumeCash() {
    Husband.WalletAccess access = husband.getWalletAccess(this);
    int cash = access.withdrawCash(20);
  }

}

More complex examples are possible, but this improves on the friend access pattern, as even individual instances of the "would-be" friend class could be singled out for access (or refusal). For example, it would be trivial to check that the Wife was actually married to this particular husband in this case by rewriting getWalletAccess(...) like so:

public WalletAccess getWalletAccess(Object other) {
  if (other instanceof Wife) {
    Wife someone = (Wife)other;
    if (someone.getHusband() == this) {
      return new WalletAccessImpl(this);
    }
  }
  return null;
}
1

I'd say interfaces are definitely the solution for your problem.

To start with, don't allow anything else to have access to the actual fields of Database. Create methods that each return one of its fields. Then, make DatabaseView an interface that declares each of these methods for reading. Then have Database implement DatabaseView. Finally, you can add methods for writing (setting) the fields that should be settable to Database.

When you have some class that needs to be able to read from the database, such as your Viewer, have it take a DatabaseView. You can then pass in the Database instance itself, but that class will not know about the methods for writing to it. If something else needs to both read and write, such as your Modifier, you can just give it the Database itself. Better yet, Database itself could be an interface that extends DatabaseView and your actual implementation object could be some class that nothing needs to know about.

0

You should rethink how much seperation you really want, this "Modifier should be "friends" with Database; that is, it should be able to read and write its variables directly." is impossible in Java - there can't be different access privileges for direct field accesses.

I assume what you really want is to strongly discourage undesirable access patterns. There are a few ways how this can be achieved:

1.) Put Modifier and Database in the same package and make the "Setters" package protected, thus the set-methods become invisible to your Viewer (as long as Viewer is not in the same package). This is more or less impractical for larger designs.

2.) Seperate the concerns into completely different Projects. Then you can set the projects dependencies that only Modifier gets access to Database at all. This implies that you change your design somewhat, either Database becomes two projects (one with the public-readonly interface and one with the full-access interface), or remove the dependency between Viewer and Database completely and make Viewer access Database only through Modifier. This solution has the advantage that its physically impossible to violate access boundaries (It will not compile in the build).

3.) A solution closer to the actual "friend" class concept would be to have two interfaces, one for read, one for write and Database implements those interfaces using inner classes. Then you can "guard" access to the inner class instances with getters that take the client as an argument like this:

public class Database {
    public DatabaseReadAccess getReadAccess(Viewer viewer) { ... }

    public DatabaseWriteAccess getWriteAccess(Modifier modifier) { ... }
}

This will not prevent a malicious access, but somewhat discourage them. If you want to go one step further, define "Token" classes for Viewer and Modifier and require the token instance for the access getters in Database (then the compiler will enforce the restrictions):

public class ModifierToken {
    ModifierToken(Modifier modifier) {
        // constructor is package protected, so no outsiders can create tokens!
    }
}

I personally would go with the "separate projects" approach, it makes undesirable accesses obvious and violations pop up at latest in the build. I've never tried the "token" approach myself.

Not the answer you're looking for? Browse other questions tagged or ask your own question.