tags:

views:

36

answers:

1

Hello,

May be i am not able to express my doubt properly in this question but still i will try. Basically i created a simple socket based chat program and everything works fine. But i think i have made many patches in it from the design point of view.

I have used ObjectInputStream and ObjectOutputStreams in my program. The question i want to ask is how do i identify the different type of data that i send across the network? say if it is simple String type object i directly add to List<String> chatMessages. Now if want to ban certain users i created an another class :-

public class User{
    private String name;
    private String id;
    //getters and setters
}

This User class means no importance to me till now but i only created it to properly identify the action. Thus if i receive an instanceOf User i can be sure that some user is to be banned. That way i dont have to hardcode strings. I mean first i thought of sending something like "Banned User :" + userName and then i used to check if string startsWith "Banned User :" then i take some action :p. I've created a User class but it means no importance to me in my program.

I want to know whether directly sending strings is good way or create a class for every action that is good. If i am not clear please let me know. If i have hundreds of action do i have to create hundreds of classes so i can check via instanceOf? Say now if i plan to create a BUZZ like facility that is available in yahoo messenger. Should i again create an another class named BUZZ? so it can be identified easily?

+1  A: 

Why not send Action objects across the wire ? You can then subclass these Action objects into (say):

  1. BanUserAction
  2. RecordChat
  3. AddUser

etc. and each object instance contains the data required e.g. BanUser contains the name of the user to be banned.

You wouldn't need to use instanceof since each object would implement a common .act() method. You can then call that method, and you won't have to care which object has been passed to you, since the object itself will take care of what to do (this is a core tenet of OO programming - tell objects to do things for you).

Note that the act() method may require some context passed into it e.g. a reference to the containing chat service.

Brian Agnew