Search Results

Search found 1030 results on 42 pages for 'refactoring'.

Page 4/42 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Refactoring exercise with generics

    - by Berryl
    I have a variation on a Quantity (Fowler) class that is designed to facilitate conversion between units. The type is declared as: public class QuantityConvertibleUnits<TFactory> where TFactory : ConvertableUnitFactory, new() { ... } In order to do math operations between dissimilar units, I convert the right hand side of the operation to the equivalent Quantity of whatever unit the left hand side is in, and do the math on the amount (which is a double) before creating a new Quantity. Inside the generic Quantity class, I have the following: protected static TQuantity _Add<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount + equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } protected static TQuantity _Subtract<TQuantity>(TQuantity lhs, TQuantity rhs) where TQuantity : QuantityConvertibleUnits<TFactory>, new() { var toUnit = lhs.ConvertableUnit; var equivalentRhs = _Convert<TQuantity>(rhs.Quantity, toUnit); var newAmount = lhs.Quantity.Amount - equivalentRhs.Quantity.Amount; return _Convert<TQuantity>(new Quantity(newAmount, toUnit.Unit), toUnit); } ... same for multiply and also divide I need to get the typing right for a concrete Quantity, so an example of an add op looks like: public static ImperialLengthQuantity operator +(ImperialLengthQuantity lhs, ImperialLengthQuantity rhs) { return _Add(lhs, rhs); } The question is those verbose methods in the Quantity class. The only change between the code is the math operator (+, -, *, etc.) so it seems that there should be a way to refactor them into a common method, but I am just not seeing it. How can I refactor that code? Cheers, Berryl

    Read the article

  • Refactoring - Speed increase

    - by Michael G
    How can I make this function more efficient. It's currently running at 6 - 45 seconds. I've ran dotTrace profiler on this specific method, and it's total time is anywhere between 6,000ms to 45,000ms. The majority of the time is spent on the "MoveNext" and "GetEnumerator" calls. and example of the times are 71.55% CreateTableFromReportDataColumns - 18, 533* ms - 190 calls -- 55.71% MoveNext - 14,422ms - 10,775 calls What can I do to speed this method up? it gets called a lot, and the seconds add up: private static DataTable CreateTableFromReportDataColumns(Report report) { DataTable table = new DataTable(); HashSet<String> colsToAdd = new HashSet<String> { "DataStream" }; foreach (ReportData reportData in report.ReportDatas) { IEnumerable<string> cols = reportData.ReportDataColumns.Where(c => !String.IsNullOrEmpty(c.Name)).Select(x => x.Name).Distinct(); foreach (var s in cols) { if (!String.IsNullOrEmpty(s)) colsToAdd.Add(s); } } foreach (string col in colsToAdd) { table.Columns.Add(col); } return table; }

    Read the article

  • Ruby on Rails controller-view refactoring

    - by Dimitar Vouldjeff
    Hello, In my app I am using the ym4r-gm plugin, which allows you to play with the Google Maps API... I put the map "setup" in the controller: @map = GMap.new("div_map") @map.control_init(:large_map => true, :map_type => true) @map.center_zoom_init([47.0, 26.0], 7) ... And only render @map in the view. So my first question is whether I am using the right approach of "diving" this code? And the second question is: I have to models, which are rendering the same map (only the resources are different). Where should I put my refactored method that renders the map? In the application controller, maybe? Thanks in advance, I hope you will understand me!

    Read the article

  • Replace conditional with polymorphism refactoring or similar?

    - by Anders Svensson
    Hi, I have tried to ask a variant of this question before. I got some helpful answers, but still nothing that felt quite right to me. It seems to me this shouldn't really be that hard a nut to crack, but I'm not able to find an elegant simple solution. (Here's my previous post, but please try to look at the problem stated here as procedural code first so as not to be influenced by the earlier explanation which seemed to lead to very complicated solutions: http://stackoverflow.com/questions/2772858/design-pattern-for-cost-calculator-app ) Basically, the problem is to create a calculator for hours needed for projects that can contain a number of services. In this case "writing" and "analysis". The hours are calculated differently for the different services: writing is calculated by multiplying a "per product" hour rate with the number of products, and the more products are included in the project, the lower the hour rate is, but the total number of hours is accumulated progressively (i.e. for a medium-sized project you take both the small range pricing and then add the medium range pricing up to the number of actual products). Whereas for analysis it's much simpler, it is just a bulk rate for each size range. How would you be able to refactor this into an elegant and preferably simple object-oriented version (please note that I would never write it like this in a purely procedural manner, this is just to show the problem in another way succinctly). I have been thinking in terms of factory, strategy and decorator patterns, but can't get any to work well. (I read Head First Design Patterns a while back, and both the decorator and factory patterns described have some similarities to this problem, but I have trouble seeing them as good solutions as stated there. The decorator example seems very complicated for just adding condiments, but maybe it could work better here, I don't know. And the factory pattern example with the pizza factory...well it just seems to create such a ridiculous explosion of classes, at least in their example. I have found good use for factory patterns before, but I can't see how I could use it here without getting a really complicated set of classes) The main goal would be to only have to change in one place (loose coupling etc) if I were to add a new parameter (say another size, like XSMALL, and/or another service, like "Administration"). Here's the procedural code example: public class Conditional { private int _numberOfManuals; private string _serviceType; private const int SMALL = 2; private const int MEDIUM = 8; public int GetHours() { if (_numberOfManuals <= SMALL) { if (_serviceType == "writing") return 30 * _numberOfManuals; if (_serviceType == "analysis") return 10; } else if (_numberOfManuals <= MEDIUM) { if (_serviceType == "writing") return (SMALL * 30) + (20 * _numberOfManuals - SMALL); if (_serviceType == "analysis") return 20; } else //i.e. LARGE { if (_serviceType == "writing") return (SMALL * 30) + (20 * (MEDIUM - SMALL)) + (10 * _numberOfManuals - MEDIUM); if (_serviceType == "analysis") return 30; } return 0; //Just a default fallback for this contrived example } } All replies are appreciated! I hope someone has a really elegant solution to this problem that I actually thought from the beginning would be really simple... Regards, Anders

    Read the article

  • Refactoring Tabs

    - by Nimbuz
    HTML: <ul> <li><a href="#tab1">tab1</a></li> <li><a href="#tab2">tab2</a></li> </ul> <div id="tab1" class="tab-content">content 1</div> <div id="tab2" class="tab-content">content 2</div> jQuery $('#mode li:first').addClass('active'); $('#mode li.active').append('<span class="arrow">&nbsp;</span>'); $('#mode li a').click(function () { $('#mode li').removeClass('active') $('.arrow').remove(); $(this).parent().addClass('active').append('<span class="arrow">&nbsp;</span>'); var a = $(this).attr('href'); $('.tab-content').hide(); $(a).show(); return false; }); .. works, but looking ugly. Can it be simplified/reduced further? Many thanks!

    Read the article

  • Refactoring PL/SQL triggers - extract procedures

    - by Juraj
    Hello, we have application where database contains large parts of business logic in triggers, with a update subsequently firing triggers on several other tables. I want to refactor the mess and wanted to start by extracting procedures from triggers, but can't find any reliable tool to do this. Using "Extract procedure" in both SQL Developer and Toad failed to properly handle :new and :old trigger variables. If you had similar problem with triggers, did you find a way around it? EDIT: Ideally, only columns that are referenced by extracted code would be sent as in/out parameters, like: Example of original code to be extracted from trigger: ..... if :new.col1 = some_var then :new.col1 := :old.col1 end if ..... would become : procedure proc(in old_col1 varchar2, in out new_col1 varchar2, some_var varchar2) is begin if new_col1 = some_var then new_col1 := old_col1 end if; end; ...... proc(:old.col1,:new.col1, some_var);

    Read the article

  • Code refactoring c# question around several if statements performing the same check

    - by James Radford
    I have a method that has a load of if statements that seems a bit silly although I'm not sure how to improve the code. Here's an example. This logic was inside the view which is now in the controller which is far better but is there something I'm missing, maybe a design pattern that stops me having to check against panelCount < NumberOfPanelsToShow and handling the panelCount every condition? Maybe not, just feels ugly! Many thanks if (model.Train && panelCount < NumberOfPanelsToShow) { panelTypeList.Add(TheType.Train); panelCount++; } if (model.Car && panelCount < NumberOfPanelsToShow) { panelTypeList.Add(TheType.Car); panelCount++; } if (model.Hotel && panelCount < NumberOfPanelsToShow) { panelTypeList.Add(TheType.Hotel); panelCount++; } ...

    Read the article

  • Refactoring common method header and footer

    - by David Wong
    I have the following chunk of header and footer code appearing in alot of methods. Is there a cleaner way of implementing this? Session sess = factory.openSession(); Transaction tx; try { tx = sess.beginTransaction(); //do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); } The class in question is actually an EJB 2.0 SessionBean which looks like: public class PersonManagerBean implements SessionBean { public void addPerson(String name) { // boilerplate // dostuff // boilerplate } public void deletePerson(Long id) { // boilerplate // dostuff // boilerplate } }

    Read the article

  • Refactoring a complicated if-condition

    - by kumar kasimala
    Hi all, Can anyone suggest best way to avoid most if conditions? I have below code, I want avoid most of cases if conditions, how to do it ? any solution is great help; if (adjustment.adjustmentAccount.isIncrease) { if (adjustment.increaseVATLine) { if (adjustment.vatItem.isSalesType) { entry2.setDebit(adjustment.total); entry2.setCredit(0d); } else { entry2.setCredit(adjustment.total); entry2.setDebit(0d); } } else { if (adjustment.vatItem.isSalesType) { entry2.setCredit(adjustment.total); entry2.setDebit(0d); } else { entry2.setDebit(adjustment.total); entry2.setCredit(0d); } } } else { if (adjustment.increaseVATLine) { if (adjustment.vatItem.isSalesType) { entry2.setCredit(adjustment.total); entry2.setDebit(0d); } else { entry2.setDebit(adjustment.total); entry2.setCredit(0d); } } else { if (adjustment.vatItem.isSalesType) { entry2.setDebit(adjustment.total); entry2.setCredit(0d); } else { entry2.setCredit(adjustment.total); entry2.setDebit(0d); } } }

    Read the article

  • [jQuery] Refactoring Tabs

    - by Nimbuz
    $('#mode li:first').addClass('active'); $('#mode li.active').append('<span class="arrow">&nbsp;</span>'); $('#mode li a').click(function () { $('#mode li').removeClass('active') $('.arrow').remove(); $(this).parent().addClass('active').append('<span class="arrow">&nbsp;</span>'); var a = $(this).attr('href'); $('.tab-content').hide(); $(a).show(); return false; }); .. works, but looking ugly. Can it be simplified/reduced further? Many thanks!

    Read the article

  • Erlang: simple refactoring

    - by alexey
    Consider the code: f(command1, UserId) -> case is_registered(UserId) of true -> %% do command1 ok; false -> not_registered end; f(command2, UserId) -> case is_registered(UserId) of true -> %% do command2 ok; false -> not_registered end. is_registered(UserId) -> %% some checks Now imagine that there are a lot of commands and they are all call is_registered at first. Is there any way to generalize this behavior (refactor this code)? I mean that it's not a good idea to place the same case in all the commands.

    Read the article

  • Rails 3 refactoring issue

    - by Craig
    The following view code generates a series of links with totals (as expected): <% @jobs.group_by(&:employer_name).sort.each do |employer, jobs| %> <%= link_to employer, jobs_path() %> <%= "(#{jobs.length})" %> <% end %> However, when I refactor the view's code and move the logic to a helper, the code doesn't work as expect. view: <%= employer_filter(@jobs_clone) %> helper: def employer_filter(jobs) jobs.group_by(&:employer_name).sort.each do |employer,jobs| link_to employer, jobs_path() end end The following output is generated: <Job:0x10342e628>#<Job:0x10342e588>#<Job:0x10342e2e0>Employer A#<Job:0x10342e1c8>Employer B#<Job:0x10342e0d8>Employer C#<Job:0x10342ded0>Employer D# What am I not understanding? At first blush, the code seems to be equivalent.

    Read the article

  • Refactoring if/else logic

    - by David
    I have a java class with a thousand line method of if/else logic like this: if (userType == "admin") { if (age > 12) { if (location == "USA") { // do stuff } else if (location == "Mexico") { // do something slightly different than the US case } } else if (age < 12 && age > 4) { if (location == "USA") { // do something slightly different than the age > 12 US case } else if (location == "Mexico") { // do something slightly different } } } else if (userType == "student") { if (age > 12) { if (location == "USA") { // do stuff } else if (location == "Mexico") { // do something slightly different than the US case } } else if (age < 12 && age > 4) { if (location == "USA") { // do something slightly different than the age > 12 US case } else if (location == "Mexico") { // do something slightly different } } How should I refactor this into something more managable?

    Read the article

  • Refactoring two methods down to one

    - by bflemi3
    I have two methods that almost do the same thing. They get a List<XmlNode> based on state OR state and schoolType and then return a distinct, ordered IEnumerable<KeyValuePair<string,string>>. I know they can be refactored but I'm struggling to determine what type the parameter should be for the linq statement in the return of the method (the last line of each method). I thank you for your help in advance. private IEnumerable<KeyValuePair<string, string>> getAreaDropDownDataSource() { StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument(); string schoolTypeXmlPath = string.Format(STATE_AND_SCHOOL_TYPE_XML_PATH, StateOfInterest, ConnectionsLearningSchoolType); var schoolNodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>()); return schoolNodes.Select(x => new KeyValuePair<string, string>(x.Attributes["idLocation"].Value, x.Value)).OrderBy(x => x.Key).Distinct(); } private IEnumerable<KeyValuePair<string, string>> getStateOfInterestDropDownDataSource() { StateInfoXmlDocument stateInfoXmlDocument = new StateInfoXmlDocument(); string schoolTypeXmlPath = string.Format(SCHOOL_TYPE_XML_PATH, ConnectionsLearningSchoolType); var schoolNodes = new List<XmlNode>(stateInfoXmlDocument.SelectNodes(schoolTypeXmlPath).Cast<XmlNode>()); return schoolNodes.Select(x => new KeyValuePair<string, string>(x.Attributes["stateCode"].Value, x.Attributes["stateName"].Value)).OrderBy(x => x.Key).Distinct(); }

    Read the article

  • Tips on refactoring an Android prototype

    - by Brad
    I have an Android project I've inherited from another developer. The original code was hacked together using a single View and a single Activity. The view class has a State variable that is switched on during input and rendering. Each "screen" is a single bitmap rendered directly onto the screen. There are no layouts used at all. To make things even worse each variable in both the View and Activity classes were all declared public static and would access each other frequently. I've reworked the code so it is now somewhat manageable, but it's still in those original two classes. This is my first decently sized Android app so I'm not completely sure where to go next. From the looks of things, each "screen" should have its own View and Activity. Is this the general practice? If so I need some way to share data between the separate Activities. I've read suggestions to use a Singleton class that holds generic data. Is there any other ways that are more built into the Android framework? Thanks in advance.

    Read the article

  • Why the R# Method Group Refactoring is Evil

    - by Liam McLennan
    The refactoring I’m talking about is recommended by resharper when it sees a lambda that consists entirely of a method call that is passed the object that is the parameter to the lambda. Here is an example: public class IWishIWasAScriptingLanguage { public void SoIWouldntNeedAllThisJunk() { (new List<int> {1, 2, 3, 4}).Select(n => IsEven(n)); } private bool IsEven(int number) { return number%2 == 0; } } When resharper gets to n => IsEven(n) it underlines the lambda with a green squiggly telling me that the code can be replaced with a method group. If I apply the refactoring the code becomes: public class IWishIWasAScriptingLanguage { public void SoIWouldntNeedAllThisJunk() { (new List<int> {1, 2, 3, 4}).Select(IsEven); } private bool IsEven(int number) { return number%2 == 0; } } The method group syntax implies that the lambda’s parameter is the same as the IsEven method’s parameter. So a readable, explicit syntax has been replaced with an obfuscated, implicit syntax. That is why the method group refactoring is evil.

    Read the article

  • Unnamed Refactoring

    - by Liam McLennan
    This post is a message in a bottle. It cast it into the sea in the hope that it will one day return to me, stuffed to the cork with enlightenment. Yesterday I  tweeted, what is the name of the pattern where you replace a multi-way conditional with an associative array? I said ‘pattern’ but I meant ‘refactoring’. Anyway, no one replied so I will describe the refactoring here. Programmers tend to think imperatively, which leads to code such as: public int GetPopulation(string country) { if (country == "Australia") { return 22360793; } else if (country == "China") { return 1324655000; } else if (country == "Switzerland") { return 7782900; } else { throw new Exception("What ain't no country I ever heard of. They speak English in what?"); } } which is horrid. We can write a cleaner version, replacing the multi-way conditional with an associative array, treating the conditional as data: public int GetPopulation(string country) { if (!Populations.ContainsKey(country)) throw new Exception("The population of " + country + " could not be found."); return Populations[country]; } private Dictionary<string, int> Populations { get { return new Dictionary<string, int> { {"Australia", 22360793}, {"China", 1324655000}, {"Switzerland", 7782900} }; } } Does this refactoring already have a name? Otherwise, I propose Replace multi-way conditional with associative array

    Read the article

  • Is there an easy way to replace a deprecated method call in Xcode?

    - by Alex Basson
    So iOS 6 deprecates presentModalViewController:animated: and dismissModalViewControllerAnimated:, and it replaces them with presentViewController:animated:completion: and dismissViewControllerAnimated:completion:, respectively. I suppose I could use find-replace to update my app, although it would be awkward with the present* methods, since the controller to be presented is different every time. I know I could handle that situation with a regex, but I don't feel comfortable enough with regex to try using it with my 1000+-files-big app. So I'm wondering: Does Xcode have some magic "update deprecated methods" command or something? I mean, I've described my particular situation above, but in general, deprecations come around with every OS release. Is there a better way to update an app than simply to use find-replace?

    Read the article

  • Advice on approaching a significant rearrangement/refactoring?

    - by Prog
    I'm working on an application (hobby project, solo programmer, small-medium size), and I have recently redesigned a significant part of it. The program already works in it's current state, but I decided to reimplement things to improve the OO design. I'm about to implement this new design by refactoring a big part of the application. Thing is I'm not sure where to start. Obviously, by the nature of a rearrangement, the moment you change one part of the program several other parts (at least temporarily) break. So it's a little 'scary' to rearrange something in a piece of software that already works. I'm asking for advice or some general guidelines: how should I approach a significant refactoring? When you approach rearranging large parts of your application, where do you start? Note that I'm interested only in re-arranging the high-level structure of the app. I have no intention of rewriting local algorithms.

    Read the article

  • How do you handle the tension between refactoring and the need for merging?

    - by Xavier Nodet
    Hi, Our policy when delivering a new version is to create a branch in our VCS and handle it to our QA team. When the latter gives the green light, we tag and release our product. The branch is kept to receive (only) bug fixes so that we can create technical releases. Those bug fixes are subsequently merged on the trunk. During this time, the trunk sees the main development work, and is potentially subject to refactoring changes. The issue is that there is a tension between the need to have a stable trunk (so that the merge of bug fixes succeed -- it usually can't if the code has been e.g. extracted to another method, or moved to another class) and the need to refactor it when introducing new features. The policy in our place is to not do any refactoring before enough time has passed and the branch is stable enough. When this is the case, one can start doing refactoring changes on the trunk, and bug-fixes are to be manually committed on both the trunk and the branch. But this means that developpers must wait quite some time before committing on the trunk any refactoring change, because this could break the subsequent merge from the branch to the trunk. And having to manually port bugs from the branch to the trunk is painful. It seems to me that this hampers development... How do you handle this tension? Thanks.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >