在软件工程课程中重构java

时间:2013-11-21 11:50:29

标签: java refactoring

所以我参加了软件工程课程,我们的任务是重构。 老师给了我们指示,但我们无法关注它们,所以我希望能从stackoverflow中找到一些帮助。

说明:

  

PurchaseInfoTableModel有一个List(继承自class   SalesSystemTableModel)和Sale有一套。你应该得到   摆脱这段代码重复。最合理的方法是   是使用PurchaseInfoTableModel中的Sale对象来获取   行。要在架构中添加此修改,您需要删除   列出SalesSystemTableModel类中的行并更改方法   public List getTableRows to abstract,那就是   在每个继承类中单独实现。

PurchaseInfoTableModel:

package ee.ut.math.tvt.salessystem.ui.model;

import ee.ut.math.tvt.salessystem.domain.data.Sale;
import ee.ut.math.tvt.salessystem.domain.data.SoldItem;
import ee.ut.math.tvt.salessystem.domain.data.StockItem;
import ee.ut.math.tvt.salessystem.domain.exception.SalesSystemException;
import java.util.ArrayList;
import org.apache.log4j.Logger;

/**
* Purchase history details model.
*/

public class PurchaseInfoTableModel extends SalesSystemTableModel<SoldItem> {
private static final long serialVersionUID = 1L;

private static final Logger log = Logger.getLogger(PurchaseInfoTableModel.class);

private SalesSystemModel model;

public PurchaseInfoTableModel() {
    super(new String[] { "Id", "Name", "Price", "Quantity", "Sum"});
}

public PurchaseInfoTableModel(SalesSystemModel model) {
    this();
    this.model = model;
}

@Override
protected Object getColumnValue(SoldItem item, int columnIndex) {
    switch (columnIndex) {
    case 0:
        return item.getId();
    case 1:
        return item.getName();
    case 2:
        return item.getPrice();
    case 3:
        return item.getQuantity();
    case 4:
        return item.getSum();
    }
    throw new IllegalArgumentException("Column index out of range");
}

@Override
public String toString() {
    final StringBuffer buffer = new StringBuffer();

    for (int i = 0; i < headers.length; i++)
        buffer.append(headers[i] + "\t");
    buffer.append("\n");

    for (final SoldItem item : rows) {
        buffer.append(item.getId() + "\t");
        buffer.append(item.getName() + "\t");
        buffer.append(item.getPrice() + "\t");
        buffer.append(item.getQuantity() + "\t");
        buffer.append(item.getSum() + "\t");
        buffer.append("\n");
    }

    return buffer.toString();
}


public SoldItem getForStockItem(long stockItemId) {
    for (SoldItem item : rows) {
        if (item.getStockItem().getId().equals(stockItemId)) {
            return item;
        }
    }
    return null;
}


/**
 * Add new StockItem to table.
 */
public void addItem(final SoldItem soldItem) throws SalesSystemException {

    StockItem stockItem = soldItem.getStockItem();
    long stockItemId = stockItem.getId();
    SoldItem existingItem = getForStockItem(stockItemId);

    if (existingItem != null) {
        int totalQuantity = existingItem.getQuantity() + soldItem.getQuantity();
        validateQuantityInStock(stockItem, totalQuantity);
        existingItem.setQuantity(totalQuantity);

        log.debug("Found existing item " + soldItem.getName()
                + " increased quantity by " + soldItem.getQuantity());

    } else {
        validateQuantityInStock(soldItem.getStockItem(), soldItem.getQuantity());
        rows.add(soldItem);
        log.debug("Added " + soldItem.getName()
                + " quantity of " + soldItem.getQuantity());
    }

    fireTableDataChanged();
}

/**
 * Returns the total sum that needs to be paid for all the items in the basket.
 */
public double getTotalPrice() {
    double price = 0.0;
    for (SoldItem item : rows) {
        price += item.getSum();
    }
    return price;
}



private void validateQuantityInStock(StockItem item, int quantity)
    throws SalesSystemException {

    if (!model.getWarehouseTableModel().hasEnoughInStock(item, quantity)) {
        log.info(" -- not enough in stock!");
        throw new SalesSystemException();
    }

}


public static PurchaseInfoTableModel getEmptyTable() {
    return new PurchaseInfoTableModel();
}

/**
 * Replace the current contents of the table with the SoldItems of the given Sale.
 * (Used by the history details table in the HistoryTab).
 */
public void showSale(Sale sale) {
    this.rows = new ArrayList<SoldItem>(sale.getSoldItems());
    fireTableDataChanged();
}

}

出售:

package ee.ut.math.tvt.salessystem.domain.data;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Sale object. Contains client and sold items.
 */
@Entity
@Table(name = "SALE")
public class Sale implements DisplayableItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(targetEntity = SoldItem.class, mappedBy = "sale", cascade = CascadeType.ALL)
private Set<SoldItem> soldItems;
private Date sellingTime;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "CLIENT_ID")
private Client client;

/** Empty constructors are used by hibernate */
public Sale() {
}

public Sale(List<SoldItem> goods) {
    this.soldItems = new HashSet<SoldItem>(goods);
    this.sellingTime = new Date();
}

public Client getClient() {
    return client;
}

public void setClient(Client client) {
    this.client = client;
}

public Date getSellingTime() {
    return sellingTime;
}

public void setSellingTime(Date sellingTime) {
    this.sellingTime = sellingTime;
}

public Set<SoldItem> getSoldItems() {
    return soldItems;
}

public void setSoldItems(Set<SoldItem> soldItems) {
    this.soldItems = soldItems;
}

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public void addSoldItem(SoldItem item) {
    item.setSale(this);
    soldItems.add(item);
}

public double getSum() {
    double sum = 0.0;
    for (SoldItem item : soldItems) {
        sum = sum + item.getPrice() * ((double) item.getQuantity());
    }
    return sum;
}

}

SalesSystemTableModel:

package ee.ut.math.tvt.salessystem.ui.model;

import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;

import javax.swing.table.AbstractTableModel;

import ee.ut.math.tvt.salessystem.domain.data.DisplayableItem;

/**
 * Generic table model implementation suitable for extending.
 */
public abstract class SalesSystemTableModel<T extends DisplayableItem> extends
    AbstractTableModel {

private static final long serialVersionUID = 1L;

protected List<T> rows;
protected final String[] headers;

public SalesSystemTableModel(final String[] headers) {
    this.headers = headers;
    rows = new ArrayList<T>();
}

/**
 * @param item
 *            item describing selected row
 * @param columnIndex
 *            selected column index
 * @return value displayed in column with specified index
 */
protected abstract Object getColumnValue(T item, int columnIndex);

public int getColumnCount() {
    return headers.length;
}

@Override
public String getColumnName(final int columnIndex) {
    return headers[columnIndex];
}

public int getRowCount() {
    return rows.size();
}

public Object getValueAt(final int rowIndex, final int columnIndex) {
    return getColumnValue(rows.get(rowIndex), columnIndex);
}

// search for item with the specified id
public T getItemById(final long id) {
    for (final T item : rows) {
        if (item.getId() == id)
            return item;
    }
    throw new NoSuchElementException();
}

public List<T> getTableRows() {
    return rows;
}

public void clear() {
    rows = new ArrayList<T>();
    fireTableDataChanged();
}

public void populateWithData(final List<T> data) {
    rows.clear();
    rows.addAll(data);
}

public void addRow(T row) {
    rows.add(row);
    fireTableDataChanged();
}

public T getRow(int index) {
    return rows.get(index);
}

public List<T> getRows() {
    return rows;
}

}

我的问题是关于删除列表行。我不能删除它吗?如果我这样做,我会留下一堆“无法解决”的变量“行”。显然我需要做出其他更改,但我很难搞清楚。

欢迎所有帮助,并提前致谢。

0 个答案:

没有答案