FAQ Database Discussion Community


Is it ok to move code that will run only once into a function? [closed]

c#,c++,function,coding-style
Considering that my program has to perform a certain set of actions based on a condition, and this set of actions is described in 20-30 lines of code, should I keep it within the conditional (an if block, part of the Main function) or is it best practice to group...

How to clean up my duplicate jquery code?

jquery,html,ajax,coding-style
I am writing on a system where you can ask and answer questions, looks like this: Everything is working fine, but the code looks hideous! Lots of duplicate parts that do pretty much the same thing. This is only for the voteUp-Buttons, the code is pretty much the same for...

Is there a better, more elegant way to do this?

ios,swift,coding-style
Check out this question: Swift probability of random number being selected? The top answer suggests to use a switch statement, which does the job. However, if I have a very large number of cases to consider, the code looks very inelegant; I have a giant switch statement with very similar...

Should you use named functions when developing a JavaScript library?

javascript,debugging,coding-style,introspection,code-readability
For example: module.exports = { myLibraryFunction: function myLibraryFunction() { ... } } The disadvantage is obvious. It's not very DRY, which means it can easily become out-of-sync if you're not careful. It also makes your code a little more verbose. So what are the advantages? Is the tradeoff worth it?...

Javascript Object Sorting and Adding new property in Modular Approach

javascript,coding-style
I have following javascript object mData=[{A: "148.0", Bit: 27 ,Ic: "0.4",ked: "229.0",Ted: "228.9985"}, {A: "148.0", Bit: 27 ,Ic: "0.4",ked: "229.0",Ted: "2285"}, {A: "148.0", Bit: 17 ,Ic: "0.4",ked: "259.0",Ted: "28"}, {A: "148.0", Bit: 27 ,Ic: "0.4",ked: "279.0",Ted: "28"}, {A: "148.0", Bit: 27 ,Ic: "0.4",ked: "239.0",Ted: "82"}, {A: "148.0", Bit: 17 ,Ic:...

How far should one take #ifdef statements for hardware flexibility [closed]

c,coding-style,arduino,embedded
As I understand it, one of the best ways to include different options for different hardware in an embedded systems program is #ifdef statements. Stylistically, how far should this go? I guess specifically, would you shake your head if someone uses an #ifdef on a function deceleration? It feels quite...

phpcs - Set default message type to warning for all snips from a custom ruleset

php,coding-style,phpcodesniffer
I am configuring phpcs to use WordPress coding standards using a custom ruleset. My phpcs.xml looks like this <?xml version="1.0"?> <ruleset name="Bulk Delete"> <description>Bulk Delete coding standard</description> <file>./</file> <!--Docs issues should be shown as warnings --> <rule ref="WordPress-Docs"> <type>warning</type> </rule> </ruleset> WordPress-Docs is a custom ruleset that is defined as...

Choosing effective function names

php,coding-style,naming,code-cleanup
I'm looking for advice on writing a good function name as part of a web page I'm developing. It's coded in PHP and the function basically reassembles array data holding customer attendance information to a music venue (example time, date, entrance, etc) . The function takes in array data and...

Is it ever okay to not use an ELSE statement if you have a return or throw inside the IF statement? [closed]

algorithm,coding-style,logic,control-structure
I often write code such as the following bool myFunct (...) { if (something) { return false; } // .... more code .... } The alternative is bool myFunct (...) { if (something) { return false; } else { // .... more code .... } } Of course, that else...

Struct or class for internationalized name object in .NET?

c#,class,internationalization,coding-style,structure
I've got a Person class and I currently try to add name attributes, either as class or as struct. Background is, thought in global dimensions, not every person's name must consist of given name and family name. So I decided to make it more atomic and create a new general...

Formatting assembly code to break a statement into multiple lines

assembly,coding-style,masm,code-cleanup
I work with ASCII bit matrices in assembly x86 which looks like this example: Sign_plus db 00000000b db 00001000b db 00001000b db 00111110b db 00001000b db 00001000b db 00000000b db 00000000b However, I'd like to keep db [sth] in new line to make the sign more visible and aesthetic ie....

Why use != null in if statements?

c#,if-statement,null,coding-style
I come from a C/C++ background and recently started a new job doing C# work. I find in a lot of code and examples online people use this convention in if statements if(obj != null) I remember being told to avoid using negative logic when possible. So why isn't something...

Create forms dynamically or statically?

javascript,html,coding-style
I have a particular web page which requires around 6 different forms; some of them are up to 15 rows of unique labels and inputs. I made a JavaScript library which can accept a large object and output a form. Basically, it accepts an endless object like: var myForm =...

How to use constant powers of 2 readable in c++?

c++,binary,coding-style,constants,code-readability
I need several integer constants with 2^n and 2^n - 1 in my GNU c++ code. What is a good practise to keep the code readable? The code uses decimal values at the moment 4294967296 and 65536 which is hard to debug in future. 2^12 is not implemented in standard...

lisp: dynamic scope vs explicit parameter passing

design-patterns,coding-style,common-lisp,anti-patterns,dynamic-scope
I see two different patterns for "output" functions in (common) lisp: (defun implicit () (format t "Life? Don't talk to me about life!")) (defun explicit (stream) (format stream "This will all end in tears.")) (defun test-im-vs-ex-plicit () (values (with-output-to-string (stream) (let ((*standard-output* stream)) (implicit))) (with-output-to-string (stream) (explicit stream)))) Is using...

Are variable bound / 1st class functions preferable over private method naming? How is hoisting affected?

javascript,angularjs,function,coding-style,hoisting
A few questions regarding structuring Angular code and the behavior of JavaScript when using variable bound vs private method naming function conventions. Is there a performance or stylistic reason for using variable bound functions / first class functions in AngularJS over private method naming? How is hoisting affected in each...

Idiomatic Scala for Options in place of if/else/else chain

scala,coding-style,optional
I often find myself writing Scala of the form: def foo = { f1() match { case Some(x1) => x1 case _ => f2() match { case Some(x2) => x2 case _ => f3() match { case Some(x3) => x3 case _ => f4() } } } } This is...

Clean coding resulting in many utility classes [closed]

java,coding-style
Warning: this question is about coding style and not functionality so if these types of questions don't interest you then don't read on. My company follows a clean coding convention (as per Robert Martin's book "Clean Code: A Handbook of Agile Software Craftmanship"). However we find that this results in...

Property name same as non anonymous function

javascript,angularjs,coding-style
I'd like to use non anonymous functions for a better debugging purpose and encountered the following question. When I have a function returning an object of methods (like in angularjs factories), is it bad style to name the returned property and the function the same? Like here: angular .module('myModule', [])...

How to avoid repetion with my code

python-3.x,coding-style
I've written a code that extracts all the words from two files, and only returns the words that are in both of the file. However, i have done some repetition and that is not considered a good style, so i wondering if it would be possible to avoid this with...

Is there way to call a table as a variable in Active Record?

ruby-on-rails,coding-style,rails-activerecord
The title is a bit confusing, so let me explain. I have 3 Model classes called Table1, Table2, and Table3. All three tables have the "total" column. This is what I want to be able to do: index = either 0, 1, or 2 tableNames = ["Table1", "Table2", "Table3"] tableNames[index].total...

SQL Repeated Condition in Two Tables

sql,variables,coding-style,condition
I am a beginner to SQL, and I am having trouble getting rid of repeated code. I have a condition "AccountId=20" that I use twice in a SQL query. The SQL looks something like: DELETE FROM Table_A WHERE FunctionId IN (Select FunctionId FROM Table_B WHERE AccountId=20); DELETE FROM Table_B WHERE...

Start programming without using advanced techniques? [on hold]

c#,coding-style
Can you start with coding programs without using advanced techniques, like Delegates or similar? Also is it wise to follow Single responsibility principle (each method has only one reason or purpose) as a beginner. Each method should have small number of code lines (like 10) is also one of coding...

Is it good to pass minimal paramters?

java,design-patterns,coding-style
Assume I have an object Car, with five parameters, { numwheels, color, mileage, horsepower, maxSpeed }. I have a method that needs 3 of these values. Which of the 2 options is said to be best practice ? Is it better to pass enclosing object and reduce the number of...

Why is `for i in a` not idiomatic Ruby? [closed]

ruby,for-loop,coding-style,iterator
Ruby has support for the for i in a syntax, but no one really uses it. One of the design principles of Ruby is it's readability, and I find for i in a ... end much more readable (and easier to type) than a.each do |i| ... end Why is...

When to use _ as a variable in Python?

python,variables,coding-style,naming-conventions
I recently discovered that I could use _ as a variable. Is there a particular protocol of when to use this as a variable name? Should __ ever be used? Example from deeplearning.net with the Theano library, there is a trend to use _ when defining theano.scan() operations... values, _...

Why do all user-defined identifiers start with an uppercase letter?

coding-style,ada
In all Ada source code i know, including the standard library (sorry, i don't know where find it on the web) or the Small game implementation, all non-reserved words starts with uppercase letter. (Last, Stack, Index,…) And because all reserved keywords are highlighted by editor, i guess/hope its not for...

[Clean Code]: Which is better? Variable or return one-line function?

actionscript-3,coding-style
Which is better? One-line returning function optionIsOutOfRange(): public function deleteOption(index:int):void { if (optionIsOutOfRange(index)) { throw new Error("Option index is out of range! Cannot delete!"); } else { options.splice(index, 1); } } private function optionIsOutOfRange(optionIndex:int):Boolean { return optionIndex > numOptions - 1; } or variable here is optionIsOutOfRange: public function deleteOption(index:int):void...

Is it good practice to use magic numbers?

html,sql,language-agnostic,coding-style
I am making a web app. In certain cases in server side I am making mysql queries where I basically say where d.id=2 meaning I hard-code a foreign key to another table. Or in client side, I have a form with a radio field, and the input field values are...

in scala what is cleaner code - to def (~member) versus pass function parameter?

scala,coding-style,code-cleanup
Which is cleaner? def version trait Foo { def db: DB def save() = db.save() def load() = db.load() } versus parametric version: trait Foo { def save(db: DB) = db.save() def load(db: DB) = db.load() } (left out intentionaly other parameters/members I want to focus on this one). I...

Concatenating C# string only when the pre check is an empty string

c#,coding-style,string-concatenation
I am kind of C# novice and I am trying to concatenate a string in C# to display the checked result in a textbox followed by a button click. I was able to get the desired output but the code seems it has not followed the DRY principle in SE....

What exactly is license boilerplate commenting and what format does it need to be in?

c++,coding-style,comments,boilerplate,commenting
I was reading through the Google C++ Style Guide to try to emulate good coding practices. When I read through the section on how to comment my code, it asks me to start each file with license boilerplate. All I could find out about this terminology was from Mozilla and...

The best way to use child classes and methods

c#,class,coding-style
Have some newbie questions. I have 6 classes: public class MainSettingsClass { int a; int b; } public class SubSettingsClass_1 : MainSettingsClass { int c; } public class SubSettingsClass_2 : MainSettingsClass { int d; } public class ParentClass { public MainSettingsClass settings; } public class ChildClass_1 : ParentClass { }...

Python one exception multiple handlers

python,exception,coding-style,programming-paradigms
I want to do this: try: raise A() except A: print 'A' except (A, B): print 'A,B' Which I hoped would print both A and A,B. That doesn't work (only the first except is executed). It makes sense for the first except to swallow the error, in case you want...

Best practices for creating a huge SQL table

mysql,database,database-design,coding-style,large-data
I want to create a table about "users" for each of the 50 states. Each state has about 2GB worth of data. Which option sounds better? Create one table called "users" that will be 100GB large OR Create 50 separate tables called "users_{state}", each which will be 2GB large I'm...

Scala: elegant way to use require to validate multiple options?

scala,functional-programming,coding-style,pattern-matching,require
I have two solutions for this problem. I do not like both of them so I was wondering if there's a more elegant solution. import java.util.Date import scala.math.Ordered.orderingToOrdered // Solution # 1: case class A(startDate: Option[Date] = None, endDate: Option[Date] = None) { require(if (startDate.isEmpty && endDate.isEmpty) false else true,...

CSS Table Styles - Trying to give more space

html,css,coding-style
Good Day Everyone, I'm writing a Wordpress Plugin with CSS and jQuery and PHP. I have the below table, I'm trying to modify the CSS but it doesn't seem to apply properly. My table basically looks like: |--------------------------------------------| | Username: | |--------------------------------------------| | | |--------------------------------------------| |Email | |--------------------------------------------| ||------------------------------------------|| ||Year...

How to check if a number is in a interval

python,coding-style,range,intervals
Suppose I got: first_var = 1 second_var = 5 interval = 2 I want an interval from second_var like second_var ± interval (from 3 to 7). I wank to check if first_var is in that interval. So in this specific case I want False If first_var = 4, I want...

Enforcing coding styles in Visual Studio and VIM

c++,visual-studio-2010,visual-studio,vim,coding-style
I work with a medium sized team of developers, with half being Linux developers using VIM on Ubuntu and MacVIM on OSX, and the other half being Windows developers using Visual Studio 2010 or later. A fair bit of time has been wasted in the past when handling things like...

How to use java.time.ZonedDateTime to generate a primitive long value in UTC

java,performance,coding-style,utc,data-type-conversion
What is a fairly efficient but most importantly a clean and concise way of generating a UTC timestamp as a long value (java primitive type). I only need this to be accurate to the most precise millisecond value. I would prefer to use java.time.ZonedDateTime as it is a clean way...

Laravel 5 - Clean code, where to keep business logic (controller example)

php,laravel,model-view-controller,coding-style,laravel-5
Below example of 'store' method of my controller Admin/MoviesController. It already seems quite big, and 'update' method will be even bigger. The algoritm is: Validate request data in CreateMovieRequest and create new movie with all fillable fields. Upload poster Fill and save all important, but not required fields (Meta title,...

I've inherited a PHP project that has a very consistent file naming pattern that I don't understand

php,coding-style
Most of the files in the project are essentially pairs of files named: xxxx xxxx.php inside the xxxx file is a single php statement requiring the same file name but w/ the php extension, e.g. <?php require('xxxx.php'); ?> What is the rational / programming practice / style / ... for...

how to convert code into recursion?

java,recursion,coding-style,drawrectangle,spiral
import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JFrame; public class DrawIt { public static void main(String[] args) { JFrame frame = new JFrame(); final int width = 400; final int height = 400; frame.setSize(width,height); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent component = new JComponent() { public void paintComponent(Graphics graph){ draw(graph); } }; frame.add(component); frame.setVisible(true); } public...

What is the use of PyCharm's docstring template? How do I use it effectively?

python,coding-style,documentation,pycharm,docstring
PyCharm, the Python IDE generate a template for docstring as I start to type in the docstring. This is the template generated for a simple function. def add_them(x, y): """ :param x: :param y: :return: """ z = x + y return z I dont find it anything similar to...

Can this Python code be further shrunk?

python,coding-style
Below is Python code that fetches all of the sub-domains within a domain. It takes a file as input that contains the page source for a website. The second argument is the domain name. For example: "https://www.sometime.com". import re def getSubDomains(fil,domain): with open(fil) as f: subDomainLst = [] for line...

Ruby how to iterate a collection and create a hash key if none exists, or add to the value if key does exist

ruby-on-rails,ruby,coding-style
This is a pattern that I find myself using a lot and I am wondering if there is something in the built-in library that does this without adding all these control flow statements. what I have is: input = <<TEXT /us/programming/sports:model.channel.tnt.name /us/programming/sports:model.channel.spice.name /us/programming/sports:model.classificationwebgenre.us-entertainment.programming_link_text /international-sports/package:model.language.international-sports.name /brazilian/programming/sports:model.package.hbo-extra.description TEXT def...

StyleCop and/or a general style guide?

c#,coding-style,stylecop
Similar questions: Styleguide for C# and StyleCop: a complete document Ok, so I'm looking into some sort of style control at my workplace for the applications we develop in C#. I was initially just planning on producing a style guide (by collecting a number of existing style guides and picking...

Can this code look cleaner in C#?

c#,casting,coding-style
I have a C programming background and I am used to doing ugly things. Is there a more elegant/readable way to do this scaling operation in C#: ImageProcessing.Resize(original, 80, (int)((float)original.Height * (80f / original.Width))); Where "original" is the .Net Image class and Image.Width and Image.Height are thus integers....

Coding practice for blocks in python [closed]

python,coding-style
Is it a bad practice to write num1=10 num2=10 if num2!=0: print(num1/num2) else: print("Cannot divide by zero") instead of num1=10 num2=10 if(num2!=0): print(num1/num2) else: print("Cannot divide by zero") I personally prefer the former one. Any references for your view?...

Where are line breaks allowed within Haskell expressions?

haskell,coding-style
Background Most style guides recommend keeping line lengths to 79 characters or less. In Haskell, indentation rules mean that expressions frequently need to be broken up with new lines. Questions: Within expressions, where is it legal to place a new line? Is this documented somewhere? Extended question: I see GHC...

Refactoring for loop with each iteration setting a different property

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

Proper style of coding __init__.py in Python modules

python,coding-style,pylint,spyder
I'm not that fluent in Python so I'm not sure if what I'm doing is common practice or the proper way to do it. I'm creating a module archive contaning files with one class each, e.g. SmsArchiveReader.py with class SmsArchiveReader inside. To make the imports less tedious, I decided to...

Naming conflict between field values and local scope in Haskell

haskell,coding-style,naming-conventions
This is a coding style question rather then a technical one. I have frequently encountered a problem where I use haskell's (less then optimal) record syntax (or lenses, the problem ends up the same) to create a data type. I end up with field accessor functions named after my fields....

Node.js and Q Promises: How can I hand over parameters in a cleaner way?

javascript,node.js,coding-style,promise,q
I have some code like this: function example(data){ asyncFnOne() .all([asyncFnTwo(), data]) .spread(asyncFnThree) .done(); }; It doesn't matter what those functions do. The problem I have is that I don't know how asyncFnThree can access both data from asyncFnTwo and from the function parameters. The way I solved the problem is...

“One-time use methods” - looks better, but harder to read?

java,coding-style
I've got a constructor that has a LOT of setup to do, for a pretty complex object. Lots of this setup includes adding listeners to other objects within this one, so my constructor is full of the boilerplate anonymous inner class method descriptions. And since you NEED to implement them...

Custom function to map two arrays of which one is subset to check if those exist

php,arrays,json,performance,coding-style
Note: To the downvoter and to those who need further clarification... I am trying to get to a solution, to not walk through the loop. i.e., I don't wanna use foreach function. Sorry about the crazy title. What I am trying to achieve is, I have two arrays, say:...

which one is better to wrap AFNetworking functions in one file or use it in separate files,

ios,coding-style,afnetworking
I'm using AFNetworking as network library. There are two different coding styles and I don't know which one is better. Wrap all functions that associated to network to one file. For example, I have a singleton file called API.m, and I wrapped login function as below: - (void) login:(NSString *)username...

Variable Declaration Inside For Loop Initialization Statement

objective-c,for-loop,coding-style,variable-declaration
I have a simple question with regards to initializing for loops. Here is my for loop declaration: for (int i=player.x-xIndex-1; i<=player.x+xIndex+1; i++) { for (int j=player.y-yIndex-1; j<=player.y+yIndex+1; j++) { } } My question is: Is it bad practice to have the values of the indices i and j be set...

How to force team members to comment using eclipse plugin or something else

eclipse,jenkins,eclipse-plugin,coding-style,build-automation
Currently, I am working in a new project and it was difficult for me to understand since there is no comment. I wonder if it is possible to force team members(including me) to add more comments. I would like to automate this ject in jenkins later if possible.

Handling unused return statements

java,c#,coding-style
I have the following code : public static QHttpResponse SafeExecute(QHttpRequest request, int retries, int sleep) { if (retries < 1) throw new Exception("retries must be at least 1"); for (int index = 0; index < retries; index++) { try { return QWebClient.Execute(request); } catch (Exception) { if (index == retries...

Java “get{Object}” method naming convention [closed]

java,android,coding-style,naming-conventions
Which of the following is compliant with Java guidelines? Observable<List<Account>> getAccounts(String userId); Observable<List<Account>> getAccountsForUser(String userId); I don't want to start a debate, I'm looking for a document that is stating the guidelines. I don't think it matters, but I'm using the previous snippet of code inside an Android project....

VIM - Reformatting indentation and braces

vim,coding-style,vim-plugin
When working with blocks of code in VIM, I'm able to easily re-indent blocks of code via selecting a region in visual mode (SHIFT+v), then just hit =. This re-tabs lines of code, uses the correct indentation depths, hard-tabs vs spaces, etc. I have a large set of functions I...

Opinion: SqlCommand style: bind int vs. put it in the string

sql,sql-server,vb.net,coding-style
Suppose that I have, for example: Dim _id As Integer = 7 And I'm going to use it to select a row from a table where foo_id is the primary key. Either I can bind the Integer value with AddWithValue such as: Dim cmd As New SqlCommand("select * from foo...

HP Fortify SQL injection issue on preparedStatement in java

java,jdbc,coding-style,fortify
I am using HP Fortify to measure code quality of my java code. HP Fortify is reporting SQL Injection error on PreparedStatement stmt = connnection.prepareStatement(queryString); so how to resolve this?...

Use param name when calling function with all default parameters in C++

c++,function,coding-style
In C++, if I have a function with all default parameters: void foo(int a = 9, int b = 3); Can I call it with param names? Like: foo(b = 5); When I search online, seems one can not bypass the first param and specify the value of the second...

String concatenation concat() and + operator usage effectively

java,coding-style,string-concatenation
I am aware of String concatenation: concat() vs + operator But i have question on usage of both concat() and + operator effectively concat() is more efficient than + operator but still we are using + operator in few cases below Case 1 System.out.println("Hi! Welcome: "+nameString); Case 2: splitting huge...

Best Practice for Checking Dependent Variables Before or inside Method

java,methods,coding-style,call
I was wondering what the best practices would be for when you have a variable that needs to be checked before a certain helper method could run. Should the check be done in the caller or callee? I see benefits to both. A bit less expensive to do it in...

Doxygen parse const member function incorrectly when const at another line

c++,coding-style,doxygen
I've tried searching stackoverflow and users mailing list in the official website but not found something useful to my problem, there are a lot of results unrelated... Doxygen I used is version 1.8.5. I prefer to style my member function declaration like this, let's call it const-at-another-line style. ReturnType FunctionName()...

Why do Kernighan and Ritchie include seemingly unnecessary typecasts?

c,casting,coding-style,kernighan-and-ritchie
Second edition. I'm looking at their hash table example in section 6.6. I found the full source transcribed here. This is the part I'm puzzling over: struct nlist *np; if((np=lookup(name))==NULL){ np=(struct nlist *)malloc(sizeof(*np)); Why the cast to (struct nlist *) on the last line? I can remove it without getting...

Can I print list data in a more elegant way?

python,list,printing,coding-style
Is there a cleaner way to structure my print function? lloyd = { "name": "Lloyd", "homework": [90.0, 97.0, 75.0, 92.0], "quizzes": [88.0, 40.0, 94.0], "tests": [75.0, 90.0] } alice = { "name": "Alice", "homework": [100.0, 92.0, 98.0, 100.0], "quizzes": [82.0, 83.0, 91.0], "tests": [89.0, 97.0] } tyler = { "name":...

Common Lisp object setter function style

coding-style,common-lisp
I am attempting to write a function that takes a list of user-defined objects called nodes to generate connections between them. Each node object has a slot for its unique number ('num') and a slot for a list of numbers that act as the edges between nodes ('edges'). +max-edges+ is...

Advise on simplifying a PHP statement

php,joomla,coding-style
I am new to PHP and am coding a template file for a Joomla K2 item layout. I have an 'extra field' $extrafields[15] configured which outputs as "Yes", "No" or "". $extrafields[16] is a text string. I have this code, which works but would appriciate advice on how to simplify...

Using .size() vs const variable for loops

c++,vector,coding-style,const
I have a vector: vector<Body*> Bodies; And it contains pointers to Body objects that I have defined. I also have a unsigned int const that contains the number of bodyobjects I wish to have in bodies. unsigned int const NumParticles = 1000; I have populated Bodieswith NumParticles amount of Body...

Python naming convention: indicating if function alters arguments

python,coding-style,naming-conventions,pep8
I was wondering if there is a proper Python convention to distinguish between functions that either alter their arguments in place or functions that leave their arguments in tact and return an altered copy. For example, consider two functions that apply some permutation. Function f takes a list as an...

Understanding the program that reads a set of text lines and prints the longest in K&R's book

c,coding-style,code-quality
I'm reading K&R's book, section 1.9. The program for printing the longest line, from a given set of lines, is given as #include <stdio.h> #define MAXLINE 1000 /* maximum input line length */ int getline(char line[], int maxline); void copy(char to[], char from[]); /* print the longest input line */...

php - define a long array

arrays,coding-style
I have a country list array which are very long. Netbeans suggests a function should not longer than 20 lines. So I want to ask if I can write this function in a short and beatiful way. Thanks! class CountryList { private static function getCountryArray() { return array( "AF" =>...

Visual Studio - Code Formatting (curly braces)

visual-studio,coding-style,indentation
I am in trouble with the Visual Studio 2013 code formatting. In particoular I have the following problem: when I cut and paste some C++/C# code it is re-formatted as follow: int main() { ... } While I would prefer the following indentation (please note the position of the opening...

Pythonic Variable Assignment

python,coding-style
At the moment I have a large section of code that looks like this: daily_stats.Turnover = int(row[2]) daily_stats.Cars = int(row[0]) daily_stats.Cash = int(row[29]) daily_stats.Card = int(row[33]) daily_stats.Other = int(row[31]) + int(row[35]) + int(row[37]) daily_stats.Exit = int(row[43]) daily_stats.Manual = int(row[42]) daily_stats.Open = int(row[47]) This continues for about 30 lines and, while...

Is it ok for a base class to contain a reference to one of its subclasses?

c#,coding-style
I wrote the following classes to create a tree-hiearchy, but since all node classes contain a parent node of type ParentNode, I would like to move that into the base class so I don't have to rewrite any code relating to the parent for all the node types. So, while...

Swift: Coding rule of optional. Which is swift's style returning nil or []

ios,swift,coding-style
I have some find methods in model classes. Which is better between returning nil or [](empty array) when data is empty. Please take a look below. I think (2) is better because I do not need nil check. (1) nil func findAll() -> [Sample]? { return nil } if let...

Encapsulation with React child components

coding-style,reactjs,encapsulation
How should one access state (just state, not the React State) of child components in React? I've built a small React UI. In it, at one point, I have a Component displaying a list of selected options and a button to allow them to be edited. Clicking the button opens...

angularjs performance best practices

javascript,angularjs,coding-style
I take a style based on johnpapa style guide, and according to Miško presentation on Angularjs MTV meetup Best Practices at 49:44 he say that performance depend on 2 thing : How many binding you have. How expensive you getter. (should fast) And i think that means simple and fast....

Is it “bad practice” to use tab characters in string literals?

c++,c,coding-style,string-literals
As a follow-up on Is it mandatory to escape tabulator characters in C and C++? (do note I'm not the author of said question). I've learned such code is considered "bad practice". The comments seem to be suggesting the same thing. However, for some reason the standard allows this trickery...

How do I partially fold a Vec in place?

coding-style,rust
I would like to walk through a Vec and combine some elements of it. How do I do that in idiomatic Rust? Example: #[derive(PartialEq, Debug)] enum Thing { A, B, AandB } fn combine(v: Vec<Thing>) -> Vec<Thing> { // idiomatic code here } fn main() { let v = vec![Thing::A,...

Are many returns in method bad code? [duplicate]

java,coding-style
This question already has an answer here: Should a function have only one return statement? 50 answers I am trying to optimize and write the best code possible (as any developer is) and I have been racking my head trying to figure out if this particular method I am...

PHP suppress errors when checking existence + value of boolean?

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

java inheritance within one class, deploy variables to two functions

java,inheritance,coding-style
How can I make the variables I define at the top of this class apply to both of the functions within? specifically dict and url. Right now eclipse is telling me, with regards to dict.open() that an "identifier is expected after it", but I think this is a red herring...