Questions tagged [coding-style]
Coding style is a set of guidelines that helps readability and understanding of the source code.
1,064 questions
1
vote
1
answer
127
views
Making type conversions better readable
If you create a function, which should make the use of typeconversions more easy, but it maybe leads to more errors, would implement it globally, and what may speaks against it - when the readability ...
2
votes
2
answers
552
views
Should I use Array or Set if both can be used to finish my task?
for example, Suppose I have a 2d array:
let filterArr=[
[1,1,0,1,1],
[0,1,1,1,0],
[1,1,0,1,0]
];
I want to find and store the index of column that all are 1, i.e.:position 1 and 3, and the ...
3
votes
0
answers
94
views
What're the necessary considerations when developing Cron Jobs (Scheduled Tasks)
I'm working on a website that has a section that shows the company's stock details and investor-related data. This data is retrieved through scheduled SOAP API calls.
I created two scheduled tasks ...
0
votes
1
answer
169
views
For arrays, should I use the first position to store the selected element, instead of variable like "selectedIndex", if possible?
For example, I have a toggle button, which would show the current selected element, and would show next element when it is clicked, and it can loop back to first element. I have 2 ways to store the ...
3
votes
1
answer
266
views
How hard should I try to write idiomatic code in a polyglot environment?
I work on a small team (2 primaries with one or two other occasional contributors) on a project/product that spans a number of separate platforms. We do embedded firmware in straight C on Arm0 chips. ...
2
votes
2
answers
202
views
Should special case be inside or outside the for loop here?
For example, suppose I have 2 arrays:
let arr1=[5,2,1];
let arr2=["abcde","ab","a"];
my work is simple : to check if length of strings in arr2 are larger than corresponding element with same index in ...
3
votes
6
answers
889
views
Is it better to write an efficient algorithm or code that is easier to understand?
So I was recently given a coding assignment from a large financial firm, and I thought of two ways to solve the problem. One of the ways involved 1 outer for loop and 1 inner for loop. In this case, ...
14
votes
6
answers
4k
views
Clean Code - Should I change the literal 1 to a constant?
To avoid magic numbers, we often hear that we should give a literal a meaningful name. Such as:
//THIS CODE COMES FROM THE CLEAN CODE BOOK
for (int j = 0; j < 34; j++) {
s += (t[j] * 4) / 5;
}
...
0
votes
3
answers
478
views
PHP How can I get rid of redundant if statements
I have a bunch of if statements written in PHP for a project I'm working on. The pattern is that when the $price increases by 5 cents every time magazines are increased by 10. When the amount of ...
0
votes
2
answers
158
views
Nomenclature for object inspection functionality
I'm adding mod support for a game I'm working on. I parse a data file that looks something like this:
"requirements":
{
"is_class": { "class": "warrior" },
"is_in_faction": { "faction": "...
3
votes
2
answers
141
views
Should I move tasks which is just for a specific element only out of for loop?
For example, I have a for loop, which element 0 has additional function to run compared with other elements, my question is, should the additional function be:
1.place inside for loop
for(int i=0;i&...
17
votes
6
answers
9k
views
Foreach-loop with break/return vs. while-loop with explicit invariant and post-condition
This is the most popular way (it seems to me) of checking if a value is in an array:
for (int x : array)
{
if (x == value)
return true;
}
return false;
However, in a book I’ve read ...
4
votes
2
answers
429
views
Why do I need a game loop with states, instead of init the next state in current state directly?
For example, it is common to see games with game loop and states:
stateChanged(){
switch(state){
STATE.PLAYER_SELECT_CHARACTER:
this.currentController=new PlayerSelectCharacterController()...
1
vote
2
answers
284
views
If a instance method is used in one place only, should I move that method to that place?
For example, suppose I have a ZipCode class:
public class ZipCode{
public value String value;
public boolean validateFormat(){
...
}
public otherMethod1(){
...
}...
4
votes
3
answers
3k
views
Is 2 methods calling each other code smell?
For example, if 2 classes depend on each other, it is a kind of circular dependency and should be avoided. How about methods? for example, if I have 2 methods which call each other:
public void ...
3
votes
1
answer
121
views
Should I replace a constant with static methods, if that constant usually 'cooperate' with a specific operator?
For example, to convert between g and kg, I have a constant 1000:
public static final float G_TO_KG=1000;
.
.
.
this.result = someResult*1000;
I found G_TO_KG always bind to operator '*'. So my ...
5
votes
3
answers
9k
views
Is it necessary for a boolean to be "false" by default?
For example, to store whether sound is on, I have a boolean originally named "isSoundOn":
private boolean isSoundOn=true;
however, the default value of boolean is false, but I want my application to ...
1
vote
2
answers
130
views
When define locale text file, language key (eg:'en') or text key (eg:'WELCOME_MESSAGE'), which one should be the outermost key?
When define a locale text map, I can use:
1.locale key first
{
"en":{
"WELCOME_TO_USE_THIS_APP":"Welcome to use this app,...",
"SOME_OTHER_TEXT":"fsdfsf..."
},
"es":{
"...
0
votes
2
answers
260
views
Would it be OK if I mention actor in the command/query name when I use CQS pattern
I'm applying Clean Architecture + DDD (maybe) in my project (web Application + REST API).
The good thing I learned from the Clean Architecture is using "Interactors" to show business use cases in my ...
1
vote
3
answers
353
views
Easy to maintain ways that helps code readability in C#?
Say we start with a base class that states if an object is valid or not (included one interface and two child classes for discussion purpose), like:
interface IValid
{
bool IsValid();
}
public ...
0
votes
2
answers
758
views
Why do Python developers pass special strings to functions instead of defined symbols? [closed]
Is there a reason why Python developers (both maintainers of Python itself and authors of modules) tend to pass special strings as arguments to functions instead of defining symbols for the same ...
2
votes
1
answer
196
views
Is it considered bad form to call `next` on the input sequence of a list comprehension?
I want to extract lines from a stream that are preceded by the character L. The list comprehension below does the job, but calls next on the stream inside the comprehension in a way I've never seen ...
2
votes
1
answer
497
views
Is 'Keep it looks similar to sample code' a valid reason to prefer WET over DRY principle?
For example, for oauth, I may need to copy and paste oauth and oauth callback code like it (assume Client is the framework I use, I don't use real framework like google because I want to simplify the ...
17
votes
4
answers
17k
views
C++ Preferred method of dealing with implementation for large templates
Typically when declaring a C++ class, it is best practice to put only the declaration in the header file and put the implementation in a source file. However, it seems that this design model does not ...
174
votes
24
answers
27k
views
Programming cleanly when writing scientific code
I don't really write large projects. I'm not maintaining a huge database or dealing with millions of lines of code.
My code is primarily "scripting" type stuff - things to test mathematical ...
1
vote
2
answers
409
views
Using C coding conventions in C++ code [duplicate]
I'm working on a large codebase whose core modules are in C and extension modules are in C++. We have a coding convention for C code but I'm being told that we need to enforce the same coding ...
6
votes
3
answers
2k
views
In languages without exception-handling, should error codes be returned from the function or in function parameters?
I'm writing a CSV parsing library in C and am considering whether to express error codes as return values or as parameters passed by reference.
For example, here are the signatures for the function ...
-3
votes
1
answer
74
views
How to make a configurable design in restaurant delivery problem? [closed]
The problem is like there are few restaurants and few delivery guys available. Each restaurant has a meal order and the delivery guys are to be assigned to the restaurant.
Now there may be many ...
-2
votes
1
answer
2k
views
How to clean a refactor Java for-if-try-catch-else kind of messy code [duplicate]
Often I came across situations like this, how to write this code in a neat and clean way.
One more issue I find here is performance as I am iteration a list and then it's properties.
Edit : - while ...
6
votes
1
answer
875
views
Is method with "ByXXX" suffix (eg:findUserById) redundant?
Sometimes I can see method definition like:
public User findUserById(int id){
}
But my justification is, isn't "(int id)" already include the information of "ById"?
is it better to have naming just ...
1
vote
2
answers
4k
views
Using the same name for setter and gettter methods for a boolean member variable
Say I have class with a boolean member variable fancy:
public class MyClass {
private boolean fancy;
}
Case 1. I could the define the setter and getter as follows:
// getter
public boolean ...
2
votes
6
answers
2k
views
Should I still prefer composition over inheritance if the child classes need BOTH the parent interface AND its class properties?
According to Why should I prefer composition over inheritance?, I should prefer composition over inheritance. But what if I need to access the interface and class member in generic way? For example, I ...
14
votes
3
answers
19k
views
readonly vs. private getter-only property in C# 6
C# 6 added auto-property initializers and so we can do
private List<LinearLayout> layouts1 { get; } = new List<LinearLayout>();
Is this better or worse than
private readonly List<...
3
votes
4
answers
1k
views
Is "Let more people able to review" a valid reason to "write c++ as if Java" at some degree?
According to Should we avoid language features that C++ has but Java doesn't?, I know it is horrible to write C++ as if Java, mostly because it drops the beneficial features of C++ languages.
But ...
-2
votes
1
answer
315
views
Is there a name for negating a condition in an if-else block?
I recently reviewed code that read as follows:
if (!condition) {
do_something();
} else {
do_something_else();
}
In other words, in the if statement we checked that a condition was false, and ran ...
2
votes
3
answers
559
views
Is it good practice to eliminate zero in a statement if possible (e.g.:rewrite a-b>0 into a>b)?
Sometimes, I would write if-statements with conditions like it:
if(a-b>0){
}
but in fact, I can move 'b' from left hand side to right hand side:
if(a>b){
}
Similar cases like 'a-b!=0','a-b<=...
0
votes
1
answer
1k
views
Representing Java Object Hierarchy With Nested Classes
I was working with some API which was used internally, and while looking at their code I found something like this:
public class Parent {
@Data
public static class Child {
private ...
1
vote
2
answers
202
views
HTML and JS code structure
I am relatively new to HTML/JS and am very much an amateur programmer. I have created a web app that works but I can't help but feel that the code is a spaghetti mess! I have been looking for JS/HTML ...
-1
votes
1
answer
195
views
For use once only functions extracted from a longer function, should the name be xxx1(),xxx2,... or relate to its task?
According to Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else?, I should split long functions into smaller functions even if they ...
18
votes
5
answers
10k
views
Is modifying an object passed by reference a bad practice?
In the past, I've typically done most of my manipulation of an object within the primary method it's being created/updated, but I've found myself taking a different approach lately, and I'm curious if ...
6
votes
4
answers
10k
views
Refactoring many else if, else if, else if, etc. statements
I'm trying to parse readable data from PDFs and I keep ending up writing code like the following:
if (IsDob(line))
{
dob = ParseDob(line);
}
else if (IsGender(line))
{
gender = ParseGender(...
2
votes
2
answers
734
views
(Style) "Good" way of dealing with flags/options
So I've seen many different methods used for this in different librarys, and I want to get a sense of which one may be preferred (or perhaps it's strictly personal preference/case by case). Just as an ...
11
votes
4
answers
867
views
Good code style to introduce data checks everywhere?
I have a project that is sufficiently large in size that I can't keep every aspect in my head any more. I'm dealing with a number of classes and functions in it, and I'm passing data around.
With ...
-2
votes
1
answer
1k
views
What to name my config classes
What name should I give classes which are just for configuration? For example, when using JAX-RS, every application is required to have an Application class which extends the superclass javax.ws.rs....
0
votes
1
answer
92
views
Should I load appropriate locale text at start, or get the locale text according to locale preference each time?
For example, suppose my app have some localization texts. My question is, should I load appropriate locale at start:
var locale=userPrefs.getLocale();
localeStringMap=getLocaleTextFromFile("...
-5
votes
1
answer
703
views
Display or Sketch a graphical representation of a large code
At my new work I am dealing with a quite big C/C++ project (50k lines in multiple files). I usually "draw" what the code is doing to understand its functioning but this time I am struggling a bit ...
1
vote
1
answer
809
views
Is there a coding style for Blade templates?
Since when I used smarty I always tried to separate logic statements from html tags, so my approach to blade would be to write:
template.blade.php
<div>
<div>
@if ($something == true)...
4
votes
1
answer
310
views
What is the best way to manage a class with lots of properties?
We have one table meta where there is key and value so each of the row represents one component or service and then we have api system which manages the metas database. And it was going pretty well ...
4
votes
5
answers
1k
views
Is it a bad practice to use conditionals with functions that change program's state?
The title might be a bit vague, so let me explain. Let's assume we have a function that does something (changes state of the program), for example a function that creates a file. That function returns ...
4
votes
2
answers
652
views
Is using spacing effectively equivalent to the long method code smell?
There's a common code smell involving long methods with the most common answer being that methods should be really small, less than 50 lines per say (or 20). I understand why this is because it ...