FAQ Database Discussion Community


Can you pass an Angular service as a parameter to a function provided by another Angular service?

javascript,angularjs,refactoring,angular-services
I have a bunch of functions throughout my Angular app using mostly the same code. So I decided to create a service which is made of the frequently duplicated code, and takes as parameters the differences. One of the primary and few differences each of the duplicate functions have is...

Clean up chain of dependent calls

ruby,refactoring
How to make cleaner such code: def some_public_method(arg) var1 = private_method(arg) var2 = private_method1(var1) if var1 var3 = private_method2(var2) if var2 var4 = private_method3(var3) if var3 private_method4(var4) if var4 end UPDATE: sorry, forgot to change method names...

How to globally replace one annotation type with another?

java,eclipse,refactoring,findbugs
I would like to replace one annotation type with another, throughout a large codebase. This requires updating import statements and the annotations themselves. Is there a mechanism to do this in the Eclipse IDE other than possibly naive textual search/replace? For example: import edu.umd.cs.findbugs.annotations.NonNull; ... public @NonNull Integer foo( @NonNull...

How to refactor logic for better error handling?

c++,validation,input,refactoring
I wrote this short console program for my introductory C++ class, and technically it functions properly and I have met all the criteria. However, I dislike that the console window closes after a failed input, and would like to learn how I could refactor this program so that failed input...

Setting the strategy in a Strategy Pattern

php,design-patterns,refactoring
I might have implementing this wrong as I cannot figure out a solid way of setting which strategy to use in my implementation of the Strategy Pattern. I'm not a big fan of writing it "statically", perhaps there is another way. Backstory: I've done two (2) implementations (soap + http)...

if and else if do the same thing

if-statement,refactoring,logic
I'm trying to refactor an if-else chain that doesn't look particularly good. My common sense is telling me that I should be able to call my method only once but I can't figure out an elegant way to do it. Currently what I have is: if(condition1) do method1; else if(condition2)...

Refactoring repetitive code -js

javascript,refactoring,dry
I have this really long function that sets all the variable positions. Is it better to leave it like this or try to refactor it? If I refactor it the only way I can think of is to do something like: function getPosition(name, id){ var name+"Box" = id.getBoundingClientRect(); var name+"Top"...

Refactoring java method to reduce cyclomatic complexity

java,refactoring
ArrayList cars = vehicles.getExtras(); Iterator it = cars.iterator(); while(it.hasNext()){ Extra cExtra = (Extra)it.next(); if (cExtra.getExtraId()==INSURANCE) insurance = cExtra.getExtra(); if (cExtra.getExtraId()==ROAD_ASSISTANCE_CODE) roadAssCode = cExtra.getExtra(); if (cExtra.getExtraId()==TYPE) replacementCarServiceType = cExtra.getExtra(); if (cExtra.getExtraId()==CATEGORY) replacementCarCategory = cExtra.getExtra(); if (cExtra.getExtraId()==ASSISTANCE){ roadAssistanceCode = cExtra.getExtra(); } I have a lot more of these 'if' types...

Refactoring for loop with each iteration setting a different property

java,coding-style,refactoring
I've been shown the following Java code as part of a code review and it's quite frankly hideous. However, I'm at a loss as to what the best way to re-write it is. We have a list that's always in the same order (0-5) and each index corresponds to a...

superscript in ggplot2 as label when ordering a factor

r,ggplot2,refactoring,superscript
I'm trying to first re-order the levels of a factor, and then change the labels so that when I plot in ggplot2, I get superscripts in some units. Not all the labels require superscripts. I've tried using 'expression' in my code, but I can't get it to work. I've seen...

What is merging 2 classes into 1 class where one class is a subclass of the other called?

java,class,intellij-idea,refactoring,subclass
I have: an abstract class A an abstract class B that extends A no other classes that extends A except B other class(es) that extend B To reduce the number of classes, I want A and B to be merged into one class, and let the other class(es) extend from...

Systematically extract noun arguments from J expression

refactoring,j,tacit-programming
What is the systematic approach to extracting nouns as arguments from an expression in J? To be clear, an expression containing two literals should become a dyadic expression with the left and right arguments used instead of the literals. I'm trying to learn tacit style so I prefer not to...

Refactoring code - variable scope

javascript,jquery,refactoring,code-duplication
I have 3 buttons that concatenate input text differently: var myTxtArea = document.getElementById('KWarea'); myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, ''); var lines = $('#KWarea').val().replace(/\*/g, '').split('\n'); $('#produce').click(function () { var endString = ""; myTxtArea.value = myTxtArea.value.replace(/^\s*|\s*$/g, ''); var lines = $('#KWarea').val().replace(/\*/g, '').split('\n'); for (var i = 0; i < lines.length; ++i) { endString +=...

How to Move a class to another dll and change the namespace without altering the method usage

c#,.net,namespaces,refactoring
I have a dll where I have one class which logs to a "channel", another Program listens to the "channel" and writes the logs to the screen. The problem with the dll is that its grown over time and now there are many dependecies in it. I want to remove...

Shortcut to organize C# usings in Visual Studio

c#,visual-studio,visual-studio-2013,refactoring
Is there a way to organize C# usings (remove and sort, in separate or together) via a shortcut in Visual Studio for one or more files of a project? I know that this can be done via the menu for one file by selecting Edit > IntelliSense > Organize Usings...

Create a typed array w/ N items in it using Swift

ios,swift,refactoring
I have a method that I'm using to create an array w/ n of a specific type of object in it: func many(count: Int) -> [Cube] { var cubes: [Cube] = [] for i in 0...count { let cube = CubeFactory.single() cubes.append(cube) } return cubes } This works but I'm...

Trouble refactoring current types(possibly GADT/Type Families related)

haskell,types,refactoring,gadt
I've got types like this: -- There are codes newtype ICode = ICode { fromICode :: String } newtype RCode = RCode { fromRCode :: String } data DCode = DCode1 | DCode2 | DCode3 -- There are locations described by type and code. -- Current implementation looks like this:...

How replace cutting string logic with Regex?

java,regex,refactoring
I want to replace my clumsy logic to regex solution. My solution works but it is very redundant. I have to process JSON data: {"action":"stop"} and take as a result only - stop. Here is my solution: private String processAction(String actionJson) { String[] data = actionJson.split(":"); int limit = data[1].length()...

Why doesn't Python optimize away temporary variables?

python,optimization,refactoring,python-internals
Fowler's Extract Variable refactoring method, formerly Introduce Explaining Variable, says use a temporary variable to make code clearer for humans. The idea is to elucidate complex code by introducing an otherwise unneeded local variable, and naming that variable for exposition purposes. It also advocates this kind of explaining over comments.....

Refactoring LINQ query to accommodate null values / missing properties

linq,refactoring
I have a string array which has a variable number of properties that I need to parse. I’m using LINQ to parse this data but can’t help thinking there’s a more efficient/elegant way to achieve this than duplicate the LINQ as I have done. Is there an inherent way to...

Visual Studio - How to refactore javascript strings from double quotes to single quotes

javascript,c#,visual-studio-2013,refactoring,resharper
Is there an easy way to refactore all javascript strings from my solution to use single quotes ' instead of double quotes " If i have: var element = $(".classSelector"); ...({ url: "<%= Url.Action("action", "controller")%>", ... I would like to refactor my javascript in .js, .aspx, .ascx files to var...

Selenium, questions about code re-factoring

selenium,junit,refactoring
With Selenium IDE I generate a sample script for test the log to a website and a value in the website after logging. So my script is (Java) : @test public void mytest() throws Exception{ // Load the home page ... // complete the log form ... // check if...

Determine appropriate parent type for function argument in eclipse

java,eclipse,refactoring
I have code that looks like this (part way through a refactoring) void doSomething( DerivedType v ) { v.foo(); v.bar(); ... } public static class DerivedType extends Parent1 { @Override void foo() { ... } } public static class Parent1 extends Parent2 { public void foo() {...} public void bar()...

Abstraction with Java in Android

java,android,refactoring,abstraction,modularity
I was studying some tutorials concerning the Java language. I was wondering if I should abstract every time that I code something, and on any type of standard and stack? I have seen that with every Spring Services for example, we could even abstract controllers, using interfaces with EJBs on...

Why `x += a + d[x]` works fine but `x +=a; x += d[x]` fails?

python,refactoring
I was recently refactoring this snippet and I broke it: if from_mac in self.announces: from_mac += '\\nAnnounces: ' + ',\\n'.join(self.announces[from_mac]) if to_mac in self.announces: to_mac += '\\nAnnounces: ' + ',\\n'.join(self.announces[to_mac]) After my refactoring, it looked like this to make the lines shorter: if from_mac in self.announces: from_mac += '\\nAnnounces: '...

How do I refactor android code to choose layout?

android,android-layout,refactoring,android-linearlayout
I have 1 top layout and 3 bottom layouts, a user drags items from top layout to one of the 3 below. The code below: puts sequentially every image in every bottom layout into a list removes items from each bottom layout puts them back into top layout public void...

Way to simplify this array insertion code?

c#,arrays,boolean,refactoring
If I have this code: array[0] = a < b ? c : d array[1] = a < b ? d : c Is there a way to simplify it elegantly? I know I can do something like this to avoid the double boolean check: if (a < b) {...

How to extract 'for' loop Method?

java,refactoring
I am attempting to extract my 'for' loop in order to call it in printPartyBreakdownInHouse() method. Basically removing any chance of duplicate code or "code smell" as well as my printdetails() method, but when doing this I'm getting '2' as a result. Any ideas? public void printPartyBreakdownInSenate() { int numDemocrats...

refactoring Rails 4 before_action for code speed with reused controller methods

ruby-on-rails,ruby-on-rails-4,controller,refactoring
I’ve been learning Rails for a while now and I’d like to know what the best way to include reusable methods in other methods is. I use before_action for some, but I’m wondering if I should convert my code which looks like ‘Fig.A’ to utilize more before actions (Fig. B)....

How can I use the Factory pattern to refactor my Java code?

java,refactoring
I would like to use the Factory pattern to make a new method addShip this determines in running time which type of Ship to initialize. while(!g.allShipsPlaced()) { NumberGenerator gen = new NumberGenerator(); int x = gen.rand(10); int y = gen.rand(10); int o = gen.rand(1); x = gen.rand(10); y = gen.rand(10);...

How to do refactoring to eliminate type-code if it is used in validation rules?

java,validation,design-patterns,refactoring
Let's say we have to check some set of rules before adding a new element in a collection. Elements are objects of a few similar types. All type specific features are encapsulated in subclasses of an abstract class. Collection contains objects of this abstract class. The rules apply conditions for...

How to use Reflection with instance methods

c#,asp.net,reflection,transactions,refactoring
If i create the following method concerning transaction : public static int Insert(string processMethod, object[] processParameters, Type processType, object process, UserTransactionDTO transObj, string spPostConfirm, int toEmpNum,int confirmState) { int affectedRows = -7; using (IfxConnection conn = new IfxConnection(ConfigurationManager.ConnectionStrings["crms"].ToString() + " Enlist=true;")) { if (conn.State == ConnectionState.Closed) { conn.Open(); } using...

What C/C++ libraries are/are not available in Arduino? [closed]

c++,oop,arduino,refactoring,software-engineering
I'm new to Arduino programming and I was trying to refactor some code from a .ino file into several supporting c++ classes. However, a problem I encountered is some c++ libraries are not seemed to be supported in Arduino. For example I was trying to use std::string but the compiler...

Flask refactoring

python,flask,refactoring
I am trying to make a web project in Flask. In short, it is a HTML/CSS site where you can input some data and either the area or circumference of the rectangle is shown. My problem is that I pretty much repeated the same code both for the circumference and...

PhpStorm 8 - Rename Refactoring - How do I rename a object property throughout my project?

php,refactoring,phpstorm
In PhpStorm 8, under the 'Refactor' menu the option 'Rename' exists. If I click on a variable in my code and then select 'Rename', then I believe 'Rename' will attempt to search throughout my project and rename the variable to whatever I wish it to be. However, if I click...

Form button not responding and badly aligned [Refactoring Ruby on Rails]

ruby-on-rails,ruby,forms,refactoring,frontend
I'm working on an assignment for a course I'm doing on refactoring some version of the typo blog. I need to add a new form to a page in order to get some information, the problem is that the submit button is not responding and the form is also badly...

Refactoring jQuery each loop on data object

jquery,object,refactoring,each
I have a csv file converted to a jQuery object using jQuery CSV (https://code.google.com/p/jquery-csv/). Here is the code for that: $.ajax({ type: "GET", url: "/path/myfile.csv", dataType: "text", success: function(data) { // once loaded, parse the file and split out into data objects // we are using jQuery CSV to do...

Refactoring. Flip all (b != a) and (b == a) occurrences in code

java,intellij-idea,refactoring
I have many occurrences in my code such as : if (null != object) and if (null == object) On a new work place I need to refactor these occurrences to: if (object != null) and if (object == null) For more readable code. I tried to make a search...

Multiple ifs in Smalltalk

refactoring,conditional-statements,smalltalk,pharo
I'm really new to smalltalk and still trying to figure out the basic stuff. Below is a simple program I wrote. It is supposed to print "a" if the number can be divided by 5, "b" if it can be divided by 3, and "ab" if it can be divided...

Is it possible to do this code with less redudancy?

vb.net,refactoring
I have the following code: If moves.Contains("1") Then lblOnes.Visible = True End If If moves.Contains("2") Then lblTwos.Visible = True End If If moves.Contains("3") Then lblThrees.Visible = True End If If moves.Contains("4") Then lblFours.Visible = True End If If moves.Contains("5") Then lblFives.Visible = True End If If moves.Contains("6") Then lblSixes.Visible =...

Rails - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring
I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to menu.name, ("tech/""#{menu.name.parameterize}") %></td> </tr> <% end %> I feel...

Exclude unit tests from Code Clones analysis

visual-studio,unit-testing,refactoring,automated-tests,static-analysis
How do I exclude my unit test project from Visual Studio's Code Clones analyzer. Hence, I am more interested in my automated test scripts serving as living documentation than I am as SOLID. As a result, I am okay with some duplication across my suite of tests. Any thoughts?...

Can you refactor this code?

coffeescript,parse.com,refactoring
How can I refactor this coffeescript method that returns json object? getQuery: -> p = user: __type: "Pointer" className: '_User' objectId: @model.id private: false q = user: __type: "Pointer" className: '_User' objectId: @model.id spec = projects: collection: "Projects" params: where: JSON.stringify(p) needsFetch: true payments: collection: "Payments" params: where: JSON.stringify(q) needsFetch:...

Refactor to smaller function, how?

c#,refactoring
I have a function that loads a large selectlist for ASP.NET MVC. This functions has a methodsize of 354 rows. I want to refactor to more functions or to a local field so that each function will be less than 40 lines. Here is the code snippet: public static SelectList...

Combining a few methods into the only one. Generics

java,generics,refactoring
I have some code to figure out the correctness of manipulations on different data types (int, long, double) comparing to BigInteger. The manipulation is getting a factorial of a number until the result is the same as BigInteger has. The question is how could i change my code, make more...

Can I use refactoring to exchange the type of a variable for another?

java,android-studio,refactoring
Android Studio provides powerful refactoring, for example Rename. I can use it to change the name of variables, fields, parameters, however I cannot seem to find a way to rename a type. For example: LinearLayout layout = (LinearLayout) v.findViewById(....); // ........ // A bunch of code using `layout` many times...

PLSQL procedure, which gets the dependend package reference as a parameter

oracle,stored-procedures,plsql,refactoring
I hava an oracle PLSQL procedure which looks quite the same in three different packages. CREATE OR REPLACE PACKAGE BODY PACK_A AS PROCEDURE PROC_A IS TYPE ref_c_data IS REF CURSOR RETURN data_rec%ROWTYPE; TYPE ref_c_items IS REF CURSOR RETURN items_rec%ROWTYPE; BEGIN ... PACK_A.PROC_B(ref_c_data, ref_c_items) ... END; PROCEDURE PROC_B -- This procedure...

PHP suppress errors when checking existence + value of boolean?

php,coding-style,refactoring
I have a PHP script that uses an array of options: $opts[] $opts can contain 0 or more key value pairs. All values are boolean. When checking for existence of a key, and then that the value is true, I have been doing the following: if(isset($opts['small']) && $opts['small']) $classes .=...

Linq select new dynamic multi part List<>

c#,linq,refactoring
I have the following query I am playing about with: public void FindAllRelatedProdsByParentCat(CategoryService categoryService, string parentCatName, bool isDeleted) { List<Category> allCats = categoryService.FindAll(isDeleted).ToList(); var results = (from a in allCats.Where(x => x.Name == parentCatName) join b in allCats on a.CategoryId equals b.Parentcategory into children select new { ParentId = a.CategoryId,...

FluentValidation NotEmpty and EmailAddress example

c#,validation,refactoring,fluentvalidation
I am using FluentValidation with a login form. The email address field is Required and Must be a valid email address. I want to display a custom error message in both cases. The code I have working is: RuleFor(customer => customer.email) .NotEmpty() .WithMessage("Email address is required."); RuleFor(customer => customer.email) .EmailAddress()...

should we avoid to use spring managed bean when it is unnecessary?

java,spring,refactoring,mockito,static-methods
Say I have a relative complex class which needs to be simplified by breaking into few smaller helper classes. One suggested refactor solution is : public class RefactoredComplexClass { private final Helper1 h1; private final Helper2 h2; // Helper1 and Helper2 will be injected by spring IoC public RefactoredComplexClass(Helper1 h1,...

Deleting one of a collection on parent update

php,laravel,refactoring
I am trying to delete (or create) a models associated objects when it is updated. Each bar has several taps. When you create a bar, these tap objects are created, and you can update that number and additional taps will be created or deleted as necessary. Originally I just wanted...

How to refactor “using” statement to avoid code duplication?

c#,wcf,refactoring,using-statement
Let's suppose I have the following methods: public string GetSchedules(string request) { using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint)) { return soapClient.GetSchedules(AuthenticationInfo, request); } } public string GetCountryList(string request) { using (var soapClient = new ServiceReference1.CustomDataTimetableToolKitServicesSoapClient(EndpointConfiguratioName, Endpoint)) { return soapClient.GetCountryList(AuthenticationInfo, request); } } public string...

refactor 'execute and log' pattern

c++,c,function,logging,refactoring
I found myself keep following the same pattern again and again: if((return_code = doFoo1(...)) != CODE_OK) { log("useful log message based on return code"); // very likely to return an error code. } // continue if((return_code = doFoo2(...)) != CODE_OK) { log("useful log message based on return code"); // very...

Why does extracting this method not work in gradle?

groovy,gradle,refactoring,extract-method
I have gradle build script for a multi module project. For better readability I'd like to extract some methods, but when I do the script fails with an exception: Cannot add task ':signArchives' as a task with that name already exists. Full reproducable example: Have an otherwise empty directory, with...

Is it ok to declare an object to be equal to itself in Javascript for the sake of refactoring a large project

javascript,eclipse,oop,refactoring
I'm working on a very large javascript web app that doesn't really have a method to it. There seems to be an attempt to declare everything as part of a master object called "app". The original program existed as a single app.js file over 300k lines of code where the...

Resharper “join declaration and assignment” don't convert to “var”

c#,refactoring,resharper
When using Resharper and editing C# code, when I choose to apply a "join declaration and assignment" suggestion, it changes my explicit type declaration to "var". Example: If I have: int myNumber; myNumber = 0; It will refactor it to: var myNumber = 0; I do not like this. I...

C++ factoring tempate methods specialization of a template class, is that possible?

c++,templates,refactoring,template-specialization
I have a template method inside a template class. I read that a method can not be specialized without specialize the class before. But I want to factorize some of theses methods, is it possible ? Example : class One { public: static const int number = 1; }; class...

Rewrite Java class to clean and testable code [closed]

java,oop,polymorphism,refactoring
So I have a Java class that looks like this: class CalendarEntry { private char type; private char status; ... public void myMethod() { switch (type) { ... } } public String myOtherMethod() { switch (status) { ... } } // and so on } Type and status are two...

Cleaning up massive amount of PageObject elements

ruby,refactoring,page-object-gem
Each of our page objects has around 80-100 PageObject elements defined. This is a byproduct of a very data centric application and I don't see that changing any time soon. We have many text fields, select lists, buttons, and menus. I want to clean up these somehow and put them...

Refactoring nested routes, how do I address this redirect_to?

ruby-on-rails,ruby,ruby-on-rails-3,routing,refactoring
I am working on an assignment for a project I have been working on. I was just introduced to refactoring my nested routes. Here are the changes. routes.rb resources :topics do resources :posts, except: [:index] do resources :comments, only: [:create, :destroy] end end to resources :topics do resources :posts, except:...

Is it more efficient to do a single SQL SELECT with joins vs several smaller SQLs?

php,mysql,database,performance,refactoring
I have code that uses long SELECT statements that usually LEFT JOIN various tables on top of each other using some kind of ids or keys to join the data. The result of this SQL is then entered into a PHP class construct. Result can contain for example curve coefficients...

Stored procedure: reduce code duplication using temp tables

sql,sql-server,stored-procedures,refactoring,temp-tables
After many changes to my stored procedure, I think it needs to re-factoring , mainly because of code duplication. How to overcome these duplications: IF @transExist > 0 BEGIN IF @transType = 1 BEGIN --INSERT SELECT a.dayDate, a.shiftName, a.limit, b.startTimeBefore, b.endTimeBefore, b.dayAdd, b.name, b.overtimeHours, c.startTime, c.endTime INTO #Residence1 FROM #ShiftTrans...

WPF: How should I refactor this C# project?

c#,wpf,visual-studio-2013,refactoring
THE PROBLEM I have created a monster. 169 Lists, 169 CheckBoxes, 169 if statements. This sucks and I want to refactor it. Here is some pseudocode to demonstrate: XAML <checkbox Name="CheckBox1"... // etc <checkbox Name="CheckBox169"/> Code behind List<ulong> masterList = big_array_of_ulongs; List<ulong> list1 = array_of_ulongs; List<ulong> list2 = array_of_ulongs; //...

Named_scope refactoring to rails 4

ruby-on-rails,ruby-on-rails-3,refactoring
I have named_scope :business, :conditions => "processing_time_15_minutes is null" how to refactor to rails4 style Thx...

Pattern for converting if-then-else to conditional

design-patterns,refactoring
What is the name of this refactoring pattern? I'd like to read more opinions about it, but can't name it. The same code is executed in both branches of an if-else-statement, but just one atomic expression is different. E.g. if (condition) { prepareSomethingAdditional(); callMethod(true, "foobar"); } else { callMethod(false, "foobar");...

How best to subclass NSManagedObject to provide a set of core methods

ios,objective-c,xcode,core-data,refactoring
I am working on a typical IOS app that implements a Core Data model and I am using XCode to generate the base set of NSManagedObjects for each entity in the model. Typical Example, nothing special here: // // ContactKey.h #import <Foundation/Foundation.h> #import <CoreData/CoreData.h> @class ContactAttribute; @interface ContactKey : NSManagedObject...

How would I refactor this C code to get rid of repetition

c,refactoring
I am working on writing a driver for a microcontroller to interface with a sensors. The sensor that I am using is the MAG3110. I have written a driver that can control everything on the sensor but there is a lot of code repetition. Three quarters of the functions are...

Refactoring a concrete method in abstract class which contains an abstract method

c#,design-patterns,refactoring,abstract-class
Considering the below code, abstract class AbstractClass { public abstract void AbstractMethodA(); public void ConcreteMethodA() { //Some operation ConcreteMethodB(); } } public void ConcreteMethodB() { //Huge code unrelated to this class AbstractMethodA(); } } class DerivedClass : AbstractClass { public void AbstractMethodA() { //Some operation } } Now I wish...

Refactor angular module name in Webstorm

angularjs,intellij-idea,refactoring,webstorm
Is there a possibility or trick to rename an angular module in Webstorm with refactoring in the whole project? 'Cause when I have something like this angular.module('my-module', []); and my caret is on the 'my-module' string, I cannot refactor the module name. Is there an appropriate place (or plugin) to...

Using lodash how I can keep a counter that later could used as a parameter?

javascript,loops,refactoring,lodash
here I have a typical for loop, where i is pass as a parameter later .splice() My question is: How I can refactor this with lodash? for(var i =0; i< scope.liveBalls.length;i++){ if(scope.liveBalls[i].bat === scope.ball.bat){ scope.splicedBalls.push(scope.liveBalls.splice(i,1)); } } ...

How to stop PHPStorm from automatically refactoring my code

refactoring,phpstorm,automated-refactoring
I renamed one of my files and phpstorm asked if I wanted to do a refactor on my project. I accidentally clicked yes to "Refactor", and it changed a bunch of the variable names in a handful of random files in my project. Not a big deal. I'm using GIT...

How to set compiler in eclipse to use borland C++ Builder 3?

c++,eclipse,refactoring,borland-c++
I know this is a pretty strange question, but I have new project that I have to refactor a code that was written long time ago using Borland C++ Builder version 3.0 It is almost impossible to refactor and use that IDE to keep track of refactoring. I am not...

Event handler has dependency on call order

c#,winforms,treeview,refactoring,anti-patterns
On WinForm there is TreeView control. In AfterSelect event is private field selectedFolder updated. For event OnKeyDown for Delete key is event handler implemented that interacts data access layer : selectedFolder is passed as parameter to method DeleteFolder. The selected node of TreeView is also removed Code has following issue:...

Ruby: Return if method returns a non-nil value

ruby,refactoring,code-smell,guard-clause
Is there a better/cleaner way to do this in Ruby? def my_method(x, y) return error if (error = validate(x, y)) # do something else end I call #validate elsewhere, so to keep things DRY, I have it return the error message....

Best practice for fat model refactor

ruby-on-rails,ruby,refactoring
I'm trying to make my fat User model less clunky. I'm using value objects to represent custom values and operations on them, and am stuck with ActiveSupport::Concerns and modules. I read this as an inspiration. I put helper methods like this: def is_a_wizard? power_level >= WIZARD_POWER end def just_became_a_wizard? power_level...

The better technique in this refactoring case?

vb.net,refactoring,pass-by-value
I need to do some refactoring (actually it's A LOT, but this small step will be very helpful for the whole process). So, let's say I've got this code snippet: If xmlDoc.SelectSingleNode("/dang") IsNot Nothing Then universalNode = xmlDoc.SelectSingleNode("/dang") Type = "dang" ElseIf xmlDoc.SelectSingleNode("/nang") IsNot Nothing Then universalNode = xmlDoc.SelectSingleNode("/nang") Type...

Refactor jQuery $(this).find

javascript,jquery,refactoring
I have a written a simple accordion script that works great, I just want to refactor it to get rid of the multiple `$(this).find. I know it is pretty slim as it is but I hate repeating myself, any ideas? Best way to learn is to ask I suppose. Thanks!...

Refactor Ruby code for Luhn algorithm

ruby,refactoring,credit-card
Help me refactor implementing Luhn algorithm, which is described as follows: The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This account number must pass the following test: From the rightmost digit, which is...

How to refactor the return of a generic method to an interface and all its implementations

java,eclipse,generics,refactoring
I would change the return type declared in an interface, which is implemented in 10 other about class method . I'm using eclipse as IDE , the signature of the current method is: public List<T> findById(int id); and what I need public T findById(int id); Regards, Santiago...

Ruby refactoring issue

ruby,refactoring
Let's say I have an @array = [1 ,2 ,3] I want to create three blocks of each number of the array with the rest like this : @array.each do |first| (@array - [first]).each do |second| (@array - [first] - [second]) do |third| #do something So each block iterates through...

Rearrange docs in Eclipse IDE

eclipse,refactoring,automated-refactoring
I want to reposition the params docs, I had written the docs for my code earlier. Now I have rearranged the arguments of my method, I want the same to reflect in my docs written above my method. How can I do this, is there any shortcut keys? I don't...

Challenge of finding 3 pairs in aray

go,refactoring
The length L at the time of joining, when the length of the bar of the N (1 ≦ N ≦ 5000) is supplied from standard input, is the L by connecting three lengths among the N number of bars please write a program to find the total number of...

How do I split up index.js file in a node/mean/express application?

javascript,node.js,express,routes,refactoring
I've got one incredibly long index.js route file for my node/mongo/express application. Here is the structure. app.js /models Schedule.js Task.js etc... /routes index.js /public /javascript etc... I want something like this app.js /models Schedule.js Task.js etc... /routes index.js schedule.js tasks.js etc... /public /javascript etc... How can I split up my...

Avoid manually decoding many strings in code

python,string,encoding,utf-8,refactoring
I work in Python. Since I have to put .decode('utf-8') very often, I would like to get it decoded automatically. Is there a way how to make all strings decoded from utf-8 automatically? And second question: Is there any disadvantage? PS: I have to decode especially strings where diacritics appears...

PHP code refactoring [closed]

php,refactoring
what the best refactoring you will do it for this class? i am looking here for "Extract and Combine Classes and Functions" method i think all the databases function in the coed can be combine like fetching the results and db connect and all user login. <?php $database = mysql_connect('localhost',...

How to restart or reuse a case statement in Ruby?

ruby,loops,refactoring,case-statement
After going through the codecademy ruby section "A Night at the Movies", I wanted to extend the case-statement to allow input again. By the end my code was: movies = { living_torah: 5, ushpizin: 5 } def input #method for gets.chomp gets.chomp.downcase end puts "To exit please type 'Quit' or...

refactoring a function that sorts with consideration for initial articles

php,arrays,sorting,filter,refactoring
I've got a function that does what I want it to do, but it's really, really ugly. Looking for ways to not necessarily make it faster, but maybe make it a little less ugly, more generic, and overall more maintainable. <?php // unordered list $list = Array( 0 => 'My...

Refactoring if statement in java

java,if-statement,refactoring
I need some help refactoring this if-statement. I thought of declaring the percentage as constants. I also thought to make a method that includes the code inside the if brackets. What else can i do? if(totalReceiptsAmount >= getIncome() && totalReceiptsAmount < 0.20 * getIncome()) setTaxIncrease(getBasicTax() + 0.05 * getBasicTax()); if(totalReceiptsAmount...

Refactoring a short case statement

ruby,refactoring
I'm having difficulty refactoring this case statement: case type when :log console = 'LOG'.on_blue.bold console_prefix = "#{prefix}:".blue.bold if prefix when :error console = 'ERROR'.on_red.bold console_prefix = "#{prefix}:".red.bold if prefix console_message = message.red when :ok console = 'OK'.on_green.bold console_prefix = "#{prefix}:".green.bold if prefix end puts "#{console} #{console_prefix} #{console_message}" There's a variable...

replace simple factory using polymorphism

java,design-patterns,refactoring,factory-pattern
I am trying to replace the simple factory StatsCreatorFactory.java class in order to delete the stink multiple use of switch case statements. This is my situation: StatsServlet.java public class StatsServlet extends HttpServlet{ private static final long serialVersionUID = 1L; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StatsContext...