PHP - What Is The Purpose Of Refactoring Software?
This will be somewhat of a brain dump with somewhat vague questions. To summarize it right now, something about "refactoring software" has been bugging me. The length of the process, the work it takes, and the time, and the "no immediately visible results" that it produces.
There have been numerous questions on "do I refactor or rewrite". Depending on circumstances, one choice may work better than another, although historically for working projects (projects people are using continuously), refactoring seemed to do better, since it does not break things as much as rewriting does. And when things break all at once, such as when introducing a rewrite (which most likely has different behavior, UI, feel, workflow, etc. etc.), people tend to get upset.
Well, refactoring seems to smooth out the 'upsetness' over a much longer period of time. People change as software changes, and each change is not as abrupt as with a rewrite. There are books written about refactoring software. That process takes time and work, `while not changing the functionality of the software`. Little improvements can be done here and there, but the main point becomes improving the internals of the software without affecting the outside behavior, the user experience. From the business end, *there are no changes!*. We have developers *doing busy work* without showing anything to the business, until perhaps much later. Is that bad? Where I work, I have business people scoff at "what have we been doing" quite regularly, and saying things like "add convertion from one unit system to another? Just put it in!" Which ends up me staring into vastness of legacy code and taking 2-3 weeks to "put it in", what in someone's mind takes a day at the most. But that's cuz maybe I'm slow, but I chose to refactor relevant code first, at least moving View items into respective view containers as a first step. What is the purpose of refactoring software? What, per se does it make better? What expectations can be set? What do I do next time someone says "it is taking too long", other than saying ... cuz I am refactoring! Similar TutorialsHi I have the following code: $image_1 = $value->getElementsByTagName("Image1"); $image1 = $image_1->item(0)->nodeValue; $image_2 = $value->getElementsByTagName("Image2"); $image2 = $image_2->item(0)->nodeValue; $image_3 = $value->getElementsByTagName("Image3"); $image3 = $image_3->item(0)->nodeValue; $filename_1 = basename($image1); $ch = curl_init ($image1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_1,'w'); fwrite($fp, $rawdata); fclose($fp); $filename_2 = basename($image2); $ch = curl_init ($image2); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_2,'w'); fwrite($fp, $rawdata); fclose($fp); $filename_3 = basename($image3); $ch = curl_init ($image3); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec ($ch); curl_close ($ch); $fp = fopen(Mage::getBaseDir('media') . DS . 'import/'.$filename_3,'w'); fwrite($fp, $rawdata); fclose($fp); Would someone help me to refactor this, as I can seem needing $image_4, $image_5 at a later date. Thank you Hi I have a method, which is pretty large. It has a lot of 'duplicate' code and I'd like to refactor it: protected function doSave($con = null) { $choices_1 = $this->getValue('question_1'); $choices_2 = $this->getValue('question_2'); $choices_3 = $this->getValue('question_3'); $choices_4 = $this->getValue('question_4'); $serialized_ = ""; $first = true; foreach($choices_1 as $choice_1) { if(!$first) { $serialized_1 .= ","; } $first = false; $serialized_1 .= $choice_1; } foreach($choices_2 as $choice_2) { if(!$first) { $serialized_2 .= ","; } $first = false; $serialized_2 .= $choice_2; } foreach($choices_3 as $choice_3) { if(!$first) { $serialized_3 .= ","; } $first = false; $serialized_3 .= $choice_3; } foreach($choices_4 as $choice_4) { if(!$first) { $serialized_4 .= ","; } $first = true; $serialized_4 .= $choice_4; } $this->setValue('question_1', $serialized_1); $this->setValue('question_2', $serialized_2); $this->setValue('question_3', $serialized_3); $this->setValue('question_4', $serialized_4); return parent::doSave($con); } You can see most of the arrays have a '_1', '_2' after them, the same goes for the $serialized variables. What I'd like is to maybe have some kind of loop, that will reduce my code down, and rather than me typing all the code above, possibly increment the '_1', '_2' part upto the 5 iterations. Can anyone provide some help/code for me to carry this out? Regards Hi all I have some code I'd like to re-factor Code: [Select] <?php $question_1 = $form->getObject()->getQuestion1(); $question_2 = $form->getObject()->getQuestion2(); ?> <div class="admin"> <div> <?php echo $form['question_1']->renderLabel(); echo $question_1; ?> </div> </div> <div class="adminl"> <div> <?php echo $form['question_2']->renderLabel(); $q2 = str_replace("-", '<br />',$question_2); echo $q2; ?> </div> </div> I'd preferably like some kind of for loop, that will just increment the _1, _2 values. Can anyone offer some help? Thanks I was working on this project earlier on in the year, I have not posted here much. I would like to get it over with and start something else. I have other files which look like the excerpt of code from a file below. I personally think that my code lacks structure and could be organized in a better fashion. I lost most of my progress and am having to backtrack and restore code. Is there a way to re-write this code and make it more readable? Please and thank you!
<?php include('header.php'); require_once('dbcon/dbcon.php'); //include('functions.php'); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // sanitize values before entering them into db, no bad seeds. $username = mysqli_real_escape_string($conn, $_POST['username']); $password = mysqli_real_escape_string($conn, $_POST['password']); $bio = mysqli_real_escape_string($conn, $_POST['bio']); $hashed_password = mysqli_real_escape_string($conn, password_hash($password, PASSWORD_DEFAULT)); $email = mysqli_real_escape_string($conn, $_POST['email_address']); $confirmation_status = 0; /* function sanitizeValues($x, string $postString) { $x = mysqli_real_escape_string($conn, $_POST[$postString]); }*/ $username_query = "SELECT * from profiles001 WHERE username='$username'"; $result = mysqli_query($conn, $username_query); // if username exists do not continue... if (mysqli_num_rows($result) > 0) { header('Location: /soapbox/signup.php'); // let user know that username is taken... } else { // file upload stuff... $file = $_FILES['file']; $fileName = $_FILES['file']['name']; $fileTmpName = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array('jpg', 'jpeg', 'png'); // avatar file constraints checks... if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize < 1000000) { $fileNameNew = uniqid($_SESSION['username'], true) . "." . $fileActualExt; $fileDestination = 'uploads/' . $fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); } else { echo "Your file is too big!"; } } else { echo "There was an error uploading your file" . $fileError . $fileSize; } } else if (!(empty(in_array($fileActualExt, $allowed))) && !($allowed)) { echo "Cannot upload file of this type!"; } mkdir("channel/" . $username); mkdir("channel/" . $username . "/videos"); fopen("channel/" . $username . "/index.php", "w"); $account_open_date = date("Y-m-d h:i:s"); $current_date = date("Y-m-d h:i:s"); //$account_open_date_retrieval_sql_select = "SELECT account_open_date from profile0"; //$account_age = date_diff($row, $current_date); // acct open date - current date = account age //$account_age_result = mysqli_query($conn, $account_open_date_retrieval_sql_select); //$row = mysqli_fetch_assoc($account_age_result); // if-then-else-if statement to get rid of the fileDestination var undefined error when avatar photo is not submitted.... if (!(empty($fileDestination))) { $sqlinsert = "INSERT INTO profiles001 (username, password, email, c_status, doc, avatar, bio) VALUES ('$username', '$hashed_password', '$email', '$confirmation_status', '$account_open_date', '$fileDestination', '$bio')"; } else if (empty($fileDestination)) { $fileDestination = "assets/soap.jpg"; $sqlinsert = "INSERT INTO profiles001 (username, password, email, c_status, doc, avatar, bio) VALUES ('$username', '$hashed_password', '$email', '$confirmation_status', '$account_open_date', '$fileDestination', '$bio')"; } $result = mysqli_query($conn, $sqlinsert); } } ?> I have a class that adds a special PDF page to an existing PDF. The page refers to a specific product and there are products A, B, C, D. Products B, C, D are similar and with a bit of if/then/else magic I can basically reuse the same function for all 3, but product A is different enough to have its own function.
My class looks like this:
class AddPdfPage { function addA(&$pdf, $vars) {} function addB(&$pdf, $vars) {} function addC(&$pdf, $vars) {} function addD(&$pdf, $vars) {} } //The way I call it from within the code right now is like this: AddPdfPage::addC($pdf, $vars); AddPdfPage::addB($pdf, $vars); //the variable below contains the product line -- A, B, C, or D //that's the one I said I could use to merge functions B/C/D into one if I wanted to //I could even include product A if I wanted to even though the code there is different. $vars['productLine']; //The code inside addX() functions is something like: function addX($pdf, $vars) { $pdf->addPage($vars); $pdf->addDescription(".."); //that is different based on each specific product line }Assuming I want to add a page to PDF for a paricular product X, how do I write or structure my code? I am not exactly sure. Do I set it up somehow to use polymorphism? Do I do something else? I assume I don't really want to merge products B/C/D into the same function, even if I could, since they physically represent different product lines, so I might as well keep them as such -- separate. But I may want to use some features of the language to clean up and better up my code. The "how", and what techniques do I use, and what my final code may look like is what my post is about. I am thinking of doing something like: class AddPdfPage() { private $pdf; private $vars; private $productLine; function __construct($pdf, $vars) { $this->pdf = $pdf; $this->vars = $vars; $this->productLine = $vars['productLine']; } public function addPage() { switch($this->productLine) { case 'A': ...break; case 'B': ...break; case 'C': ...break; case 'D': ...break; } } }Use that as a jump start and I guess I could use polymorphism by creating separate classes for each product line and extending some base class, if switch statement is not good.. (http://c2.com/cgi/wi...StatementsSmell) but I feel like I will be polluting my file system with too many classes and not sure if that's exactly a benefit. So just thinking about how to do this. Edited by dennis-fedco, 15 October 2014 - 10:56 AM. Hey guys, what's the purpose of using ob_start() in the begining of the script? I even saw alot of people turning output buffering by default in their php.ini file ! What's the benefit of this action ? Thanks in advance What is the purpose of using an Interface in OOP? I understand the textbook definition, but am not getting the extra value that they provide... TomTees In C, when you dynamically allocate memory, you have to free it, otherwise you face memory leaks:
char *str; str = (char *) malloc(10); free(str);But in most other languages you do not need to worry about this. PHP has a function called unset, which unsets the variable's value. But why would you want to do this, if PHP has a garbage collector that will free variables once they leave scope anyway? I see no point of unset in a scripting language with garbage collection. Can someone tell me what some of the purposes of this would be? global $PHP_SELF; its defined right after a function like this function myFunction(module =' '){ global $PHP_SELF; .... } Thanks Imagine 6 PHP classes (one each for a product line), that have very similar coding structures, that go like this:
//function that computes stuff inside each of 6 files: //they vary slightly from file to file but essentially it is this: function computeFunction { $this->x = new X(); $this->x->calcD(); if ($this->x->dOk) { $this->x->calcE(); $this->x->calcN(); } //more complicated logic that is essentially like above //and by the way! print $this->x->someVarThatIsUsedLater; }Then there is a single class like so : class X { function calcD() { //compute some condition if (<computed condition is met>) $this->dOk = true; else $this->dOk = false; //and by the way $this->someVarThatIsUsedLater = 4; } }Just to bring your attention to it, none of these functions return any result or value, but they nevertheless operate on variables of key interest via side-effects. That is, they modify variables that essentially act like globals, and then use those variables later ($this->dOk and $this->someVarThatIsUsedLater are one more prominent examples). I need to untangle this mess. And make it clean and clear again, and make sense. How do I best proceed? I have been wrestling with some ideas... like $this->dOk, can within reason be turned into a return variable of calcD() function, and then be tested against like if ($this->x->calcD()) and I think it will be reasonable enough. But then there are other functions that don't return anything and just act on variables via side-effects anyway so $this->dOk is one of the lesser troubles... Other than that, what I am thinking of doing is getting rid of these mini-functions (calcE(), calcN(), etc.), removing them as a funciton, and putting their body directly into the code, as a first step to refactor. Many of the computations done inside are just a few lines of code anyway, and the functions kind of hide a lot of side-effects that happen, instead of actually encapsulating the behavior. So while it may be counter-intuitive to dismantle the functions that appear to be doing something that normally can be encapsulated (computing key variables E, N, etc), I think dismantling them will actually clean things up as far as collecting all the side-effects inside a single parent function thereby making them more visible. Caveat: while doing so I will end up with 6 copies of untangled dismantled functions, because dismantling class X and putting its content into each of the 6 product line classes will have that effect. But my hope is that from that point I will see more clearly to start identifying places where I can start to truly encapsulating the behavior via various structures, instead of masking it. Problems / Questions: I would like to but I am not entirely sure that I can skip that step of dismantling functions & the 6x multiplying effect. It's probably the same like skipping steps in solving polynomial equations. Some can do it and some need to list each step of their work. And I am not entirely sure what structures I can replace it with in the end after I dismantle the functions. It also looks like a lot of work. Is there a better way? P.S. I already put tests on computeFunction() for each product line so I can be less paranoid about hacking stuff up. Edited by dennis-fedco, 19 January 2015 - 03:06 PM. I am refactoring entire collective scattered SQL from my legacy codebase, and into separate classes, and looking for some structure to put it into. Right now I have folders effectively called `DataFromDB` - contains classes that accepts whatever parameters are given, and returns pure data back to the user `DAO` - Data Access Object, which takes that raw data from DB and makes sense out of it and prepares it for consumption by the model/business logic layer objects. That is: - src (folder) |- DAO (folder) | - ProductADAO (classes - take data in, return consumable objects out) | - ProductBDAO | - ... | - ProductZDAO |- DataFromDB (folder) | - ProductAData (classes - contain methods to query pure result sets from DB) | - ProductBData | - ... | - ProductZDataWhenever I need to make a new SQL or refactor an old one I do this: What is this SQL doing? Is it operating on `SomeObjectX`? If yes, find/create class called `ObjectX`, and add a method to it, extracting pure data from DB, put it into `DataFromDB` folder. Write the `DAO` object if needed to transform data into a consumable object. Use the object as is in my code. Does this look like a good strategy? Is there a better one? My problem with this one is that before (now) all the SQL is tightly coupled and is included into the multiple business classes. Using the above strategy will mean I am to be creating many many classes, a lot of classes, most likely one for every few SQL statements. The pros is that it seems like I will achieve a level of code modularity that I wanted. Anyone have any experience with something called Moodle at all? I have just been handed it to 'check out', I told them to 'get out'. Rw This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=349065.0 Hey guys, glad I found this forum! I have written a SMS gateway software using VB6 and would like to port to PHP. Is there a way to write it under windows OS? I m using the dio_* commands in PHP and it works, but I dont want to do infinite loop to read incoming sms... right now I do infinite loop until I received +CMTI and the while loop breaks. This is very redundant and costly, is there any way that PHP has a "timer" feature-like in VB6 to check on incoming sms, like say, every second? Thanks guys! I'd like to make myself a poker software that plays itself on all sites. What I don't know is how to get the variables names that I need. I need the cards variables name and the buttons name. Any suggestion how I do it? Or if I could read the from the screen somehow. Thanks Hey, whats going on. i have been using microsoft access for doing all my queries. And they are pretty complex. One query can be the combination of like 8 tables. Do you think Access is the best program to build and run these queries or do you think there is better software out there for building queries. what do you suggest. It seems like Access cant handle very complex queries. A lot of times i have to break the queries down into 3 or 4 queries. i build one, export it to a csv file and then import it back into Access and build a new query on the new imported file. Please let me know what you think. I previously used https://www.phpdoc.org/ (not sure about the part 2 part) but got out of the habit. Wish to change, but had more installation problems than expected. Is it still considered a good solution? If so, any recommendations whether I should install using pear, phar, or other? Thanks Hello,
I'm looking for server management software, preferably free or low cost. I did some googling but could not come up with a good solution for what I need. I manage a small data center and currently keep all server information (IPs, Rack ID, Client ID, etc) in an excel sheet. Does anyone know of something that I can manage the server information more efficiently?
Thanks
I am working on an application and part of the requirements is to restrict the number of users that can log in based on a license. So on install, I will provide a license that allows for 10 user accounts to be created.
If the client requires 50, a different license will be provided that allows 50.
Regards Title: Software Developer Support Lead
About Us:
We are a small, rapidly growing software company based in Wilmington, NC. Our mission is simple: help companies, cities, and school systems save money in bulk fuel acquisition and managing their fleets of vehicles. We are in the fuel industry and we want transparency. We have a diligent, diverse team, which enjoys challenges and the joy of extracting our best in our daily work life.
Who We Are Seeking:
A charismatic individual to serve as a first line of defense for our software team's most valuable product. Ideally you would be happiest when making others happy, especially as it relates to solving elusive problems in code, or logic in a large, web application. If you have high expectations of your work, and that of others, and seek to solve problems at their core, this will be a good fit for you. We strive to deal with difficult problems today so that tomorrow will be a better place.
About The Position:
You will be the primary point of contact between our Operations and Development teams--this means you will have to help refine problems, research code, develop and apply rock-solid solutions, and work well with others in the process. In short, you will be coding, but you will also plan, weighing many potential outcomes, and test the result. You will need to know Linux, MVC frameworks, PHP, MSSQL/MySQL and have a desire to learn: both about technology and from our experiences.
General:
B.S. in Computer Science, or comparable
comfortable in PHP, MySQL/MSSQL, Javascript, jQuery
familiarity with any web framework (Yii experience preferred)
excellent communication skills
explain what is on your mind: with words, pictures, metaphors, UML, etc.
1 or more years of experience desired
Helpful Characteristics:
daily user of Linux (Arch, Fedora, CentOS, for example)
familiarity with vim, tmux
personality traits which would be helpful
methodical in nature
willingness to learn
desire to please
re-enforcing standards, rather than "just get the job done"
ability to work with a team
"Pair Programming" is a daily practice
regular code reviews
group project planning
plan first, act later
asking questions is considered a strength
highly communicative in nature
work with Operations Team to refine the actual problem
determine the source of the problem
propose solution to Software Architect
implement a solution
Please email résumé and cover sheet to development@goenergies.com.
|