Search Results

Search found 4617 results on 185 pages for 'coding crow'.

Page 16/185 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • if ('constant' == $variable) vs. if ($variable == 'constant')

    - by Tom Auger
    Lately, I've been working a lot in PHP and specifically within the WordPress framework. I'm noticing a lot of code in the form of: if ( 1 == $options['postlink'] ) Where I would have expected to see: if ( $options['postlink'] == 1 ) Is this a convention found in certain languages / frameworks? Is there any reason the former approach is preferable to the latter (from a processing perspective, or a parsing perspective or even a human perspective?) Or is it merely a matter of taste? I have always thought it better when performing a test, that the variable item being tested against some constant is on the left. It seems to map better to the way we would ask the question in natural language: "if the cake is chocolate" rather than "if chocolate is the cake".

    Read the article

  • Is writing comments inside methods not a good practice?

    - by Srini Kandula
    A friend told me that writing comments inside methods is not good. He said that we should have comments only for the method definitions(javadocs) but not inside the method body. It seems he read in a book that having comments inside the code means there is a problem in the code. I don't quite understand his reasoning. I think writing comments inside the method body is good and it helps other developers to understand it better and faster. Please provide your comments.

    Read the article

  • How to learn what the industry standards/expectations are, particularly with security?

    - by Aerovistae
    For instance, I was making my first mobile web-application about a year ago, and half-way through, someone pointed me to jQuery Mobile. Obviously this induced a total revolution in my app. Rewrote everything. Now, if you're in the field long enough, maybe that seems like common knowledge, but I was totally new to it. But this set me wondering: there are so many libraries and extensions and frameworks. This seems particularly crucial in the category of security. I'm afraid I'm going to find myself doing something in a professional setting eventually (I'm still a student) and someone's going to walk over and be like, My god, you're trying to secure user data that way? Don't you know about the Gordon-Wokker crypto-magic-hash-algorithms library? Without it you may as well go plaintext. How do you know what the best ways are to maximize security? Especially if you're trying to develop something on your own...

    Read the article

  • How to get feedback from the community on large chunks of code?

    - by MainMa
    Code Review.SE is great when you need feedback on a precise, short piece of code. But where to get similar feedback about the code itself when: you have thousands of LOC, don't have colleagues in your workplace ready or willing to review the code¹, don't have thousands of dollars to spend for a professional review by a third party developer?² Places like CodePlex are a good idea to get your project known³, but from what I've seen, the feedback you get on known projects are consumer feedback, i.e. concerns the bugs and feature requests, not the quality of the source code itself. What are the social way to get the community involved in the code review of the codebase of a certain size for an open source project which doesn't have the scale of Firefox or similar products? ¹ Which is the case for most personal and open source projects, or projects done in companies where the practice of regular and complete code review is nonexistent. ² Which is, again, the case for most personal and open source projects. ³ Even if too many projects published on CodePlex never get known, either because nobody cares or because they are presented not very well.

    Read the article

  • Should I sacrifice code succintness to ensure the narrowest variable scope? [duplicate]

    - by David Scholefield
    This question already has an answer here: Is the usage of internal scope blocks within a function bad style? 3 answers In many languages (e.g. both Perl and Java - which are the two languages I work most with) it is possible to narrow the scope of local variables by declaring them within a block. Although it adds extra code length (the opening and closing block braces), and possibly reduces readability, should I create blocks purely to narrow the scope of variables to the statements that use the variables and to uphold the principle of narrowest scope or does this sacrifice succinctness and readability just to unnecessarily uphold an agreed 'best practice' principle? I usually declare local variables to functions/methods at the start of the function to aid readability, but I could not do this, and just create blocks throughout the function and declare the variables throughout the code - within those blocks - to narrow their scope.

    Read the article

  • How do I organize a GUI application for passing around events and for setting up reads from a shared resource

    - by Savanni D'Gerinel
    My tools involved here are GTK and Haskell. My questions are probably pretty trivial for anyone who has done significant GUI work, but I've been off in the equivalent of CGI applications for my whole career. I'm building an application that displays tabular data, displays the same data in a graph form, and has an edit field for both entering new data and for editing existing data. After asking about sharing resources, I decided that all of the data involved will be stored in an MVar so that every component can just read the current state from the MVar. All of that works, but now it is time for me to rearrange the application so that it can be interactive. With that in mind, I have three widgets: a TextView (for editing), a TreeView (for displaying the data), and a DrawingArea (for displaying the data as a graph). I THINK I need to do two things, and the core of my question is, are these the right things, or is there a better way. Thing the first: All event handlers, those functions that will be called any time a redisplay is needed, need to be written at a high level and then passed into the function that actually constructs the widget to begin with. For instance: drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: (DrawingArea -> IO ()) -> IO VBox createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do graphs <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 return hbox In this case, createStatView builds up a VBox that contains a DrawingArea to graph the data and potentially other widgets. It attaches drawStatData to the realize and exposeEvent events for the DrawingArea. I would do something similar for the TreeView, but I am not completely sure what since I have not yet done it and what I am thinking of would involve replacing the TreeModel every time the TreeView needs to be updated. My alternative to the above would be... drawStatData :: DrawingArea -> MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO () createStatView :: IO (VBox, DrawingArea) ... but in this case, I would arrange createUI like so: createUI :: MVar Core.ST -> (Core.ST -> SetRepWorkout.WorkoutStore) -> IO HBox createUI storeMVar field = do (graphbox, graph) <- createStatView (\area -> drawStatData area storeMVar field) hbox <- hBoxNew False 10 boxPackStart hbox graphs PackNatural 0 on graph realize (drawStatData graph storeMVar field) on graph exposeEvent (do liftIO $ drawStatData graph storeMVar field return ()) return hbox I'm not sure which is better, but that does lead me to... Thing the second: it will be necessary for me to rig up an event system so that various events can send signals all the way to my widgets. I'm going to need a mediator of some kind to pass events around and to translate application-semantic events to the actual events that my widgets respond to. Is it better for me to pass my addressable widgets up the call stack to the level where the mediator lives, or to pass the mediator down the call stack and have the widgets register directly with it? So, in summary, my two questions: 1) pass widgets up the call stack to a global mediator, or pass the global mediator down and have the widgets register themselves to it? 2) pass my redraw functions to the builders and have the builders attach the redraw functions to the constructed widgets, or pass the constructed widgets back and have a higher level attach the redraw functions (and potentially link some widgets together)? Okay, and... 3) Books or wikis about GUI application architecture, preferably coherent architectures where people aren't arguing about minute details? The application in its current form (displays data but does not write data or allow for much interaction) is available at https://bitbucket.org/savannidgerinel/fitness . You can run the application by going to the root directory and typing runhaskell -isrc src/Main.hs data/ or... cabal build dist/build/fitness/fitness data/ You may need to install libraries, but cabal should tell you which ones.

    Read the article

  • Should you always pass the bare minimum data needed into a function

    - by Anders Holmström
    Let's say I have a function IsAdmin that checks whether a user is an admin. Let's also say that the admin checking is done by matching user id, name and password against some sort of rule (not important). In my head there are then two possible function signatures for this: public bool IsAdmin(User user); public bool IsAdmin(int id, string name, string password); I most often go for the second type of signature, thinking that: The function signature gives the reader a lot more info The logic contained inside the function doesn't have to know about the User class It usually results in slightly less code inside the function However I sometimes question this approach, and also realize that at some point it would become unwieldy. If for example a function would map between ten different object fields into a resulting bool I would obviously send in the entire object. But apart from a stark example like that I can't see a reason to pass in the actual object. I would appreciate any arguments for either style, as well as any general observations you might offer. I program in both object oriented and functional styles, so the question should be seen as regarding any and all idioms.

    Read the article

  • When to use typedef?

    - by futlib
    I'm a bit confused about if and when I should use typedef in C++. I feel it's a balancing act between readability and clarity. Here's a code sample without any typedefs: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { static std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int> lookup_table; std::map<std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator>, int>::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } Pretty ugly IMO. So I'll add some typedefs within the function to make it look nicer: int sum(std::vector<int>::const_iterator first, std::vector<int>::const_iterator last) { typedef std::tuple<std::vector<int>::const_iterator, std::vector<int>::const_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } The code is still a bit clumsy, but I get rid of most nightmare material. But there's still the int vector iterators, this variant gets rid of those: typedef std::vector<int>::const_iterator Input_iterator; int sum(Input_iterator first, Input_iterator last) { typedef std::tuple<Input_iterator, Input_iterator> Lookup_key; typedef std::map<Lookup_key, int> Lookup_table; static Lookup_table lookup_table; Lookup_table::iterator lookup_it = lookup_table.find(lookup_key); if (lookup_it != lookup_table.end()) return lookup_it->second; ... } This looks clean, but is it still readable? When should I use a typedef? As soon as I have a nightmare type? As soon as it occurs more than once? Where should I put them? Should I use them in function signatures or keep them to the implementation?

    Read the article

  • organization of DLL linked functions

    - by m25
    So this is a code organization question. I got my basic code working but when I expand it will be terrible. I have a DLL that I don't have a .lib for. Therefore I have to use the whole loadLibrary()/getprocaddress() combo. it works great. But this DLL that i'm referencing at 100+ functions. my current process is (1) typedef a type for the function. or typedef short(_stdcall *type1)(void); then (2) assign a function name that I want to use such as type1 function_1, then (3) I do the whole LoadLibrary, then do something like function_1 = (type1)GetProcAddress(hinstLib, "_mangled_funcName@5"); normally I would like to do all of my function definitions in a header file but because I have to do use the load library function, its not that easy. the code will be a mess. Right now i'm doing (1) and (2) in a header file and was considering making a function in another .cpp file to do the load library and dump all of the (3)'s in there. I considered using a namespace for the functions so I can use them in the main function and not have to pass over to the other function. Any other tips on how to organize this code to where it is readable and organized? My goals are to be able to use function_1 as a regular function in the main code. if I have to a ref::function_1 that would be okay but I would prefer to avoid it. this code for all practical purposes is just plane C at the moment. thanks in advance for any advice!

    Read the article

  • What is the worst programmer habit?

    - by 0x4a6f4672
    Many people get into programming because programming is fun. At least in the beginning. After some time doing it professionally, programming is no longer fun, often just hard work. Sometimes we develop bad habits along the way to make it fun again. Some bad habits of programmers are well known, for example the "I fix that in a second" habit, the "reinvent the wheel" practice or the "all code except mine is crap" attitude (which often leads to "I will re-write the entire program from scratch" syndrome). There are things which a programmer should never do. What is the worst programmer habit?

    Read the article

  • Use unnamed object to invoke method or not?

    - by Chen OT
    If I have a class with only only public method. When I use this class, is it good to use unnamed object to invoke its method? normal: TaxFileParser tax_parser(tax_file_name); auto content = tax_parser.get_content(); or unnamed object version: auto content = TaxFileParser(tax_file_name).get_content(); Because I've told that we should avoid temporary as possible. If tax_parser object is used only once, can I call it a temporary and try to eliminate it? Any suggestion will be helpful.

    Read the article

  • Functions that only call other functions. Is this a good practice?

    - by Eric C.
    I'm currently working on a set of reports that have many different sections (all requiring different formatting), and I'm trying to figure out the best way to structure my code. Similar reports we've done in the past end up having very large (200+ line) functions that do all of the data manipulation and formatting for the report, such that the workflow looks something like this: DataTable reportTable = new DataTable(); void RunReport() { reportTable = DataClass.getReportData(); largeReportProcessingFunction(); outputReportToUser(); } I would like to be able to break these large functions up into smaller chunks, but I'm afraid that I'll just end up having dozens of non-reusable functions, and a similar "do everything here" function whose only job is to call all these smaller functions, like so: void largeReportProcessingFunction() { processSection1HeaderData(); calculateSection1HeaderAverages(); formatSection1HeaderDisplay(); processSection1SummaryTableData(); calculateSection1SummaryTableTotalRow(); formatSection1SummaryTableDisplay(); processSection1FooterData(); getSection1FooterSummaryTotals(); formatSection1FooterDisplay(); processSection2HeaderData(); calculateSection1HeaderAverages(); formatSection1HeaderDisplay(); calculateSection1HeaderAverages(); ... } Or, if we go one step further: void largeReportProcessingFunction() { callAllSection1Functions(); callAllSection2Functions(); callAllSection3Functions(); ... } Is this really a better solution? From an organizational point of view I suppose it is (i.e. everything is much more organized than it might otherwise be), but as far as code readability I'm not sure (potentially large chains of functions that only call other functions). Thoughts?

    Read the article

  • Should I use parentheses in logical statements even where not necessary?

    - by Jeff Bridgman
    Let's say I have a boolean condition a AND b OR c AND d and I'm using a language where AND has a higher order of operation precedent than OR. I could write this line of code: If (a AND b) OR (c AND d) Then ... But really, that's equivalent to: If a AND b OR c AND d Then ... Are there any arguments in for or against including the extraneous parentheses? Does practical experience suggest that it is worth including them for readability? Or is it a sign that a developer needs to really sit down and become confident in the basics of their language?

    Read the article

  • Assignments in mock return values

    - by zerkms
    (I will show examples using php and phpunit but this may be applied to any programming language) The case: let's say we have a method A::foo that delegates some work to class M and returns the value as-is. Which of these solutions would you choose: $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue('baz')); $obj = new A($mock); $this->assertEquals('baz', $obj->foo()); or $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue($result = 'baz')); $obj = new A($mock); $this->assertEquals($result, $obj->foo()); or $result = 'baz'; $mock = $this->getMock('M'); $mock->expects($this->once()) ->method('bar') ->will($this->returnValue($result)); $obj = new A($mock); $this->assertEquals($result, $obj->foo()); Personally I always follow the 2nd solution, but just 10 minutes ago I had a conversation with couple of developers who said that it is "too tricky" and chose 3rd or 1st. So what would you usually do? And do you have any conventions to follow in such cases?

    Read the article

  • creative & complex vs simple and readable

    - by Shirish11
    Which is a better option? Its not always that when you have something creative your code is going to look ugly. But at times it does go a bit ugly. e.g. if ( (object1(0)==object2(0) && (object1(1)==object2(1) && (object1(2)==object2(2) && (object1(3)==object2(3)){ retval = true; else retval = false; is simple and readable bool retValue = (object1(0)==object2(0)) && (object1(1)==object2(1)) && (object1(2)==object2(2)) && (object1(3)==object2(3)); but having something like this will make some newbies scratch their heads. So what do I go for? including simple code everywhere might sometime hamper my performance. what I could think of was commenting wherever necessary but at times u get too curious to know what is actually happening. Any suggestions are welcome.

    Read the article

  • Naming conventions for newtype deconstructors (destructors?)

    - by Petr Pudlák
    Looking into Haskell's standard library we can see: newtype StateT s m a = StateT { runStateT :: s -> m (a, s) } newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a } newtype Sum a = Sum { getSum :: a } Apparently, there (at least) 3 different prefixes used to unwrap a value inside a newtype: un-, run- and get-. (Moreover run- and get- capitalizes the next letter while un- doesn't.) This seems confusing. Are there any reasons for that, or is that just a historical thing? If I design my own newtype, what prefix should I use and why?

    Read the article

  • Where should I define constants in scripts?

    - by bshacklett
    When writing scripts using a modern scripting language, e.g. Powershell or JavaScript, where should I define constants? Should I make all constants global for readability and ease of use, or does it make sense to define constants as close to their scopes as possible (in a function, for instance, if it's not needed elsewhere)? I'm thinking mostly of error messages, error IDs, paths to resources or configuration options.

    Read the article

  • Reformatting and version control

    - by l0b0
    Code formatting matters. Even indentation matters. And consistency is more important than minor improvements. But projects usually don't have a clear, complete, verifiable and enforced style guide from day 1, and major improvements may arrive any day. Maybe you find that SELECT id, name, address FROM persons JOIN addresses ON persons.id = addresses.person_id; could be better written as / is better written than SELECT persons.id, persons.name, addresses.address FROM persons JOIN addresses ON persons.id = addresses.person_id; while working on adding more columns to the query. Maybe this is the most complex of all four queries in your code, or a trivial query among thousands. No matter how difficult the transition, you decide it's worth it. But how do you track code changes across major formatting changes? You could just give up and say "this is the point where we start again", or you could reformat all queries in the entire repository history. If you're using a distributed version control system like Git you can revert to the first commit ever, and reformat your way from there to the current state. But it's a lot of work, and everyone else would have to pause work (or be prepared for the mother of all merges) while it's going on. Is there a better way to change history which gives the best of all results: Same style in all commits Minimal merge work ? To clarify, this is not about best practices when starting the project, but rather what should be done when a large refactoring has been deemed a Good Thing™ but you still want a traceable history? Never rewriting history is great if it's the only way to ensure that your versions always work the same, but what about the developer benefits of a clean rewrite? Especially if you have ways (tests, syntax definitions or an identical binary after compilation) to ensure that the rewritten version works exactly the same way as the original?

    Read the article

  • Why Should I Avoid Inline Scripting?

    - by thesunneversets
    A knowledgeable friend recently looked at a website I helped launch, and commented something like "very cool site, shame about the inline scripting in the source code". I'm definitely in a position to remove the inline scripting where it occurs; I'm vaguely aware that it's "a bad thing". My question is: what are the real problems with inline scripting? Is there a significant performance issue, or is it mostly just a matter of good style? Can I justify immediate action on the inline scripting front to my superiors, when there are other things to work on that might have a more obvious impact on the site? If you pulled up to a website, and took a peek at the source code, what factors would lead you to say "hmm, professional work here", and what would cause you to recoil from an obviously amateurish job? Okay, that question turned into multiple questions in the writing. But basically, inline scripting - what's the deal?

    Read the article

  • Strict C++ guidelines [on hold]

    - by Banex
    Some time ago I ran across an answer here on Programmers that linked a Wikipedia page about some strict guidelines for C++. The only thing I remember is that it didn't allow exceptions and was in general very strict, and that it was used in many workplaces where most C++ features are not considered useful, or are not available (embedded systems, etc). I'd like to know the name of those guidelines, as I searched the whole internet without finding it.

    Read the article

  • How do you proactively guard against errors of omission?

    - by Gabriel
    I'll preface this with I don't know if anyone else who's been programming as long as I have actually has this problem, but at the very least, the answer might help someone with less xp. I just stared at this code for 5 minutes, thinking I was losing my mind that it didn't work: var usedNames = new HashSet<string>(); Func<string, string> l = (s) => { for (int i = 0; ; i++) { var next = (s + i).TrimEnd('0'); if (!usedNames.Contains(next)) { return next; } } }; Finally I noticed I forgot to add the used name to the hash set. Similarly, I've spent minutes upon minutes over omitting context.SaveChanges(). I think I get so distracted by the details that I'm thinking about that some really small details become invisible to me - it's almost at the level of mental block. Are there tactics to prevent this? update: a side effect of asking this was fixing the error it would have for i 9 (Thanks!) var usedNames = new HashSet<string>(); Func<string, string> name = (s) => { string result = s; if(usedNames.Contains(s)) for (int i = 1; ; result = s + i++) if (!usedNames.Contains(result)) break; usedNames.Add(result); return result; };

    Read the article

  • Using 'new' in a projection?

    - by davenewza
    I wish to project a collection from one type (Something) to another type (SomethingElse). Yes, this is a very open-eneded question, but which of the two options below do you prefer? Creating a new instance using new: var result = query.Select(something => new SomethingElse(something)); Using a factory: var result = query.Select(something => SomethingElse.FromSomething(something)); When I think of a projection, I generally think of it as a conversion. Using new gives me this idea that I'm creating new objects during a conversion, which doesn't feel right. Semantically, SomethingElse.FromSomething() most definitely fits better. Although, the second option does require addition code to setup a factory, which could become unnecessarily compulsive.

    Read the article

  • What's wrong with circular references?

    - by dash-tom-bang
    I was involved in a programming discussion today where I made some statements that basically assumed axiomatically that circular references (between modules, classes, whatever) are generally bad. Once I got through with my pitch, my coworker asked, "what's wrong with circular references?" I've got strong feelings on this, but it's hard for me to verbalize concisely and concretely. Any explanation that I may come up with tends to rely on other items that I too consider axioms ("can't use in isolation, so can't test", "unknown/undefined behavior as state mutates in the participating objects", etc.), but I'd love to hear a concise reason for why circular references are bad that don't take the kinds of leaps of faith that my own brain does, having spent many hours over the years untangling them to understand, fix, and extend various bits of code. Edit: I am not asking about homogenous circular references, like those in a doubly-linked list or pointer-to-parent. This question is really asking about "larger scope" circular references, like libA calling libB which calls back to libA. Substitute 'module' for 'lib' if you like. Thanks for all of the answers so far!

    Read the article

  • Is it bad style to redundantly check a condition?

    - by mcwise
    I often get to positions in my code where I find myself checking a specific condition over and over again. I want to give you a small example: suppose there is a text file which contains lines starting with "a", lines starting with "b" and other lines and I actually only want to work with the first two sort of lines. My code would look something like this (using python, but read it as pseudocode): # ... clear_lines() # removes every other line than those starting with "a" or "b" for line in lines: if (line.startsWith("a")): # do stuff if (line.startsWith("b")): # magic else: # this else is redundant, I already made sure there is no else-case # by using clear_lines() # ... You can imagine I won't only check this condition here, but maybe also in other functions and so on. Do you think of it as noise or does it add some value to my code?

    Read the article

  • What do you do when working with multiple languages with different capitalization schemes?

    - by dvcolgan
    I'm making a webapp using Django. The Python convention for naming variables is lowercase_with_underscores, but the Javascript convention is camelCase. In addition, I've seen many people use lowercase-with-hyphens for CSS identifiers. Would you suggest using all three naming conventions where appropriate, or picking one and using it, even if the other two recommend something else? Switching back and forth isn't a huge problem, but it can still be mental overhead.

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >