Search Results

Search found 525 results on 21 pages for 'readability'.

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

  • Python doctests / sphinx : style guide, how to use those and have a readable code ?

    - by Sébastien Piquemal
    Hi ! I love doctests, it is the only testing framwork I use, because it is so quick to write, and because used with sphinx it makes such great documentations with almost no effort... However, very often, I end-up doing things like this : """ Descriptions ============= bla bla bla ... >>> test 1 bla bla bla + tests tests tests * 200 lines = poor readability of the actual code """ What I mean is that I put all my tests with documentation explanations on the top of the module, so you have to scroll stupidly to find the actual code, and this is quite ugly (in my opinion). However, I think that the doctests should still stay in the module, because you should be able to read them while reading the source code. So here comes my question : sphinx/doctests lovers, how do you organize your doctests, such as the code readability doesn't suffer ?

    Read the article

  • Are there advantages for using recursion over iteration - other than sometimes readability and elegance?

    - by Prog
    I am about to make two assumptions. Please correct me if they're wrong: There isn't a recursive algorithm without an iterative equivalent. Iteration is always cheaper performance-wise than recursion (at least in general purpose languages such as Java, C++, Python etc.). If it's true that recursion is always more costly than iteration, and that it can always be replaced with an iterative algorithm (in languages that allow it) - than I think that the two remaining reasons to use recursion are: elegance and readability. Some algorithms are expressed more elegantly with recursion. E.g. scanning a binary tree. However apart from that, are there any reasons to use recursion over iteration? Does recursion have advantages over iteration other than sometimes elegance and readability?

    Read the article

  • What was the most refreshingly honest non-technical comment you saw?

    - by DVK
    OK, so we all saw the lists of "funny" or "bad" comments. However, today, when maintaining an old stored procedure, I stumbled upon a comment which I couldn't classify other than "refreshingly brutally honest", left by a previous maintainer around a really freakish (both performance and readability-wise) page-long query: -- Feel free to optimize this if you can understand what it means So, in the first (and hopefully only) poll type question in my history of Stack Overflow, I'd like to hear some other "refreshingly brutally honest" code comments you encountered or written.

    Read the article

  • What was the most refreshingly honest non-technical comment you saw in the code?

    - by DVK
    OK, so we all saw the lists of "funny" or "bad" comments. However, today, when maintaining an old stored proc, I stumbled upon a comment which I couldn't classify other than "refreshingly brutally honest", left by a previous maintainer around a really freakish (both performance and readability-wise) page-long query: -- Feel free to optimize this if you can understand what it means So, in the first (and hopefully only) poll type question in my history of Stack Overflow, I'd like to hear some other "refreshingly brutally honest" code comments you encountered or written.

    Read the article

  • Gracefully avoiding NullPointerException in Java

    - by Yuval A
    Consider this line: if (object.getAttribute("someAttr").equals("true")) { // .... Obviously this line is a potential bug, the attribute might be null and we will get a NullPointerException. So we need to refactor it to one of two choices: First option: if ("true".equals(object.getAttribute("someAttr"))) { // .... Second option: String attr = object.getAttribute("someAttr"); if (attr != null) { if (attr.equals("true")) { // .... The first option is awkward to read but more concise, while the second one is clear in intent, but verbose. Which option do you prefer in terms of readability?

    Read the article

  • StringBuilder/StringBuffer vs. "+" Operator

    - by matt.seil
    I'm reading "Better, Faster, Lighter Java" (by Bruce Tate and Justin Gehtland) and am familiar with the readability requirements in agile type teams, such as what Robert Martin discusses in his clean coding books. On the team I'm on now, I've been told explicitly not to use the "+" operator because it creates extra (and unnecessary) string objects during runtime. But this article: http://www.ibm.com/developerworks/java/library/j-jtp01274.html Written back in '04 talks about how object allocation is about 10 machine instructions. (essentially free) It also talks about how the GC also helps to reduce costs in this environment. What is the actual performance tradeoffs between using "+," "StringBuilder," or "StringBuffer?" (In my case it is StringBuffer only as we are limited to Java 1.4.2.) StringBuffer to me results in ugly, less readable code, as a couple of examples in Tate's book demonstrates. And StringBuffer is thread-synchronized which seems to have its own costs that outweigh the "danger" in using the "+" operator. Thoughts/Opinions?

    Read the article

  • Please help me convert this C# 2.0 snippet to Linq.

    - by Hamish Grubijan
    This is not a homework ;) I need to both A) optimize the following code (between a TODO and a ~TODO) and B) convert it to [P]Linq. Better readability is desired. It might make sense to provide answers to A) and B) separately. Thanks! lock (Status.LockObj) { // TODO: find a better way to merge these dictionaries foreach (KeyValuePair<Guid, Message> sInstance in newSInstanceDictionary) { this.sInstanceDictionary.Add(sInstance.Key, sInstance.Value); } foreach (KeyValuePair<Guid, Message> sOperation in newSOperationDictionary) { this.sOperationDictionary.Add(sOperation.Key, sOperation.Value); } // ~TODO }

    Read the article

  • How do you make long SQL invoked from other code readable?

    - by Artem
    This is a very open question, but I think it can be very beneficial for SQL readability. So you have a Java program, and you are trying to call a monster SQL statement from it, with many subqueries and joins. The starting point for my question is a string constant like this: static string MONSTER_STATEMENT = "SELECT " + " fields" + "WHERE "+ " fieldA = (SELECT a FROM TableC) " + "AND fieldB IN (%s)" + "AND fieldC = %d " + "FROM " " tableA INNER JOIN tableB ON ..."; It later gets filled using String.format and executed. What are you tricks for making this kind of stuff readable? Do you separate your inner joins. Do you indent the SQL itself inside the string? Where do you put the comments? Please share all of the tricks in your arsenal.

    Read the article

  • Return lines in input code causing gaps/whitespace between elements in output?

    - by Jenny Zhang
    I am trying to put images next to each other on a webpage. Here is my HTML: <img class="pt" src="Yellow Tulip.jpg" title="Yellow Tulip" alt="Yellow Tulip" /> <img class="pt" src="Pink Tulip.jpg" title="Pink Tulip" alt="Pink Tulip" /> <img class="pt" src="Purple Tulip.jpg" title="Purple Tulip" alt="Purple Tulip" /> However, on my webpage, this shows a gap between each image. I've noticed that once I remove the return line that makes the elements separate and readable and instead just put all the elements on one line, the gaps go away. <img class="pt" src="Yellow Tulip.jpg" title="Yellow Tulip" alt="Yellow Tulip" /><img class="pt" src="Pink Tulip.jpg" title="Pink Tulip" alt="Pink Tulip" /><img class="pt" src="Purple Tulip.jpg" title="Purple Tulip" alt="Purple Tulip" /> Is there anyway I can achieve the output of the latter but still have the code/input look like the former? I really like the readability that the return lines (enter spaces) bring to the code, but I don't want the whitespace it creates on the actual page. If someone could explain why this is and/or how to fix it, I'd be really grateful! :)

    Read the article

  • Best ways to format LINQ queries.

    - by Aren B
    Before you ignore / vote-to-close this question, I consider this a valid question to ask because code clarity is an important topic of discussion, it's essential to writing maintainable code and I would greatly appreciate answers from those who have come across this before. I've recently run into this problem, LINQ queries can get pretty nasty real quick because of the large amount of nesting. Below are some examples of the differences in formatting that I've come up with (for the same relatively non-complex query) No Formatting var allInventory = system.InventorySources.Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }).GroupBy(i => i.Region, i => i.Inventory); Elevated Formatting var allInventory = system.InventorySources .Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }) .GroupBy( i => i.Region, i => i.Inventory); Block Formatting var allInventory = system.InventorySources .Select( src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }) .GroupBy( i => i.Region, i => i.Inventory ); List Formatting var allInventory = system.InventorySources .Select(src => new { Inventory = src.Value.GetInventory(product.OriginalProductId, true), Region = src.Value.Region }) .GroupBy(i => i.Region, i => i.Inventory); I want to come up with a standard for linq formatting so that it maximizes readability & understanding and looks clean and professional. So far I can't decide so I turn the question to the professionals here.

    Read the article

  • Is there anything for Python that is like readability.js?

    - by Emre Sevinç
    Hi, I'm looking for a package / module / function etc. that is approximately the Python equivalent of Arc90's readability.js http://lab.arc90.com/experiments/readability http://lab.arc90.com/experiments/readability/js/readability.js so that I can give it some input.html and the result is cleaned up version of that html page's "main text". I want this so that I can use it on the server-side (unlike the JS version that runs only on browser side). Any ideas? PS: I have tried Rhino + env.js and that combination works but the performance is unacceptable it takes minutes to clean up most of the html content :( (still couldn't find why there is such a big performance difference).

    Read the article

  • When should an API favour optimization over readability and ease-of-use?

    - by jmlane
    I am in the process of designing a small library, where one of my design goals is to use as much of the native domain language as possible in the API. While doing so, I've noticed that there are some cases in the API outline where a more intuitive, readable attribute/method call requires some functionally unnecessary encapsulation. Since the final product will not necessarily require high performance, I am unconcerned about making the decision to favour ease-of-use in my current project over the most efficient implementation of the code in question. I know not to assume readability and ease-of-use are paramount in all expected use-cases, such as when performance is required. I would like to know if there are more general reasons that argue for an API design preferring (marginally) more efficient implementations?

    Read the article

  • When should code favour optimization over readability and ease-of-use?

    - by jmlane
    I am in the process of designing a small library, where one of my design goals is that the API should be as close to the domain language as possible. While working on the design, I've noticed that there are some cases in the code where a more intuitive, readable attribute/method call requires some functionally unnecessary encapsulation. Since the final product will not necessarily require high performance, I am unconcerned about making the decision to favour ease-of-use in my current project over the most efficient implementation of the code in question. I know not to assume readability and ease-of-use are paramount in all expected use-cases, such as when performance is required. I would like to know if there are more general reasons that argue for a design preferring more efficient implementations—even if only marginally so?

    Read the article

  • How can I hide tracing code in Visual Studio IDE C# ?

    - by Mark
    As I'm starting to put more tracing in my code, i'm realizing it adds a lot of clutter. I know Visual Studio allows you to hide and reveal code, however, i'd like to be able group code into "tracing" code and then hide it and reveal at will as i'm reading the code. I suppose it could do this either per file or per class or per function. Is there any way to do this? What do you guys do? Adding some clarification The hide current feature kind of allows you to do this except that when the code is hidden, you can't tell if its tracing or not. You also can't say "hide all tracing code" and "reveal all tracing code" which is useful when reading a function depending on what you are trying to do.

    Read the article

  • c#: Clean way to fit a collection into a multidimensional array?

    - by Rosarch
    I have an ICollection<MapNode>. Each MapNode has a Position attribute, which is a Point. I want to sort these points first by Y value, then by X value, and put them in a multidimensional array (MapNode[,]). The collection would look something like this: (30, 20) (20, 20) (20, 30) (30, 10) (30, 30) (20, 10) And the final product: (20, 10) (20, 20) (20, 30) (30, 10) (30, 20) (30, 30) Here is the code I have come up with to do it. Is this hideously unreadable? I feel like it's more hacky than it needs to be. private Map createWorldPathNodes() { ICollection<MapNode> points = new HashSet<MapNode>(); Rectangle worldBounds = WorldQueryUtils.WorldBounds(); for (float x = worldBounds.Left; x < worldBounds.Right; x += PATH_NODE_CHUNK_SIZE) { for (float y = worldBounds.Y; y > worldBounds.Height; y -= PATH_NODE_CHUNK_SIZE) { // default is that everywhere is navigable; // a different function is responsible for determining the real value points.Add(new MapNode(true, new Point((int)x, (int)y))); } } int distinctXValues = points.Select(node => node.Position.X).Distinct().Count(); int distinctYValues = points.Select(node => node.Position.Y).Distinct().Count(); IList<MapNode[]> mapNodeRowsToAdd = new List<MapNode[]>(); while (points.Count > 0) // every iteration will take a row out of points { // get all the nodes with the greatest Y value currently in the collection int currentMaxY = points.Select(node => node.Position.Y).Max(); ICollection<MapNode> ythRow = points.Where(node => node.Position.Y == currentMaxY).ToList(); // remove these nodes from the pool we're picking from points = points.Where(node => ! ythRow.Contains(node)).ToList(); // ToList() is just so it is still a collection // put the nodes with max y value in the array, sorting by X value mapNodeRowsToAdd.Add(ythRow.OrderByDescending(node => node.Position.X).ToArray()); } MapNode[,] mapNodes = new MapNode[distinctXValues, distinctYValues]; int xValuesAdded = 0; int yValuesAdded = 0; foreach (MapNode[] mapNodeRow in mapNodeRowsToAdd) { xValuesAdded = 0; foreach (MapNode node in mapNodeRow) { // [y, x] may seem backwards, but mapNodes[y] == the yth row mapNodes[yValuesAdded, xValuesAdded] = node; xValuesAdded++; } yValuesAdded++; } return pathNodes; } The above function seems to work pretty well, but it hasn't been subjected to bulletproof testing yet.

    Read the article

  • Is it possible to embed Cockburn style textual UML Use Case content in the code base to improve code

    - by fooledbyprimes
    experimenting with Cockburn use cases in code I was writing some complicated UI code. I decided to employ Cockburn use cases with fish,kite,and sea levels (discussed by Martin Fowler in his book 'UML Distilled'). I wrapped Cockburn use cases in static C# objects so that I could test logical conditions against static constants which represented steps in a UI workflow. The idea was that you could read the code and know what it was doing because the wrapped objects and their public contants gave you ENGLISH use cases via namespaces. Also, I was going to use reflection to pump out error messages that included the described use cases. The idea is that the stack trace could include some UI use case steps IN ENGLISH.... It turned out to be a fun way to achieve a mini,psuedo light-weight Domain Language but without having to write a DSL compiler. So my question is whether or not this is a good way to do this? Has anyone out there ever done something similar? c# example snippets follow Assume we have some aspx page which has 3 user controls (with lots of clickable stuff). User must click on stuff in one particular user control (possibly making some kind of selection) and then the UI must visually cue the user that the selection was successful. Now, while that item is selected, the user must browse through a gridview to find an item within one of the other user controls and then select something. This sounds like an easy thing to manage but the code can get ugly. In my case, the user controls all sent event messages which were captured by the main page. This way, the page acted like a central processor of UI events and could keep track of what happens when the user is clicking around. So, in the main aspx page, we capture the first user control's event. using MyCompany.MyApp.Web.UseCases; protected void MyFirstUserControl_SomeUIWorkflowRequestCommingIn(object sender, EventArgs e) { // some code here to respond and make "state" changes or whatever // // blah blah blah // finally we have this (how did we know to call fish level method?? because we knew when we wrote the code to send the event in the user control) UpdateUserInterfaceOnFishLevelUseCaseGoalSuccess(FishLevel.SomeNamedUIWorkflow.SelectedItemForPurchase) } protected void UpdateUserInterfaceOnFishLevelGoalSuccess(FishLevel.SomeNamedUIWorkflow goal) { switch (goal) { case FishLevel.SomeNamedUIWorkflow.NewMasterItemSelected: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.DrillDownOnDetails: //call some UI related methods here including methods for the other user controls if necessary.... break; case FishLevel.SomeNamedUIWorkFlow.CancelMultiSelect: //call some UI related methods here including methods for the other user controls if necessary.... break; // more cases... } } } //also we have protected void UpdateUserInterfaceOnSeaLevelGoalSuccess(SeaLevel.SomeNamedUIWorkflow goal) { switch (goal) { case SeaLevel.CheckOutWorkflow.ChangedCreditCard: // do stuff // more cases... } } } So, in the MyCompany.MyApp.Web.UseCases namespace we might have code like this: class SeaLevel... class FishLevel... class KiteLevel... The workflow use cases embedded in the classes could be inner classes or static methods or enumerations or whatever gives you the cleanest namespace. I can't remember what I did originally but you get the picture.

    Read the article

  • How to find good looking font color if background color is known?

    - by Mecki
    There seem to be so many color wheel, color picker, and color matcher web apps out there, where you give one color and the they'll find a couple of other colors that will create a harmonic layout when being used in combination. However most of them focus on background colors only and any text printed on each background color (if text is printed at all in the preview) is either black or white. My problem is different. I know the background color I want to use for a text area. What I need help with is choosing a couple of colors (the more, the merrier) I can use as font colors on this background. Most important is that the color will make sure the font is readable (contrast not being too low, also maybe not being too high to avoid that eyes are stressed) and of course that the combination of foreground and background just looks good. Anyone being aware of such an application? I'd prefer a web application to anything I have to download. Thanks.

    Read the article

  • Is there any tool to standardize format of C++ code?

    - by BillyONeal
    Hello, all :) I'm looking for a tool that works on Windows to reformat some C++ code in my codebase. Essentially, I've got some code I wrote a while ago that I'd like to use, but it doesn't match the style I'm using in a more recent project. What's the best way to reformat C++ code in a standard manner? Billy3

    Read the article

  • Does this feature exist? Defining my own curly brackets in C#

    - by Carlos
    You'll appreciate the following two syntactic sugars: lock(obj) { //Code } same as: Monitor.Enter(obj) try { //Code } finally { Monitor.Exit(obj) } and using(var adapt = new adapter()){ //Code2 } same as: var adapt= new adapter() try{ //Code2 } finally{ adapt.Dispose() } Clearly the first example in each case is more readable. Is there a way to define this kind of thing myself, either in the C# language, or in the IDE? The reason I ask is that there are many similar usages (of the long kind) that would benefit from this, eg. if you're using ReaderWriterLockSlim, you want something pretty similar.

    Read the article

  • Java: Best practices for turning foreign horror-code into clean API...?

    - by java.is.for.desktop
    Hello, everyone! I have a project (related to graph algorithms). It is written by someone else. The code is horrible: public fields, no getters/setters huge methods, all public some classes have over 20 fields some classes have over 5 constructors (which are also huge) some of those constructors just left many fields null (so I can't make some fields final, because then every second constructor signals errors) methods and classes rely on each other in both directions I have to rewrite this into a clean and understandable API. Problem is: I myself don't understand anything in this code. Please give me hints on analyzing and understanding such code. I was thinking, perhaps, there are tools which perform static code analysis and give me call graphs and things like this.

    Read the article

  • Should java try blocks be scoped as tightly as possible?

    - by isme
    I've been told that there is some overhead in using the Java try-catch mechanism. So, while it is necessary to put methods that throw checked exception within a try block to handle the possible exception, it is good practice performance-wise to limit the size of the try block to contain only those operations that could throw exceptions. I'm not so sure that this is a sensible conclusion. Consider the two implementations below of a function that processes a specified text file. Even if it is true that the first one incurs some unnecessary overhead, I find it much easier to follow. It is less clear where exactly the exceptions come from just from looking at statements, but the comments clearly show which statements are responsible. The second one is much longer and complicated than the first. In particular, the nice line-reading idiom of the first has to be mangled to fit the readLine call into a try block. What is the best practice for handling exceptions in a funcion where multiple exceptions could be thrown in its definition? This one contains all the processing code within the try block: void processFile(File f) { try { // construction of FileReader can throw FileNotFoundException BufferedReader in = new BufferedReader(new FileReader(f)); // call of readLine can throw IOException String line; while ((line = in.readLine()) != null) { process(line); } } catch (FileNotFoundException ex) { handle(ex); } catch (IOException ex) { handle(ex); } } This one contains only the methods that throw exceptions within try blocks: void processFile(File f) { FileReader reader; try { reader = new FileReader(f); } catch (FileNotFoundException ex) { handle(ex); return; } BufferedReader in = new BufferedReader(reader); String line; while (true) { try { line = in.readLine(); } catch (IOException ex) { handle(ex); break; } if (line == null) { break; } process(line); } }

    Read the article

  • IF-block brackets: best practice

    - by MasterPeter
    I am preparing a short tutorial for level 1 uni students learning JavaScript basics. The task is to validate a phone number. The number must not contain non-digits and must be 14 digits long or less. The following code excerpt is what I came up with and I would like to make it as readable as possible. if ( //set of rules for invalid phone number phoneNumber.length == 0 //empty || phoneNumber.length > 14 //too long || /\D/.test(phoneNumber) //contains non-digits ) { setMessageText(invalid); } else { setMessageText(valid); } A simple question I can not quite answer myself and would like to hear your opinions on: How to position the surrounding (outermost) brackets? It's hard to see the difference between a normal and a curly bracket. Do you usually put the last ) on the same line as the last condition? Do you keep the first opening ( on a line by itself? Do you wrap each individual sub-condition in brackets too? Do you align horizontally the first ( with the last ), or do you place the last ) in the same column as the if? Do you keep ) { on a separate line or you place the last ) on the same line with the last sub-condition and then place the opening { on a new line? Or do you just put the ) { on the same line as the last sub-condition? Community wiki.

    Read the article

  • How can I implement NotOfType<T> in LINQ that has a nice calling syntax?

    - by Lette
    I'm trying to come up with an implementation for NotOfType, which has a readable call syntax. NotOfType should be the complement to OfType<T> and would consequently yield all elements that are not of type T My goal was to implement a method which would be called just like OfType<T>, like in the last line of this snippet: public abstract class Animal {} public class Monkey : Animal {} public class Giraffe : Animal {} public class Lion : Animal {} var monkey = new Monkey(); var giraffe = new Giraffe(); var lion = new Lion(); IEnumerable<Animal> animals = new Animal[] { monkey, giraffe, lion }; IEnumerable<Animal> fewerAnimals = animals.NotOfType<Giraffe>(); However, I can not come up with an implementation that supports that specific calling syntax. This is what I've tried so far: public static class EnumerableExtensions { public static IEnumerable<T> NotOfType<T>(this IEnumerable<T> sequence, Type type) { return sequence.Where(x => x.GetType() != type); } public static IEnumerable<T> NotOfType<T, TExclude>(this IEnumerable<T> sequence) { return sequence.Where(x => !(x is TExclude)); } } Calling these methods would look like this: // Animal is inferred IEnumerable<Animal> fewerAnimals = animals.NotOfType(typeof(Giraffe)); and // Not all types could be inferred, so I have to state all types explicitly IEnumerable<Animal> fewerAnimals = animals.NotOfType<Animal, Giraffe>(); I think that there are major drawbacks with the style of both of these calls. The first one suffers from a redundant "of type/type of" construct, and the second one just doesn't make sense (do I want a list of animals that are neither Animals nor Giraffes?). So, is there a way to accomplish what I want? If not, could it be possible in future versions of the language? (I'm thinking that maybe one day we will have named type arguments, or that we only need to explicitly supply type arguments that can't be inferred?) Or am I just being silly?

    Read the article

  • Using explicitly numbered repetition instead of question mark, star and plus

    - by polygenelubricants
    I've seen regex patterns that use explicitly numbered repetition instead of ?, * and +, i.e.: Explicit Shorthand (something){0,1} (something)? (something){1} (something) (something){0,} (something)* (something){1,} (something)+ The questions are: Are these two forms identical? What if you add possessive/reluctant modifiers? If they are identical, which one is more idiomatic? More readable? Simply "better"?

    Read the article

  • Why is there so much poorly indented code out there?

    - by dsimcha
    The more I browse the code to open source projects in languages that aren't Python, the more I realize that it seems a lot of programmers don't believe in proper indentation. (I won't mention any projects specifically to avoid having anyone take this question too personally.) Usually code is indented, but in a way just different enough from the standard style that it drives me crazy, especially in old/crufty code. I've noticed that when I write in C-like languages, I tend to indent correctly as religiously as when I'm writing in Python, with the exception of debugging code that I actually want to stick out like a sore thumb. Given how easy it is with a modern IDE to fix incorrect indentation, what are some rationales for not religiously keeping indentation in sync with braces?

    Read the article

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