简体   繁体   中英

Good Design for adding business logic to Java Bean

In the following code, does it make sense to have isMatched() in here (in a Value object/java bean) ? What's a good design. btw, I tried compareTo, compare, hashSet etc. by following other posts of Stack overflow and somehow that still does not work for me to remove dups from two lists.

public class SessionAttributes { 

private static final Logger LOGGER = Logger
        .getLogger(SessionAttributes.class);

public SessionNotificationAttributes(String userName, String sessionState) {
    this.userName = userName;
    this.sessionState = sessionState;
}

String userName;
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
// .. getters/setters for sessionState

 public static isMatched (List<SessionAttributes> list1, 
             List<SessionAttributes> list2) {

   //.. custom logic here...
 }

}

==== Entire Code per the ask in comment by David. Look at main() method. This is directly copied pasted from Eclipse to meet http://sscce.org/ requirement ========

package snippet;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;


public class SessionAttributes  implements 
    Comparable<SessionAttributes>, Comparator<SessionAttributes>  {

private static final Logger LOGGER = Logger
        .getLogger(SessionAttributes.class);

public SessionAttributes(String userName, String sessionState) {
    /*
     * String nasPort, String endpointProfile, String audiSessionId, String
     * epsStatus, String securityGroup, String nasIp, String postureStatus,
     * String postureTimestamp) {
     */

    this.userName = userName;
    this.sessionState = sessionState;

    /*
     * this.nasPort = nasPort; this.endpoinProfile = endpointProfile;
     * this.auditSessionId = audiSessionId; this.epsStatus = epsStatus;
     * this.securityGroup = securityGroup; this.nasIp = nasIp;
     * this.postureStatus = postureStatus; this.postureTimestamp =
     * postureTimestamp;
     */

}


String userName;
public String getUserName() {
    return userName;
}
String sessionState;
public String getSessionState() {
    return sessionState;
}
public int compareTo(SessionAttributes o) {
    // TODO Auto-generated method stub
    if (this.getUserName().equals(o.getUserName()) && this.getSessionState().equalsIgnoreCase(o.getSessionState())) {
        return 0;
    }
    return -1;
}

public String toString() {

    return "\n User Name : " + this.getUserName() + " Session State : "
            + getSessionState() + "\n";
}



static boolean isMatched(List<SessionAttributes> list1,
        List<SessionAttributes> list2) {

    if (null == list1 || null == list2)
        return false;

    System.out.println("Actual List=>" + list1);
    System.out.println("Expected List=>" + list2);
    Iterator<SessionAttributes> iterator = list1.iterator();

    while (iterator.hasNext()) {
        SessionAttributes actual = iterator.next();
        Iterator<SessionAttributes> iterator2 = list2
                .iterator();
        while (iterator2.hasNext()) {
            SessionAttributes expected = iterator2.next();
            if (expected.getUserName().equalsIgnoreCase(
                    actual.getUserName())) {
                if (expected.getSessionState().equalsIgnoreCase(
                        actual.getSessionState())) {
                    System.out.println("Element matched - user name-"
                            + expected.getUserName() + " State -"
                            + expected.getSessionState());
                    iterator.remove();
                    iterator2.remove();
                }
            } else {
                System.out.println("Element NOT matched - user name-"
                        + expected.getUserName() + " State -"
                        + expected.getSessionState());

            }
        }
    }

    System.out.println("Lists after removing Dups -");
    System.out.println("list1 =>" + list1.toString() + " list2 -"
            + list2.toString());

    if (list1.size() > 0 || list2.size() > 0)
        return false;

    return true;
}

static void sortLists () {

    List<SessionAttributes> expectedSessionList = new ArrayList<SessionAttributes>();

    SessionAttributes user11 = new SessionAttributes(
            "postureuser1", "STARTED"); //
    // ,null,null,null,null,null,null,null,null);

    SessionAttributes user12 = new SessionAttributes(
            "postureuser1", "DISCONNECTED");

    SessionAttributes user13 = new SessionAttributes(
            "postureuser5", "STARTED");

    // ,null,null,null,null,null,null,null,null);

    expectedSessionList.add(user11);
    expectedSessionList.add(user12);
    expectedSessionList.add(user13);

    List<SessionAttributes> actualSessionList = new ArrayList<SessionAttributes>();

    SessionAttributes user3 = new SessionAttributes(
            "postureuser1", "STARTED");
    // ,null,null,null,null,null,null,null,null);

    SessionAttributes user4 = new SessionAttributes(
            "postureuser1", "DISCONNECTED");

    SessionAttributes user5 = new SessionAttributes(
            "postureuser2", "DISCONNECTED");

    // ,null,null,null,null,null,null,null,null);

    actualSessionList.add(user3);
    actualSessionList.add(user4);
    actualSessionList.add(user5);

    Set<SessionAttributes> removeDups = new HashSet<SessionAttributes>();

    boolean b1 = removeDups.add(user11);
    boolean b2 = removeDups.add(user12);
    boolean b3 = removeDups.add(user13);
    boolean b4 = removeDups.add(user3);
    boolean b5 = removeDups.add(user4);
    boolean b6 = removeDups.add(user5);
    System.out.println(" Set--" + removeDups);

    // removeDups.addAll(expectedSessionList);
    // removeDups.addAll(actualSessionList);

    System.out.println("== Printing Set ====");
    int countMisMatch = 0;

    System.out.println(isMatched(actualSessionList, expectedSessionList));

    // int isMatch = user3.compareTo(user1);
    // System.out.println("Compare=>" + isMatch);
}

static void  sortSet () {

    List<SessionAttributes> expectedSessionList = new ArrayList<SessionAttributes>();

    SessionAttributes user11 = new SessionAttributes(
            "postureuser1", "STARTED"); //
    // ,null,null,null,null,null,null,null,null);

    SessionAttributes user12 = new SessionAttributes(
            "postureuser1", "DISCONNECTED");

    SessionAttributes user13 = new SessionAttributes(
            "postureuser5", "STARTED");

    SessionAttributes user3 = new SessionAttributes(
            "postureuser1", "STARTED");
    // ,null,null,null,null,null,null,null,null);

    SessionAttributes user4 = new SessionAttributes(
            "postureuser1", "DISCONNECTED");

    SessionAttributes user5 = new SessionAttributes(
            "postureuser2", "DISCONNECTED");

    // ,null,null,null,null,null,null,null,null);


    Set<SessionAttributes> removeDups = new HashSet<SessionAttributes>();

    boolean b1 = removeDups.add(user11);
    boolean b2 = removeDups.add(user12);
    boolean b3 = removeDups.add(user13);
    boolean b4 = removeDups.add(user3);
    boolean b5 = removeDups.add(user4);
    boolean b6 = removeDups.add(user5);
    System.out.println(" Set--" + removeDups);

    // removeDups.addAll(expectedSessionList);
    // removeDups.addAll(actualSessionList);

    System.out.println("== Printing Set ====");
    System.out.println(removeDups);

    // int isMatch = user3.compareTo(user1);
    // System.out.println("Compare=>" + isMatch);



}

public int compare(SessionAttributes o1,
        SessionAttributes o2) {

    LOGGER.debug("Compare called -[" + o1.getUserName() + "] ["
            + o2.getUserName() + "]");
    boolean isSameUserName = o1.userName.equalsIgnoreCase(o2.userName);
    boolean isSameState = o1.sessionState
            .equalsIgnoreCase(this.sessionState);

    if (isSameUserName && isSameState)
        return 0;

    return -1;
}

public boolean equals(SessionAttributes obj) {

    if (obj == null || !(obj instanceof SessionAttributes)) {
        return false;
    }
    System.out.println(" In equals==");
    boolean isSameUserName = obj.userName.equalsIgnoreCase(this.userName);
    boolean isSameState = obj.sessionState
            .equalsIgnoreCase(this.sessionState);
    return (isSameUserName && isSameState);
}

public int hashCode() {

    System.out.println(" in hashcode ");
    int hash = 1;
    hash = hash * 17 + this.getUserName().hashCode();
    hash = hash * 31 + this.getSessionState().hashCode();
    // hash = hash * 13 + this.getAuditSessionId().hashCode();
    System.out.println(" hash=>" + hash);
    return hash;
}

public static void main(String[] args) {
    //sortSet();
    sortLists();
}

}

==== Code from David which is supposed to remove dups. Pasting only relevant portion for better comparison. Somehow, this still does not work

    public int compareTo(SessionAttributesFromDavid o) {
          if (this == o) {
            return 0;
        }
        // Null is considered less than any object.
        if (o == null) {
            return 1;
        }

        // Use compareToIgnoreCase since you used equalsIgnoreCase in equals.

        int diff = userName.compareToIgnoreCase(o.userName);
        if (diff != 0)
            return diff;

        diff = sessionState.compareToIgnoreCase(o.sessionState);
        return diff;
    }
 public boolean equals(Object o) {
        // See if o is the same object. If it is, return true.
        if (o == this) {
            return true;
        }

        // The instanceof check also checks for null. If o is null, instanceof will be false.
        if (!(o instanceof SessionAttributes)) {
            return false;
        }

        SessionAttributes that = (SessionAttributes) o;
        return userName.equalsIgnoreCase(that.userName) &&   sessionState.equalsIgnoreCase(sessionState);
    }

Set removeDups = new TreeSet();

        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);

Set--[ User Name : postureuser2 Session State : DISCONNECTED , User Name : postureuser1 Session State : STARTED , User Name : postureuser5 Session State : STARTED , User Name : postureuser1 Session State : DISCONNECTED , User Name : postureuser1 Session State : STARTED ]

I would not create an isMatched method to compare two Lists of SessionAttributes.

I would definitely go with having SessionAttributes implement equals and hashCode. It's crucial that you implement them both and in the same way. If you want to compare both Strings for equality, calculate your hashCode using both Strings. If you don't get equals and hashCode right, none of this will work.

If you want to put SessionAttributes in a SortedSet, I would have SessionAttributes implement Comparable, too.

Also, I would make SessionAttributes immutable, so no setters and declare the two String elements as final. If you do this, you can add SessionAttributes to a Set or Map and you won't have to worry about their values changing. If you don't make them immutable, you have to be sure not to change any of the SessionAttributes values after adding them to the List or Set.

Instead of putting them in a List, I would put them in a Set to ensure that you don't have duplicates within the same Collection of SessionAttributes.

If you want to remove duplicates from one of the Collections, use Collection's removeAll method on it, passing it the other Collection of SessionAttributes.

As a side note, sessionState looks like a variable with a finite number of possible values, so I would consider defining an Enum for it instead of making it a String.

I hope this helps.

Edit:

Your compareTo method is not working because it returns 0 if equal, but -1 if not. It does not fulfill the contract for compareTo. Please read its javadocs .

Below is the SSCCE with some changes and comments. Since in equals, you compare for equality ignoring case, you have to convert the Strings to all upper or lower case in your hashCode method so it will be consistent with equals. You also have to use compareIgnoreCase in your compareTo method for consistency. Since the compareTo method works, you now can simply use a TreeSet to sort a collection of your objects.

I removed the methods you won't need any more and tried to put some helpful comments in the code.

package snippet;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

// You don't need to implement Comparator.
public class SessionAttributes implements Comparable<SessionAttributes> {

    // You typically define member variables at the top of the class definition.
    private final String userName;
    private final String sessionState;

    public SessionAttributes(String userName, String sessionState) {

        // Throw a NullPointerException from the constructor if either of the Strings is null. This way, you know that
        // if the object is constructed successfully, it is free of nulls.
        if (userName == null) {
            throw new NullPointerException("userName must not be null");
        }
        if (sessionState == null) {
            throw new NullPointerException("sessionState must not be null");
        }
        /*
         * String nasPort, String endpointProfile, String audiSessionId, String epsStatus, String securityGroup, String
         * nasIp, String postureStatus, String postureTimestamp) {
         */

        this.userName = userName;
        this.sessionState = sessionState;

        /*
         * this.nasPort = nasPort; this.endpoinProfile = endpointProfile; this.auditSessionId = audiSessionId;
         * this.epsStatus = epsStatus; this.securityGroup = securityGroup; this.nasIp = nasIp; this.postureStatus =
         * postureStatus; this.postureTimestamp = postureTimestamp;
         */

    }

    public String getUserName() {
        return userName;
    }

    public String getSessionState() {
        return sessionState;
    }

    @Override
    public int compareTo(SessionAttributes o) {
        if (this == o) {
            return 0;
        }
        // Null is considered less than any object.
        if (o == null) {
            return 1;
        }

        // Use compareToIgnoreCase since you used equalsIgnoreCase in equals.

        int diff = userName.compareToIgnoreCase(o.userName);
        if (diff != 0)
            return diff;

        diff = sessionState.compareToIgnoreCase(o.sessionState);
        return diff;
    }

    // public int compareTo(SessionAttributes o) {
    // // TODO Auto-generated method stub
    // if (this.getUserName().equals(o.getUserName()) && this.getSessionState().equalsIgnoreCase(o.getSessionState())) {
    // return 0;
    // }
    // return -1;
    // }

    public String toString() {

        return "\n User Name : " + this.getUserName() + " Session State : " + getSessionState() + "\n";
    }

    // public boolean equals(SessionAttributes obj) {
    //
    // if (obj == null || !(obj instanceof SessionAttributes)) {
    // return false;
    // }
    // System.out.println(" In equals==");
    // boolean isSameUserName = obj.userName.equalsIgnoreCase(this.userName);
    // boolean isSameState = obj.sessionState.equalsIgnoreCase(this.sessionState);
    // return (isSameUserName && isSameState);
    // }

    public boolean equals(Object o) {
        // See if o is the same object. If it is, return true.
        if (o == this) {
            return true;
        }

        // The instanceof check also checks for null. If o is null, instanceof will be false.
        if (!(o instanceof SessionAttributes)) {
            return false;
        }

        SessionAttributes that = (SessionAttributes) o;
        return userName.equalsIgnoreCase(that.userName) && sessionState.equalsIgnoreCase(sessionState);
    }

    public int hashCode() {

        System.out.println(" in hashcode ");
        int hash = 1;
        // Since in equals you are comparing for equality and ignoring case, you must convert the Strings to either
        // lower
        // or upper case when computing the hashCode so that it will always be consistent with equals.
        hash = hash * 17 + this.getUserName().toUpperCase().hashCode();
        hash = hash * 31 + this.getSessionState().toUpperCase().hashCode();
        // hash = hash * 13 + this.getAuditSessionId().hashCode();
        System.out.println(" hash=>" + hash);
        return hash;
    }

    public static void main(String[] args) {
        // sortSet();
        // sortLists();

        // expectedSessionList
        List<SessionAttributes> expectedSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user11 = new SessionAttributes("postureuser1", "STARTED"); //
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user12 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user13 = new SessionAttributes("postureuser5", "STARTED");

        expectedSessionList.add(user11);
        expectedSessionList.add(user12);
        expectedSessionList.add(user13);

        System.out.println("expectedSessionList: " + expectedSessionList);

        // actualSessionList
        List<SessionAttributes> actualSessionList = new ArrayList<SessionAttributes>();

        SessionAttributes user3 = new SessionAttributes("postureuser1", "STARTED");
        // ,null,null,null,null,null,null,null,null);

        SessionAttributes user4 = new SessionAttributes("postureuser1", "DISCONNECTED");

        SessionAttributes user5 = new SessionAttributes("postureuser2", "DISCONNECTED");

        // ,null,null,null,null,null,null,null,null);

        actualSessionList.add(user3);
        actualSessionList.add(user4);
        actualSessionList.add(user5);

        System.out.println("actualSessionList: " + actualSessionList);

        // removeDups
        // Use a TreeSet to sort it.
        Set<SessionAttributes> removeDups = new TreeSet<SessionAttributes>();

        boolean b1 = removeDups.add(user11);
        boolean b2 = removeDups.add(user12);
        boolean b3 = removeDups.add(user13);
        boolean b4 = removeDups.add(user3);
        boolean b5 = removeDups.add(user4);
        boolean b6 = removeDups.add(user5);

        System.out.println(" Set--" + removeDups);

        actualSessionList.removeAll(expectedSessionList);
        System.out.println("actualSessionList after removeAll: " + actualSessionList);

    }

}

Output:

expectedSessionList: [ User Name : postureuser1 Session State : STARTED , User Name : postureuser1 Session State : DISCONNECTED , User Name : postureuser5 Session State : STARTED ]

actualSessionList: [ User Name : postureuser1 Session State : STARTED , User Name : postureuser1 Session State : DISCONNECTED , User Name : postureuser2 Session State : DISCONNECTED ]

Set--[ User Name : postureuser1 Session State : DISCONNECTED , User Name : postureuser1 Session State : STARTED , User Name : postureuser2 Session State : DISCONNECTED , User Name : postureuser5 Session State : STARTED ]

actualSessionList after removeAll: [ User Name : postureuser2 Session State : DISCONNECTED ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM