Search Results

Search found 406 results on 17 pages for 'dry'.

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

  • DRY, string, and unit testing

    - by Rodrigue
    I have a recurring question when writing unit tests for code that involves constant string values. Let's take an example of a method/function that does some processing and returns a string containing a pre-defined constant. In python, that would be something like: STRING_TEMPLATE = "/some/constant/string/with/%s/that/needs/interpolation/" def process(some_param): # We do some meaningful work that gives us a value result = _some_meaningful_action() return STRING_TEMPLATE % result If I want to unit test process, one of my tests will check the return value. This is where I wonder what the best solution is. In my unit test, I can: apply DRY and use the already defined constant repeat myself and rewrite the entire string def test_foo_should_return_correct_url(): string_result = process() # Applying DRY and using the already defined constant assert STRING_TEMPLATE % "1234" == string_result # Repeating myself, repeating myself assert "/some/constant/string/with/1234/that/needs/interpolation/" == url The advantage I see in the former is that my test will break if I put the wrong string value in my constant. The inconvenient is that I may be rewriting the same string over and over again across different unit tests.

    Read the article

  • How do you keep SOA DRY?

    - by TaylorOtwell
    In our organization, we've shifted to a more "service oriented architecture". To give an example, let's assume we need to retrieve a "Quote" object. This quote has a shipper, a consignee, phone numbers, contacts, email addresses, and other location information. In other words, a Quote object is made up of many other objects. So, it seems like it would make sense to make a "Quote Retrieval Service". In our situation, we've accomplished this by creating a .NET solution and writing the service. The service API looks something like this (in pseudo-code): Function GetQuote(String ID) Returns Quote So, so far so good. Now, when this service is consumed, to keep things "de-coupled", we are creating essentially a duplicate of the Quote object and mapping from the QuoteService version of the Quote into the consumer's version of the Quote. In many cases, these classes will have the exact same properties. So, if the Quote service is consumed by 5 other applications, we would have 6 definitions of what a "Quote" is. One for each consumer, and one for the service. This feels wrong. I thought code was supposed to be DRY, but it seems like our method of SOA is forcing us to create tons of duplicated class definitions. What are we doing wrong, or is the code duplication just a "necessary evil" of SOA?

    Read the article

  • Violation of the DRY Principle

    - by Onorio Catenacci
    I am sure there's a name for this anti-pattern somewhere; however I am not familiar enough with the anti-pattern literature to know it. Consider the following scenario: or0 is a member function in a class. For better or worse, it's heavily dependent on class member variables. Programmer A comes along and needs functionality like or0 but rather than calling or0, Programmer A copies and renames the entire class. I'm guessing that she doesn't call or0 because, as I say, it's heavily dependent on member variables for its functionality. Or maybe she's a junior programmer and doesn't know how to call it from other code. So now we've got or0 and c0 (c for copy). I can't completely fault Programmer A for this approach--we all get under tight deadlines and we hack code to get work done. Several programmers maintain or0 so it's now version orN. c0 is now version cN. Unfortunately most of the programmers that maintained the class containing or0 seemed to be completely unaware of c0--which is one of the strongest arguments I can think of for the wisdom of the DRY principle. And there may also have been independent maintainance of the code in c. Either way it appears that or0 and c0 were maintained independent of each other. And, joy and happiness, an error is occurring in cN that does not occur in orN. So I have a few questions: 1.) Is there a name for this anti-pattern? I've seen this happen so often I'd find it hard to believe this is not a named anti-pattern. 2.) I can see a few alternatives: a.) Fix orN to take a parameter that specifies the values of all the member variables it needs. Then modify cN to call orN with all of the needed parameters passed in. b.) Try to manually port fixes from orN to cN. (Mind you I don't want to do this but it is a realistic possibility.) c.) Recopy orN to cN--again, yuck but I list it for sake of completeness. d.) Try to figure out where cN is broken and then repair it independently of orN. Alternative a seems like the best fix in the long term but I doubt the customer will let me implement it. Never time or money to fix things right but always time and money to repair the same problem 40 or 50 times, right? Can anyone suggest other approaches I may not have considered? If you were in my place, which approach would you take? If there are other questions and answers here along these lines, please post links to them. I don't mind removing this question if it's a dupe but my searching hasn't turned up anything that addresses this question yet. EDIT: Thanks everyone for all the thoughtful responses. I asked about a name for the anti-pattern so I could research it further on my own. I'm surprised this particular bad coding practice doesn't seem to have a "canonical" name for it.

    Read the article

  • Is goto to improve DRY-ness OK?

    - by Marco Scannadinari
    My code has many checks to detect errors in various cases (many conditions would result in the same error), inside a function returning an error struct. Instead of looking like this: err_struct myfunc(...) { err_struct error = { .error = false }; ... if(something) { error.error = true; error.description = "invalid input"; return error; } ... case 1024: error.error = true; error.description = "invalid input"; // same error, but different detection scenario return error; break; // don't comment on this break please (EDIT: pun unintended) ... Is use of goto in the following context considered better than the previous example? err_struct myfunc(...) { err_struct error = { .error = false }; ... if(something) goto invalid_input; ... case 1024: goto invalid_input; break; return error; invalid_input: error.error = true; error.description = "invalid input"; return error;

    Read the article

  • Repository query conditions, dependencies and DRY

    - by vFragosop
    To keep it simple, let's suppose an application which has Accounts and Users. Each account may have any number of users. There's also 3 consumers of UserRepository: An admin interface which may list all users Public front-end which may list all users An account authenticated API which should only list it's own users Assuming UserRepository is something like this: class UsersRepository extends DatabaseAbstraction { private function query() { return $this->database()->select('users.*'); } public function getAll() { return $this->query()->exec(); } // IMPORTANT: // Tons of other methods for searching, filtering, // joining of other tables, ordering and such... } Keeping in mind the comment above, and the necessity to abstract user querying conditions, How should I handle querying of users filtering by account_id? I can picture three possible roads: 1. Should I create an AccountUsersRepository? class AccountUsersRepository extends UserRepository { public function __construct(Account $account) { $this->account = $account; } private function query() { return parent::query() ->where('account_id', '=', $this->account->id); } } This has the advantage of reducing the duplication of UsersRepository methods, but doesn't quite fit into anything I've read about DDD so far (I'm rookie by the way) 2. Should I put it as a method on AccountsRepository? class AccountsRepository extends DatabaseAbstraction { public function getAccountUsers(Account $account) { return $this->database() ->select('users.*') ->where('account_id', '=', $account->id) ->exec(); } } This requires the duplication of all UserRepository methods and may need another UserQuery layer, that implements those querying logic on chainable way. 3. Should I query UserRepository from within my account entity? class Account extends Entity { public function getUsers() { return UserRepository::findByAccountId($this->id); } } This feels more like an aggregate root for me, but introduces dependency of UserRepository on Account entity, which may violate a few principles. 4. Or am I missing the point completely? Maybe there's an even better solution? Footnotes: Besides permissions being a Service concern, in my understanding, they shouldn't implement SQL query but leave that to repositories since those may not even be SQL driven.

    Read the article

  • Implementing dry-run in bash scripts

    - by Apikot
    How would one implement a dry-run option in a bash script? I can think of either wrapping every single command in an if and echoing out the command instead of running it if the script is running with dry-run. Another way would be to define a function and then passing each command call through that function. Something like: function _run () { if [[ "$DRY_RUN" ]]; then echo $@ else $@ fi } _run mv /tmp/file /tmp/file2 DRY_RUN=true _run mv /tmp/file /tmp/file2 Is this just wrong and there is a much better way of doing it?

    Read the article

  • DRY vs Security and Maintainability with MVC and View Models

    - by Mystere Man
    I like to strive for DRY, and obviously it's not always possible. However, I have to scratch my head over a concept that seems pretty common in MVC, that of the "View Model". The View Model is designed to only pass the minimum amount of information to the view, for both security, maintainability, and testing concerns. I get that. It makes sense. However, from a DRY perspective, a View Model is simply duplicating data you already have. The View Model may be temporary, and used only as a DTO, but you're basically maintaing two different versions of the same model which seems to violate the DRY principal. Do View Models violate DRY? Are they a necessary evil? Do they do more good than bad?

    Read the article

  • Rails: keeping DRY with ActiveRecord models that share similar complex attributes

    - by Greg
    This seems like it should have a straightforward answer, but after much time on Google and SO I can't find it. It might be a case of missing the right keywords. In my RoR application I have several models that share a specific kind of string attribute that has special validation and other functionality. The closest similar example I can think of is a string that represents a URL. This leads to a lot of duplication in the models (and even more duplication in the unit tests), but I'm not sure how to make it more DRY. I can think of several possible directions... create a plugin along the lines of the "validates_url_format_of" plugin, but that would only make the validations DRY give this special string its own model, but this seems like a very heavy solution create a ruby class for this special string, but how do I get ActiveRecord to associate this class with the model attribute that is a string in the db Number 3 seems the most reasonable, but I can't figure out how to extend ActiveRecord to handle anything other than the base data types. Any pointers? Finally, if there is a way to do this, where in the folder hierarchy would you put the new class that is not a model? Many thanks.

    Read the article

  • DRY URL's in Django Javascript

    - by Noio
    I'm using Django on Appengine. I'm using the django reverse() function everywhere, keeping everything as DRY as possible. However, I'm having trouble applying this to my client-side javascript. There is a JS class that loads some data depending on a passed-in ID. Is there a standard way to not-hardcode the URL that this data should come from? var rq = new Request.HTML({ 'update':this.element, }).get('/template/'+template_id+'/preview'); //The part that bothers me.

    Read the article

  • Evil DRY

    - by StefanSteinegger
    DRY (Don't Repeat Yourself) is a basic software design and coding principle. But there is just no silver bullet. While DRY should increase maintainability by avoiding common design mistakes, it could lead to huge maintenance problems when misunderstood. The root of the problem is most probably that many developers believe that DRY means that any piece of code that is written more then once should be made reusable. But the principle is stated as "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." So the important thing here is "knowledge". Nobody ever said "every piece of code". I try to give some examples of misusing the DRY principle. Code Repetitions by Coincidence There is code that is repeated by pure coincidence. It is not the same code because it is based on the same piece of knowledge, it is just the same by coincidence. It's hard to give an example of such a case. Just think about some lines of code the developer thinks "I already wrote something similar". Then he takes the original code, puts it into a public method, even worse into a base class where none had been there before, puts some weird arguments and some if or switch statements into it to support all special cases and calls this "increasing maintainability based on the DRY principle". The resulting "reusable method" is usually something the developer not even can give a meaningful name, because its contents isn't anything specific, it is just a bunch of code. For the same reason, nobody will really understand this piece of code. Typically this method only makes sense to call after some other method had been called. All the symptoms of really bad design is evident. Fact is, writing this kind of "reusable methods" is worse then copy pasting! Believe me. What will happen when you change this weird piece of code? You can't say what'll happen, because you can't understand what the code is actually doing. So better don't touch it anymore. Maintainability just died. Of course this problem is with any badly designed code. But because the developer tried to make this method as reusable as possible, large parts of the system get dependent on it. Completely independent parts get tightly coupled by this common piece of code. Changing on the single common place will have effects anywhere in the system, a typical symptom of too tight coupling. Without trying to dogmatically (and wrongly) apply the DRY principle, you just had a system with a weak design. Now you get a system which just can't be maintained anymore. So what can you do against it? When making code reusable, always identify the generally reusable parts of it. Find the reason why the code is repeated, find the common "piece of knowledge". If you have to search too far, it's probably not really there. Explain it to a colleague, if you can't explain or the explanation is to complicated, it's probably not worth to reuse. If you identify the piece of knowledge, don't forget to carefully find the place where it should be implemented. Reusing code is never worth giving up a clean design. Methods always need to do something specific. If you can't give it a simple and explanatory name, you did probably something weird. If you can't find the common piece of knowledge, try to make the code simpler. For instance, if you have some complicated string or collection operations within this code, write some general-purpose operations into a helper class. If your code gets simple enough, its not so bad if it can't be reused. If you are not able to find anything simple and reasonable, copy paste it. Put a comment into the code to reference the other copies. You may find a solution later. Requirements Repetitions by Coincidence Let's assume that you need to implement complex tax calculations for many countries. It's possible that some countries have very similar tax rules. These rules are still completely independent from each other, since every country can change it of its own. (Assumed that this similarity is actually by coincidence and not by political membership. There might be basic rules applying to all European countries. etc.) Let's assume that there are similarities between an Asian country and an African country. Moving the common part to a central place will cause problems. What happens if one of the countries changes its rules? Or - more likely - what happens if users of one country complain about an error in the calculation? If there is shared code, it is very risky to change it, even for a bugfix. It is hard to find requirements to be repeated by coincidence. Then there is not much you can do against the repetition of the code. What you really should consider is to make coding of the rules as simple as possible. So this independent knowledge "Tax Rules in Timbuktu" or wherever should be as pure as possible, without much overhead and stuff that does not belong to it. So you can write every independent requirement short and clean. DRYing try-catch and using Blocks This is a technical issue. Blocks like try-catch or using (e.g. in C#) are very hard to DRY. Imagine a complex exception handling, including several catch blocks. When the contents of the try block as well as the contents of the individual catch block are trivial, but the whole structure is repeated on many places in the code, there is almost no reasonable way to DRY it. try { // trivial code here using (Thingy thing = new thingy) { //trivial, but always different line of code } } catch(FooException foo) { // trivial foo handling } catch (BarException bar) { // trivial bar handling } catch { // trivial common handling } finally { // trivial finally block } The key here is that every block is trivial, so there is nothing to just move into a separate method. The only part that differs from case to case is the line of code in the body of the using block (or any other block). The situation is especially interesting if the many occurrences of this structure are completely independent: they appear in classes with no common base class, they don't aggregate each other and so on. Let's assume that this is a common pattern in service methods within the whole system. Examples of Evil DRYing in this situation: Put a if or switch statement into the method to choose the line of code to execute. There are several reasons why this is not a good idea: The close coupling of the formerly independent implementation is the strongest. Also the readability of the code and the use of a parameter to control the logic. Put everything into a method which takes a delegate as argument to call. The caller just passes his "specific line of code" to this method. The code will be very unreadable. The same maintainability problems apply as for any "Code Repetition by Coincidence" situations. Enforce a base class to all the classes where this pattern appears and use the template method pattern. It's the same readability and maintainability problem as above, but additionally complex and tightly coupled because of the base class. I would call this "Inheritance by Coincidence" which will not lead to great software design. What can you do against it: Ideally, the individual line of code is a call to a class or interface, which could be made individual by inheritance. If this would be the case, it wouldn't be a problem at all. I assume that it is no such a trivial case. Consider to refactor the error concept to make error handling easier. The last but not worst option is to keep the replications. Some pattern of code must be maintained in consistency, there is nothing we can do against it. And no reason to make it unreadable. Conclusion The DRY-principle is an important and basic principle every software developer should master. The key is to identify the "pieces of knowledge". There is code which can't be reused easily because of technical reasons. This requires quite a bit flexibility and creativity to make code simple and maintainable. It's not the problem of the principle, it is the problem of blindly applying a principle without understanding the problem it should solve. The result is mostly much worse then ignoring the principle.

    Read the article

  • Implementing DRY Forms

    - by virtualeyes
    Getting into Play 2.0, overall, blown away, great stuff. Anyway, wondering how one can achieve DRY forms in Play? If you look at the create & edit examples in the Computer Database Sample, you'll see that the form elements are repeated. With just 4 fields (in the sample form), no big deal, but when you're dealing with large, complex forms and/or handling many CRUD models, the duplication becomes a bigger maintenance issue. On the binding end ( form.bindFromRequest and form.fill(Foo) ), the implementation is so elegant for create/edit operations; is there a corresponding solution in the template layer?

    Read the article

  • How to make this C++ code more DRY?

    - by Macha
    I have these two methods on a class that differ only in one method call. Obviously, this is very un-DRY, especially as both use the same formula. int PlayerCharacter::getAttack() { attack = 1 + this.level; for(int i = 0; i <= current_equipment; i++) { attack += this.equipment[i].getAttack(); } attack *= sqrt(this.level); return attack; } int PlayerCharacter::getDefense() { defense = 1 + this.level; for(int i = 0; i <= current_equipment; i++) { defense += this.equipment[i].getDefense(); } defense *= sqrt(this.level); return defense; } How can I tidy this up in C++?

    Read the article

  • How do you keep your business rules DRY?

    - by Mario
    I periodically ponder how to best design an application whose every business rule exists in just a single location. (While I know there is no proverbial “best way” and that designs are situational, people must have a leaning toward one practice or another.) I work for a shop where they prefer to house as much of the business rules as possible in the database. This requires developers in many cases to perform identical front-end validations to avoid sending data to the database that will result in an exception—not very DRY. It grates me anytime I find myself duplicating any kind of logic—even lowly validation logic. I am a single-point-of-truth purist to an anal degree. On the other end of the spectrum, I know of shops that create dumb databases (the Rails community leans in this direction) and handle all of the business logic in a separate tier (in Rails the models would house “most” of this). Note the word “most” which implies that some business logic does end up spilling into other places (in Rails it might spill over into the controllers). In way, a clean separation of concerns where all business logic exists in a single core location is a Utopian fantasy that’s hard to uphold (n-tiered architecture or not). Furthermore, is see the “Database as a fortress” and would agree that it should be built on constraints that cause it to reject bad data. As such, I hold principles that cause a degree of angst as I attempt to balance them. How do you balance the database-as-a-fortress view with the desire to have a single-point-of-truth?

    Read the article

  • Django DRY Feeds

    - by Mandx
    I'm using the Django Feeds Framework and it's really nice, very intuitive and easy to use. But, I think there is a problem when creating links to feeds in HTML. For example: <link rel="alternate" type="application/rss+xml" title="{{ feed_title }}" href="{{ url_of_feed }}" /> Link's HREF attribute can be easily found out, just use reverse() But, what about the TITLE attribute? Where the template engine should look for this? Even more, what if the feed is build up dinamically and the title depends on parameters (like this)? I can't come up with a solution that "seems" DRY to me... All that I can come up with is using context processors o template tags, but it gets messy when the context procesor/template tag has to find parameters to construct the Feed class, and writing this I realize I don't even know how to create a Feed instance myself within the view. If I put all this logic in the view, it would not be just one view. Also, the value for TITLE would be in the view AND in the feed.

    Read the article

  • How to "DRY up" C# attributes in Models and ViewModels?

    - by DanM
    This question was inspired by my struggles with ASP.NET MVC, but I think it applies to other situations as well. Let's say I have an ORM-generated Model and two ViewModels (one for a "details" view and one for an "edit" view): Model public class FooModel // ORM generated { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public int Age { get; set; } public int CategoryId { get; set; } } Display ViewModel public class FooDisplayViewModel // use for "details" view { [DisplayName("ID Number")] public int Id { get; set; } [DisplayName("First Name")] public string FirstName { get; set; } [DisplayName("Last Name")] public string LastName { get; set; } [DisplayName("Email Address")] [DataType("EmailAddress")] public string EmailAddress { get; set; } public int Age { get; set; } [DisplayName("Category")] public string CategoryName { get; set; } } Edit ViewModel public class FooEditViewModel // use for "edit" view { [DisplayName("First Name")] // not DRY public string FirstName { get; set; } [DisplayName("Last Name")] // not DRY public string LastName { get; set; } [DisplayName("Email Address")] // not DRY [DataType("EmailAddress")] // not DRY public string EmailAddress { get; set; } public int Age { get; set; } [DisplayName("Category")] // not DRY public SelectList Categories { get; set; } } Note that the attributes on the ViewModels are not DRY--a lot of information is repeated. Now imagine this scenario multiplied by 10 or 100, and you can see that it can quickly become quite tedious and error prone to ensure consistency across ViewModels (and therefore across Views). How can I "DRY up" this code? Before you answer, "Just put all the attributes on FooModel," I've tried that, but it didn't work because I need to keep my ViewModels "flat". In other words, I can't just compose each ViewModel with a Model--I need my ViewModel to have only the properties (and attributes) that should be consumed by the View, and the View can't burrow into sub-properties to get at the values. Update LukLed's answer suggests using inheritance. This definitely reduces the amount of non-DRY code, but it doesn't eliminate it. Note that, in my example above, the DisplayName attribute for the Category property would need to be written twice because the data type of the property is different between the display and edit ViewModels. This isn't going to be a big deal on a small scale, but as the size and complexity of a project scales up (imagine a lot more properties, more attributes per property, more views per model), there is still the potentially for "repeating yourself" a fair amount. Perhaps I'm taking DRY too far here, but I'd still rather have all my "friendly names", data types, validation rules, etc. typed out only once.

    Read the article

  • DRY Validation with MVC2

    - by Matthew
    Hi All, I'm trying to figure out how I can define validation rules for my domain objects in one single location within my application but have run in to a snag... Some background: My location has several parts: - Database - DAL - Business Logic Layer - SOAP API Layer - MVC website The MVC website accesses the database via the SOAP API, just as third parties would. We are using server and and client side validation on the MVC website as well as in the SOAP API Layer. To avoid having to manually write client side validation we are implementing strongly typed views in conjunction with the Html.TextBoxFor and Html.ValidationMessageFor HTML helpers, as shown in Step 3 here. We also create custom models for each form where one form takes input for multiple domain objects. This is where the problem begins, the HTML helpers read from the model for the data annotation validation attributes. In most cases our forms deal with multiple domain objects and you can't specify more than one type in the <%@Page ... Inherits="System.Web.Mvc.ViewPage" % page directive. So we are forced to create a custom model class, which would mean duplicating validation attributes from the domain objects on to the model class. I've spent quite some time looking for workarounds to this, such has referencing the same MetadataType from both the domain class and the custom MVC models, but that won't work for several reasons: You can only specify one MetadataType attribute per class, so its a problem if a model references multiple domain objects, each with their own metadata type. The data annotation validation code throws an exception if the model class doesn't contain a property that is specified in the referenced MetadataType which is a problem with the model only deals with a subset of the properties for a given domain object. I've looked at other solutions as well but to no avail. If anyone has any ideas on how to achieve a single source for validation logic that would work across MVC client and server side validation functionality and other locations (such as my SOAP API) I would love to hear it! Thanks in advance, Matthew

    Read the article

  • Rails: DRY in views, I need help

    - by Totty
    Hy, I have a layout in the views/layout that has 2 cols and then in every view i have content_for :main_col and content_for :side_col. The problem is that i have more than 5 views with the same content in the content_for :side_col You have a better idea on how to do this?thanks

    Read the article

  • How do I DRY up my CouchDB views?

    - by James A. Rosen
    What can I do to share code among views in CouchDB? Example 1 -- utility methods Jesse Hallett has some good utility methods, including function dot(attr) { return function(obj) { return obj[attr]; } } Array.prototype.map = function(func) { var i, r = [], for (i = 0; i < this.length; i += 1) { r[i] = func(this[i]); } return r; }; ... Where can I put this code so every view can access it? Example 2 -- constants Similarly for constants I use in my application. Where do I put MyApp = { A_CONSTANT = "..."; ANOTHER_CONSTANT = "..."; }; Example 3 -- filter of a filter: What if I want a one view that filters by "is this a rich person?": function(doc) { if (doc.type == 'person' && doc.net_worth > 1000000) { emit(doc.id, doc); } } and another that indexes by last name: function(doc) { if (doc.last_name) { emit(doc.last_name, doc); } } How can I combine them into a "rich people by last name" view? I sort of want the equivalent of the Ruby my_array.select { |x| x.person? }.select { |x| x.net_worth > 1,000,000 }.map { |x| [x.last_name, x] } How can I be DRYer?

    Read the article

  • Django + jQuery: Sometimes AJAX, but always DRY?

    - by Justin Myles Holmes
    Let's say I have an app (in Django) for which I want to sometimes (but not always) load content via ajax. An easy example is logging in. When the user logs in, I don't want to refresh the page, just change things around. Yet, if they are already logged in, and then arrive at (or refresh) the same page, I want it to show the same content. So, in the first case, obviously I do some sort of ajax login and load changes to the page accordingly. Easy enough. But what about in the second case? Do I go back through and add {% if user.authenticated %} all over the place? This seems cold, dark, and WET. On the other hand, I can just wrap all the ajaxy stuff in a javascript function, called loggedIn(), and run that if the user is authenticated. But then I'm faced with two http requests instead of one. Also undesirable. So what's the standard solution here?

    Read the article

  • DRY Ruby Initialization with Hash Argument

    - by ktex
    I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. What I end up doing is something like the following: class Example PROPERTIES = [:name, :age] PROPERTIES.each { |p| attr_reader p } def initialize(args) PROPERTIES.each do |p| self.instance_variable_set "@#{p}", args[p] if not args[p].nil? end end end Is there no more idiomatic way to achieve this? The throw-away constant and the symbol to string conversion seem particularly egregious.

    Read the article

  • help me "dry" out this .net XML serialization code

    - by Sarah Vessels
    I have a base collection class and a child collection class, each of which are serializable. In a test, I discovered that simply having the child class's ReadXml method call base.ReadXml resulted in an InvalidCastException later on. First, here's the class structure: Base Class // Collection of Row objects [Serializable] [XmlRoot("Rows")] public class Rows : IList<Row>, ICollection<Row>, IEnumerable<Row>, IEquatable<Rows>, IXmlSerializable { public Collection<Row> Collection { get; protected set; } public void ReadXml(XmlReader reader) { reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new Row(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } } Derived Class // Acts as a collection of SpecificRow objects, which inherit from Row. Uses the same // Collection<Row> that Rows defines which is fine since SpecificRow : Row. [Serializable] [XmlRoot("MySpecificRowList")] public class SpecificRows : Rows, IXmlSerializable { public new void ReadXml(XmlReader reader) { // Trying to just do base.ReadXml(reader) causes a cast exception later reader.ReadToFollowing(XmlNodeName); do { using (XmlReader rowReader = reader.ReadSubtree()) { var row = new SpecificRow(); row.ReadXml(rowReader); Collection.Add(row); } } while (reader.ReadToNextSibling(XmlNodeName)); } public new Row this[int index] { // The cast in this getter is what causes InvalidCastException if I try // to call base.ReadXml from this class's ReadXml get { return (Row)Collection[index]; } set { Collection[index] = value; } } } And here's the code that causes a runtime InvalidCastException if I do not use the version of ReadXml shown in SpecificRows above (i.e., I get the exception if I just call base.ReadXml from within SpecificRows.ReadXml): TextReader reader = new StringReader(serializedResultStr); SpecificRows deserializedResults = (SpecificRows)xs.Deserialize(reader); SpecificRow = deserializedResults[0]; // this throws InvalidCastException So, the code above all compiles and runs exception-free, but it bugs me that Rows.ReadXml and SpecificRows.ReadXml are essentially the same code. The value of XmlNodeName and the new Row()/new SpecificRow() are the differences. How would you suggest I extract out all the common functionality of both versions of ReadXml? Would it be silly to create some generic class just for one method? Sorry for the lengthy code samples, I just wanted to provide the reason I can't simply call base.ReadXml from within SpecificRows.

    Read the article

  • How to stay DRY when using both Javascript and ERB templates (Rails)

    - by user94154
    I'm building a Rails app that uses Pusher to use web sockets to push updates to directly to the client. In javascript: channel.bind('tweet-create', function(tweet){ //when a tweet is created, execute the following code: $('#timeline').append("<div class='tweet'><div class='tweeter'>"+tweet.username+"</div>"+tweet.status+"</div>"); }); This is nasty mixing of code and presentation. So the natural solution would be to use a javascript template. Perhaps eco or mustache: //store this somewhere convenient, perhaps in the view folder: tweet_view = "<div class='tweet'><div class='tweeter'>{{tweet.username}}</div>{{tweet.status}}</div>" channel.bind('tweet-create', function(tweet){ //when a tweet is created, execute the following code: $('#timeline').append(Mustache.to_html(tweet_view, tweet)); //much cleaner }); This is good and all, except, I'm repeating myself. The mustache template is 99% identical to the ERB templates I already have written to render HTML from the server. The intended output/purpose of the mustache and ERB templates are 100% the same: to turn a tweet object into tweet html. What is the best way to eliminate this repetition? UPDATE: Even though I answered my own question, I really want to see other ideas/solutions from other people--hence the bounty!

    Read the article

  • PHP: MVC and DRY

    - by Pirkka
    Hello! Question about controllers. Can controller call it`s own class methods inside an action? EDIT: Oh sorry. I meant I dont want to repeat myself. :)

    Read the article

  • DRY and SRP

    - by Timothy Klenke
    Originally posted on: http://geekswithblogs.net/TimothyK/archive/2014/06/11/dry-and-srp.aspxKent Beck’s XP Simplicity Rules (aka Four Rules of Simple Design) are a prioritized list of rules that when applied to your code generally yield a great design.  As you’ll see from the above link the list has slightly evolved over time.  I find today they are usually listed as: All Tests Pass Don’t Repeat Yourself (DRY) Express Intent Minimalistic These are prioritized.  If your code doesn’t work (rule 1) then everything else is forfeit.  Go back to rule one and get the code working before worrying about anything else. Over the years the community have debated whether the priority of rules 2 and 3 should be reversed.  Some say a little duplication in the code is OK as long as it helps express intent.  I’ve debated it myself.  This recent post got me thinking about this again, hence this post.   I don’t think it is fair to compare “Expressing Intent” against “DRY”.  This is a comparison of apples to oranges.  “Expressing Intent” is a principal of code quality.  “Repeating Yourself” is a code smell.  A code smell is merely an indicator that there might be something wrong with the code.  It takes further investigation to determine if a violation of an underlying principal of code quality has actually occurred. For example “using nouns for method names”, “using verbs for property names”, or “using Booleans for parameters” are all code smells that indicate that code probably isn’t doing a good job at expressing intent.  They are usually very good indicators.  But what principle is the code smell of Duplication pointing to and how good of an indicator is it? Duplication in the code base is bad for a couple reasons.  If you need to make a change and that needs to be made in a number of locations it is difficult to know if you have caught all of them.  This can lead to bugs if/when one of those locations is overlooked.  By refactoring the code to remove all duplication there will be left with only one place to change, thereby eliminating this problem. With most projects the code becomes the single source of truth for a project.  If a production code base is inconsistent with a five year old requirements or design document the production code that people are currently living with is usually declared as the current reality (or truth).  Requirement or design documents at this age in a project life cycle are usually of little value. Although comparing production code to external documentation is usually straight forward, duplication within the code base muddles this declaration of truth.  When code is duplicated small discrepancies will creep in between the two copies over time.  The question then becomes which copy is correct?  As different factions debate how the software should work, trust in the software and the team behind it erodes. The code smell of Duplication points to a violation of the “Single Source of Truth” principle.  Let me define that as: A stakeholder’s requirement for a software change should never cause more than one class to change. Violation of the Single Source of Truth principle will always result in duplication in the code.  However, the inverse is not always true.  Duplication in the code does not necessarily indicate that there is a violation of the Single Source of Truth principle. To illustrate this, let’s look at a retail system where the system will (1) send a transaction to a bank and (2) print a receipt for the customer.  Although these are two separate features of the system, they are closely related.  The reason for printing the receipt is usually to provide an audit trail back to the bank transaction.  Both features use the same data:  amount charged, account number, transaction date, customer name, retail store name, and etcetera.  Because both features use much of the same data, there is likely to be a lot of duplication between them.  This duplication can be removed by making both features use the same data access layer. Then start coming the divergent requirements.  The receipt stakeholder wants a change so that the account number has the last few digits masked out to protect the customer’s privacy.  That can be solve with a small IF statement whilst still eliminating all duplication in the system.  Then the bank wants to take a picture of the customer as well as capture their signature and/or PIN number for enhanced security.  Then the receipt owner wants to pull data from a completely different system to report the customer’s loyalty program point total. After a while you realize that the two stakeholders have somewhat similar, but ultimately different responsibilities.  They have their own reasons for pulling the data access layer in different directions.  Then it dawns on you, the Single Responsibility Principle: There should never be more than one reason for a class to change. In this example we have two stakeholders giving two separate reasons for the data access class to change.  It is clear violation of the Single Responsibility Principle.  That’s a problem because it can often lead the project owner pitting the two stakeholders against each other in a vein attempt to get them to work out a mutual single source of truth.  But that doesn’t exist.  There are two completely valid truths that the developers need to support.  How is this to be supported and honour the Single Responsibility Principle?  The solution is to duplicate the data access layer and let each stakeholder control their own copy. The Single Source of Truth and Single Responsibility Principles are very closely related.  SST tells you when to remove duplication; SRP tells you when to introduce it.  They may seem to be fighting each other, but really they are not.  The key is to clearly identify the different responsibilities (or sources of truth) over a system.  Sometimes there is a single person with that responsibility, other times there are many.  This can be especially difficult if the same person has dual responsibilities.  They might not even realize they are wearing multiple hats. In my opinion Single Source of Truth should be listed as the second rule of simple design with Express Intent at number three.  Investigation of the DRY code smell should yield to the proper application SST, without violating SRP.  When necessary leave duplication in the system and let the class names express the different people that are responsible for controlling them.  Knowing all the people with responsibilities over a system is the higher priority because you’ll need to know this before you can express it.  Although it may be a code smell when there is duplication in the code, it does not necessarily mean that the coder has chosen to be expressive over DRY or that the code is bad.

    Read the article

  • Eyes easily get dry and itchy [closed]

    - by Lo Wai Lun
    I have currently working as a programmer for half a year Very often, I often looking the monitors with natural contrast and brightness. Still when the weather is getting cold, my eyes feel dry and itchy. Sometimes I can see some red 'tree-roots' (capillaries) near iris. At home, i sometimes use my notebook for 13" or Galaxy Nexus Brightness are also natural contrast and brightness , a bit dim How should we take care of our eyes under this scenario?

    Read the article

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