How can I avoid duplicate code in the if-else chain? - apex

I have the following code snippet
if(!setPass){
this.teacher = Ev_TeacherTestUtil.createTeacher
(sess, 'TestTeacher1',
Ev_TeacherService.NOMINATED,
Ev_TeacherService.EMPLOYEE_NO,
Ev_TeacherService.PASS_NO);
}else{
this.speaker = Ev_TeacherTestUtil.createTeacher
(sess, 'TestTeacher1',
Ev_TeacherService.NOMINATED,
Ev_TeacherService.EMPLOYEE_NO,
Ev_TeacherService.PASS_YES);
}
The only change in the else condition is Ev_TeacherService.PASS_YES (in the if condition it is set to Ev_TeacherService.PASS_NO), the rest is just being duplicated! How can I avoid this? Thanks in advance for the help!

How about this :
this.teacher = Ev_TeacherTestUtil.createTeacher
(sess, 'TestTeacher1',
Ev_TeacherService.NOMINATED,
Ev_TeacherService.EMPLOYEE_NO,
(setPass) ? Ev_TeacherService.PASS_YES : Ev_TeacherService.PASS_NO);

this.teacher = Ev_TeacherTestUtil.createTeacher
(sess, 'TestTeacher1',
Ev_TeacherService.NOMINATED,
Ev_TeacherService.EMPLOYEE_NO,
(!setPass)?Ev_TeacherService.PASS_YES:Ev_TeacherService.PASS_NO);

I'm not sure which language is this, but you can usually use
public void main() {
if(!setPass){
this.teacher = create(false);
} else {
this.speaker = create(true);
}
}
public Teacher create(boolean setPass) {
return Ev_TeacherTestUtil.createTeacher
(sess, 'TestTeacher1',
Ev_TeacherService.NOMINATED,
Ev_TeacherService.EMPLOYEE_NO,
setPass ? Ev_TeacherService.PASS_YES : Ev_TeacherService.PASS_NO);
}
In other words, single line if statement, should solve this.
setPass ? Ev_TeacherService.PASS_YES : Ev_TeacherService.PASS_NO
Other option, is builder pattern
http://en.wikipedia.org/wiki/Builder_pattern

Related

how to check if an object is not in the scene

I wanted this code to send a "no" when it doesn't find the object "Player_1" but when it finds it, it sends "yes" in the debug log but when I remove it simply
don't send "no"
{
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
public
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
if (_objeto1 == true)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
}
Try this:
public GameObject _objeto1;
public GameObject _objeto2;
public float _distancia1;
void Start()
{
_distancia1 = 0;
}
void Update()
{
_objeto1 = GameObject.Find("Player_1");
if (_object1 != null)
{
_distancia1 = Vector3.Distance(_objeto1.transform.position, _objeto2.transform.position);
}
if (_objeto1 != null)
{
Debug.Log("sim");
}
else
{
Debug.Log("nao");
}
}
Thank you for question!
GameObject.Find() returns GameObject if it's exist on scene and returns "null" when there is no object. So you can use if statment to check if _objeto1 is null.
_objeto1 = GameObject.Find("Player_1");
if (_objeto1 == null)
{
Debug.Log("nao");
}
else
{
Debug.Log("Yes");
}
And don't use '_' for public fields. It's bad practice. You can use it for private fields.

yii lucene index doesn't exists

I want to do the SearchBox on my webapp. I followed tutorial: SeachBox Tutorial excatly, did everything author mentioned, and I'm getting an error:
Index doesn't exists in the specified directory.
My SearchController:
<?php
class SearchController extends Controller
{
private $_indexFiles = 'runtime.search';
public function init(){
Yii::import('application.vendors.*');
require_once('Zend/Search/Lucene.php');
parent::init();
}
/**
* Search index creation
*/
public function actionCreate()
{
$index = Zend_Search_Lucene::create($_indexFiles);
$index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);
$posts = News::model()->findAll();
foreach($news as $news){
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Text('title',
CHtml::encode($news->name), 'utf-8')
);
$doc->addField(Zend_Search_Lucene_Field::Text('link',
CHtml::encode($news->url)
, 'utf-8')
);
$doc->addField(Zend_Search_Lucene_Field::Text('content',
CHtml::encode($news->description)
, 'utf-8')
);
$index->addDocument($doc);
}
$index->commit();
echo 'Lucene index created';
}
public function actionSearch()
{
$this->layout='column2';
if (($term = Yii::app()->getRequest()->getParam('q', null)) !== null) {
$index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles));
$results = $index->find($term);
$query = Zend_Search_Lucene_Search_QueryParser::parse($term);
$this->render('search', compact('results', 'term', 'query'));
}
}
}
Any ideas to solve this problem? Thanks for any help.
EDIT: OK, the solution was quite obvious. Index wasn't writed because it wasn't really declared...
this private $_indexFiles = 'runtime.search'; before init should just be in actionCreate function - then it works
Thanks for your help!
You have a typo:
$posts = News::model()->findAll();
foreach($news as $news){
Should be:
$posts = News::model()->findAll();
foreach($posts as $news){

filtering datagrid using combobox

I had created a datagridview like this
public void gridviewsetup()
{
tbl_Aplication.Columns.Add("1", "Empid");
tbl_Aplication.Columns.Add("2", "Emp no");
tbl_Aplication.Columns.Add("3", "Emp Name");
tbl_Aplication.Columns.Add("4", "Department ");
tbl_Aplication.Columns.Add("5", "Designation");
tbl_Aplication.Columns.Add("6", "Shift");
tbl_Aplication.Columns.Add("7", "Start Time");
tbl_Aplication.Columns.Add("8", "End Time");
tbl_Aplication.Columns.Add("9", "OT");
tbl_Aplication.Columns.Add("10", "Reversed Swipe Out");
tbl_Aplication.RowTemplate.Height = 18;
}
and i had populated a data table to fill the data dgridview
public void filldatagrid()
{
if (cmb_dept.Text.Trim() != "")
{
Datatable employedata = empreg.getallemployeeshiftdetails(int.Parse(cmb_dept.SelectedValue.ToString()), Program.LOCTNPK);
tbl_Aplication.Rows.Clear();
tbl_Aplication.DataSource = null;
for (int i = 0; i < employedata.Rows.Count; i++)
{
tbl_Aplication.Rows.Add();
tbl_Aplication.Rows[i].Cells[1].Value = employedata.Rows[i][0];
tbl_Aplication.Rows[i].Cells[2].Value = employedata.Rows[i][1];
tbl_Aplication.Rows[i].Cells[3].Value = employedata.Rows[i][2];
tbl_Aplication.Rows[i].Cells[4].Value = employedata.Rows[i][3];
tbl_Aplication.Rows[i].Cells[5].Value = employedata.Rows[i][4];
tbl_Aplication.Rows[i].Cells[6].Value = employedata.Rows[i][5];
tbl_Aplication.Rows[i].Cells[7].Value = employedata.Rows[i][6];
tbl_Aplication.Rows[i].Cells[8].Value = employedata.Rows[i][7];
tbl_Aplication.Rows[i].Cells[9].Value = 0;
tbl_Aplication.Rows[i].Cells[10].Value = employedata.Rows[i][7];
}
}
}
now i want to filter data in the datagrid with the designation selected in the combobox without going back to database ,I did it like this but it shows error
private void cmb_designation_SelectedIndexChanged(object sender, EventArgs e)
{
if (desgflag != 0)
{
if (cmb_dept.SelectedValue!=null )
{
// tbl_Aplication.DataSource = employedata;
((DataTable)tbl_Aplication.DataSource).DefaultView.RowFilter = " designationnName like '%" + cmb_dept.Text.Trim() + "%' ";
}
}
}
I had done it
private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)
{
tbl_DestinationData.DataSource = dt;
}
else
{
((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";
}
}
catch (Exception )
{
throw;
}
}

my commands using lwuit not working properly ..

I am trying to move between 3 forms. 1 is main form and 2 other simple forms.
I have commands in the soft keys but they are not working...
below is my code...
public class checkOutComponents extends MIDlet implements ActionListener
{
private Form appForm;
private Form f1;
private Form f2;
Command GoTof1 = new Command("GoTof1");
Command GoTof2 = new Command("GoTof2");
Command GoToMainForm = new Command("GoToMainForm");
public void startApp()
{
Display.init(this);
appForm = new Form("Check These Components!! ");
appForm.setLayout(new BorderLayout());
appForm.addCommand(GoTof1);
appForm.addCommand(GoTof2);
appForm.addComponent(BorderLayout.CENTER, formContainer);
appForm.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional)
{
}
public void actionPerformed(ActionEvent event)
{
Command eventCmd = event.getCommand();
Form f = Display.getInstance().getCurrent();
boolean sentido = false;
if (eventCmd == GoTof1)
{
sentido = true;
Image i1 = null;
try
{
i1 = Image.createImage("/hello/1.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab1 = new Label(i1);
f1.addComponent(lab1);
f1.addCommand(GoTof2);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f1.show();
}
else if (eventCmd == GoTof2)
{
sentido = false;
Image i2 = null;
try
{
i2 = Image.createImage("/hello/2.jpeg");
}
catch (IOException ex)
{
ex.printStackTrace();
}
Label lab2 = new Label(i2);
f1.addComponent(lab2);
f1.addCommand(GoTof1);
f1.addCommand(GoToMainForm);
f.setTransitionOutAnimator(Transition3D.createCube(300, sentido));
f2.show();
}
else if(eventCmd == GoToMainForm)
{
appForm.showBack();
}
}
}
Kindly help regarding this.
Thanks in advance and regards,
Swati
Add command listener to the form appForm.
appForm.addCommandListener(this);

Testcase using NUnit

Folks, I am new to writing testcases for the methods. Here I have a InsertMethod for which I want to write testcase using NUnit testing framework. Help me in writing the testcase for the method below :
public bool insertUser(String FirstName, String LastName)
{
bool result = false;
SqlConnection myconn = new SqlConnection();
SqlCommand mycmd = new SqlCommand();
try
{
myconn.ConnectionString = "Data Source=BABU-PC;Initial Catalog=contacts;Integrated Security=True";
myconn.Open();
mycmd.Connection = myconn;
mycmd.CommandText = "InsertUser";
mycmd.CommandType = CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "#FirstName";
param1.DbType = DbType.AnsiString;
param1.Size = 8000;
param1.Value = FirstName;
mycmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter();
param2.ParameterName = "#LastName";
param2.DbType = DbType.AnsiString;
param2.Size = 8000;
param2.Value = LastName;
mycmd.Parameters.Add(param2);
int i = 0;
i = mycmd.ExecuteNonQuery();
if (i > 0)
{
result = true;
}
else
{
result = false;
}
}
catch (Exception err)
{
Console.WriteLine(err.Message.ToString());
return false;
}
finally
{
mycmd.Dispose();
myconn.Close();
myconn = null;
}
return result;
}
Thanks
SBM
Cellfish is right. Don't think about the code, think about what the method is supposed to do. Without even looking at your code, I'd do this kind of test:
1- Preparation
lastName = "LastName"
firstName = "FirstName"
Then try to fetch a user with firstName and lastName and make sure that it's not already there.
2- Execute
InsertUser(firstName, lastName)
3- Check
Make sure InsertUser return true
Try to fetch a user with firstName and lastName and make sure that it is there with the correct values.